file_id
int64
1
46.7k
content
stringlengths
14
344k
repo
stringlengths
7
109
path
stringlengths
8
171
888
package gr.cti.eslate.database.engine; import java.util.ListResourceBundle; public class DBResourceBundle_el_GR extends ListResourceBundle { public Object [][] getContents() { return contents; } static final Object[][] contents={ {"Error", "Λάθος"}, {"Warning", "Προειδοποίηση"}, {"Integer", "Ακέραιος"}, {"Float", "Float"}, {"Alphanumeric", "Αλφαριθμητικός"}, {"Number", "Αριθμός"}, {"Double", "Αριθμός"}, {"Image", "Εικόνα"}, {"URL", "URL"}, {"Boolean", "Αληθές/Ψευδές"}, {"Date", "Ημερομηνία"}, {"Time", "Ώρα"}, {"IntegerAit", "Ακέραιο"}, {"AlphanumericAit", "Αλφαριθμητικό"}, {"NumberAit", "Αριθμό"}, {"DoubleAit", "Αριθμό"}, {"Error", "Λάθος"}, {"Yes", "Ναί"}, {"No", "Όχι"}, {"Cancel", "Άκυρο"}, {"AND", "και"}, {"and", "και"}, {"OR", "ή"}, {"or", "ή"}, {"NOT", "όχι"}, {"not", "όχι"}, {"CONTAINS", "περιέχει"}, {"Contains", "περιέχει"}, {"contains", "περιέχει"}, {"CONTAINED", "περιέχεται"}, {"Contained", "περιέχεται"}, {"contained", "περιέχεται"}, {"true", "Αληθές"}, {"false", "Ψευδές"}, {"CDatabaseMsg1", "Δεν είναι δυνατό το άνοιγμα του αρχείου βάσης \""}, {"CDatabaseMsg2", "Δεν είναι δυνατό το άνοιγμα του αρχείου πίνακα \""}, {"CDatabaseMsg3", "\". Πιθανώς το αρχείο έχει βλάβη"}, {"CDatabaseMsg4", "Η βάση δεδομένων είναι ήδη ανοικτή"}, {"CDatabaseMsg5", "\". Θέλετε να ανοίξει το αρχείο \""}, {"CDatabaseMsg6", "\". Θέλετε να εντοπίσετε το αρχείο μόνοι σας;"}, {"CDatabaseMsg7", "\", αντ' αυτού?"}, {"CDatabaseMsg8", "Άνοιγμα πίνακα"}, {"CDatabaseMsg9", "\". Πιθανώς το αρχείο έχει βλάβη"}, {"CDatabaseMsg11", "Λάθος: ο πίνακας δεν προστέθηκε στη βάση δεδομένων, διότι δεν ανήκει σε αυτή"}, {"CDatabaseMsg12", "Δεν υποδείξατε όνομα αρχείου"}, {"CDatabaseMsg13", "Ο κατάλογος "}, {"CDatabaseMsg14", " δέν υπάρχει"}, {"CDatabaseMsg15", " δεν είναι κατάλογος"}, {"CDatabaseMsg16", "Λάθος όνομα αρχείου \""}, {"CDatabaseMsg17", "Το αρχείο \""}, {"CDatabaseMsg18", "\" δεν υπάρχει"}, {"CDatabaseMsg19", "Ο χαρακτήρας '"}, {"CDatabaseMsg20", "' δεν υποστηρίζεται ως διαχωριστής πεδίων"}, {"CDatabaseMsg21", "Δεν είναι δυνατή η ανάγνωση του αρχείου κειμένου \""}, {"CDatabaseMsg22", "\" είναι άδειο!"}, {"CDatabaseMsg23", "\" περιέχει μηδενικό όνομα πεδίου"}, {"CDatabaseMsg24", "\" περιέχει άκυρο όνομα πεδίου ή το ίδιο όνομα πεδίου περισσότερες από μία φορές"}, {"CDatabaseMsg26", "Άκυρο αρχείο. Αδύνατη η επεξεργασία της εγγραφής #"}, {"CDatabaseMsg28", "Άκυρο αρχείο \""}, {"CDatabaseMsg29", "\". Η εγγραφή #"}, {"CDatabaseMsg30", " περιέχει περισσότερα πεδία από τα πεδία του πίνακα(="}, {"CDatabaseMsg31", "Δεν είναι δυνατό το κλείσιμο του αρχείου κειμένου \""}, {"CDatabaseMsg32", "Δεν είναι δυνατό το άνοιγμα του αρχείου \""}, {"CDatabaseMsg33", "\". Πιθανώς η διαδρομή ή το όνομα του αρχείου δεν είναι σωστά"}, {"CDatabaseMsg34", "Δεν είναι δυνατό το κλείσιμο του αρχείου \""}, {"CDatabaseMsg35", "Αποθήκευση βάσης δεδομένων "}, {"CDatabaseMsg36", "Αδύνατη η αποθήκευση της βάσης δεδομένων \""}, {"CDatabaseMsg37", "\" στο αρχείο \""}, {"CDatabaseMsg38", "Θέλετε να αποθηκευτούν οι αλλαγές που έγιναν στον πίνακα \""}, {"CDatabaseMsg39", "\" ;"}, {"CDatabaseMsg40", "Αποθήκευση πίνακα"}, {"CDatabaseMsg41", "Θέλετε να αποθηκευτούν οι αλλαγές που έγιναν στη βάση δεδομένων \""}, {"CDatabaseMsg42", "Αποθήκευση βάσης δεδομένων"}, {"CDatabaseMsg43", "Αδύνατη η αποθήκευση: Δεν μπορείτε να γράψετε το αρχείο \""}, {"CDatabaseMsg44", "Αποθήκευση πίνακα"}, {"CDatabaseMsg45", "Αδύνατο η εγγραφή του αρχείου. Το αρχείο \""}, {"CDatabaseMsg46", "\" είναι φορτωμένο στον πίνακα \""}, {"CDatabaseMsg47", "\" της βάσης δεδομένων"}, {"CDatabaseMsg48", "Αδύνατη η αποθήκευση του πίνακα \""}, {"CDatabaseMsg49", "\" στο αρχείο \""}, {"CDatabaseMsg50", "Θέλετε να επανέλθει ο πίνακας στην αρχική του κατάσταση;"}, {"CDatabaseMsg51", "Προσθήκη πίνακα"}, {"CDatabaseMsg52", "Αδύνατο το άνοιγμα του αρχείου \""}, {"CDatabaseMsg53", "\". Πιθανώς δεν είναι σωστό αρχείο πίνακα"}, {"CDatabaseMsg54", "Θέλετε να αποθηκευτεί ο πίνακας πριν κλείσει;"}, {"CDatabaseMsg55", "Αποθήκευση του πίνακα \""}, {"CDatabaseMsg56", "\" πριν κλείσει;"}, {"CDatabaseMsg58", "Θέλετε να γράφτεί το υπάρχον αρχείο;"}, {"CDatabaseMsg59", "Οι πίνακες \""}, {"CDatabaseMsg60", "\" και \""}, {"CDatabaseMsg61", "\" δεν έχουν κοινά πεδία"}, {"CDatabaseMsg62", "Τα κοινά πεδία των πινάκων \""}, {"CDatabaseMsg63", "\" είναι τύπου \"Ήχος\". Δεν είναι δυνατή η σύνδεση πινάκων πάνω σε πεδία τύπου \"Ήχου\""}, {"CDatabaseMsg64", "Σύνδεση("}, {"CDatabaseMsg65", "Δεν προσδιορίστηκαν πεδία για τον πίνακα \""}, {"CDatabaseMsg66", "Δεν προσδιορίστηκαν τελεστές"}, {"CDatabaseMsg67", "Πρέπει να δοθεί ίσος αριθμός πεδίων και από τους δύο πίνακες"}, {"CDatabaseMsg68", "Δόθηκαν λιγότεροι τελεστές απ'ότι ονόματα πεδίων ή το αντίστροφο"}, {"CDatabaseMsg69", "Ο πίνακας \""}, {"CDatabaseMsg70", "\" είναι άδειος!"}, {"CDatabaseMsg71", "Δεν προσδιορίστηκε πεδίο"}, {"CDatabaseMsg72", "Δεν προσδιορίστηκε τελεστής"}, {"CDatabaseMsg73", "Λάθος τύπος δεδομένων παραμέτρου εισόδου"}, {"CDatabaseMsg74", "Το πεδίο \""}, {"CDatabaseMsg75", "\" δεν υπάρχει στον πίνακα "}, {"CDatabaseMsg76", "Τα πεδία "}, {"CDatabaseMsg77", " και "}, {"CDatabaseMsg78", " δεν έχουν συμβατούς τύπους δεδομένων"}, {"CDatabaseMsg79", "Ο τελεστής \""}, {"CDatabaseMsg80", "\" δεν μπορεί να χρησιμοποιηθεί σε "}, {"CDatabaseMsg81", " πεδία"}, {"CDatabaseMsg82", "Υπό συνθήκη σύνδεση("}, {"CDatabaseMsg83", "\" δεν είναι ταυτόσημοι στη δομή τους"}, {"CDatabaseMsg84", "Τα πεδία \""}, {"CDatabaseMsg85", "\" δεν έχουν το ίδιο τύπο δεδομένων"}, {"CDatabaseMsg86", "Δεν είναι δυνατή η τομή πινάκων που περιέχουν μόνο πεδία τύπου \"Εικόνας\""}, {"CDatabaseMsg87", "Τομή("}, {"CDatabaseMsg88", "Ένωση("}, {"CDatabaseMsg89", "Αδύνατη η προσθήκη του πίνακα στη βάση δεδομένων. "}, {"CDatabaseMsg90", "Άτιτλος"}, {"CDatabaseMsg91", "Παράμετρος χωρίς τιμή δόθηκε"}, {"CDatabaseMsg92", "Ο πίνακας δεν έχει τίτλο"}, {"CDatabaseMsg93", "Η βάση δεδομένων είναι υπό προστασία από το χρήστη \""}, {"CDatabaseMsg94", "\". Δεν είναι δυνατή η προσθήκη πίνακα σε αυτή."}, {"CDatabaseMsg95", "\". Δεν είναι δυνατή η αφαίρεση πίνακα από αυτή."}, {"CDatabaseMsg96", "\". Δεν είναι δυνατή η εξαγωγή πίνακα από αυτή."}, {"CDatabaseMsg97", "Δεν είναι δυνατό το άνοιγμα της βάσης"}, {"CDatabaseMsg98", "Ο τίτλος \""}, {"CDatabaseMsg99", "\" ανήκει ήδη σε άλλο πίνακα της βάσης"}, {"CDatabaseMsg100", "Πίνακας"}, {"CDatabaseMsg101", "Η προσθήκη εγγραφών δεν μπορεί να (απ)ενερογοποιηθεί για τον πίνακα \""}, {"CDatabaseMsg102", "Η διαγραφή εγγραφών δεν μπορεί να (απ)ενερογοποιηθεί για τον πίνακα \""}, {"CDatabaseMsg103", "Η προσθήκη πεδίων δεν μπορεί να (απ)ενερογοποιηθεί για τον πίνακα \""}, {"CDatabaseMsg104", "Η διαγραφή πεδίων δεν μπορεί να (απ)ενερογοποιηθεί για τον πίνακα \""}, {"CDatabaseMsg105", "Η αναδιάταξη πεδίων δεν μπορεί να (απ)ενερογοποιηθεί για τον πίνακα \""}, {"CDatabaseMsg106", "Η αλλαγή κλειδιού δεν μπορεί να (απ)ενερογοποιηθεί για τον πίνακα \""}, {"CDatabaseMsg107", "Η ορατότητα των πεδίων δεν μπορεί να (απ)ενερογοποιηθεί για τον πίνακα \""}, {"CDatabaseMsg108", "Η μεταβλητότητα των δεδομένων δεν μπορεί να (απ)ενερογοποιηθεί για τον πίνακα \""}, {"CDatabaseMsg109", "Η ορατότητα του πίνακα \""}, {"CDatabaseMsg110", "\" δεν μπορεί να (απ)ενερογοποιηθεί"}, {"CDatabaseMsg111", "Η μεταβλητότητα των δεδομένων του πεδίου \""}, {"CDatabaseMsg112", "\" του πίνακα \""}, {"CDatabaseMsg113", "Δεν είναι δυνατή η (απ)ενεργοποίηση της διαγραψιμότητας του πεδίου \""}, {"CDatabaseMsg114", "Δεν είναι δυνατή η (απ)ενεργοποίηση της μεταβολής τύπου του πεδίου \""}, {"CDatabaseMsg115", "Δεν είναι δυνατή η (απ)ενεργοποίηση της ιδιότητας 'Υπολογιζόμενο' του πεδίου \""}, {"CDatabaseMsg116", "Δεν είναι δυνατή η (απ)ενεργοποίηση της ιδιότητας 'Κλειδί' του πεδίου \""}, {"CDatabaseMsg117", "Δεν είναι δυνατή η (απ)ενεργοποίηση της ορατότητας του πεδίου \""}, {"CDatabaseMsg118", "Δεν είναι δυνατή η (απ)ενεργοποίηση της αλλαγής φόρμουλας του πεδίου \""}, {"CDatabaseMsg119", "Αδύνατη η αλλαγή ονόματος του πίνακα \""}, {"CDatabaseMsg120", "\". Το όνομα \""}, {"CDatabaseMsg121", "\" χρησιμοποιείται ήδη στη βάση δεδομένων \""}, {"CBooleanOperandExpressionMsg1", "Λάθος φόρμουλα \""}, {"CBooleanOperandExpressionMsg2", ". Ο αριθμός των αριστερών και δεξιών παρενθέσεων δεν ταιριάζει"}, {"CBooleanOperandExpressionMsg3", "Λάθος φόρμουλα. Δεν κλείνουν τα εισαγωγικά"}, {"CBooleanOperandExpressionMsg4", "Αδύνατος ο υπολογισμός της φόρμουλας: "}, {"CBooleanOperandExpressionMsg5", "\" δεν μπορεί να μετατραπεί σε \"Αληθές/Ψευδές\""}, {"CBooleanOperandExpressionMsg6", "Λάθος φόρμουλα. Άκυρος τελεστής \""}, {"CBooleanOperandExpressionMsg7", "Λάθος φόρμουλα \""}, {"CBooleanOperandExpressionMsg8", "\" . Δεν κλείνουν τα εισαγωγικά"}, {"CImageIconMsg1", "Δεν είναι δυνατή η δημιουργία της εικόνας. Το αρχείο \""}, {"CImageIconMsg2", "\" δεν υπάρχει"}, {"CDateOperandExpressionMsg1", "Λάθος φόρμουλα \""}, {"CDateOperandExpressionMsg2", "\". Τα αριθμητικά πεδία πρέπει να συνοδεύονται από ένα από τους χαρακτήρες 'd', 'm' or 'y' σε φόρμουλες υπολογιζόμενων πεδίων τύπου Ημερομηνία"}, {"CDateOperandExpressionMsg3", "\". Τα αριθμητικά πεδία πρέπει να συνοδεύονται από ένα από τους χαρακτήρες 'h' or 'm' σε φόρμουλες υπολογιζόμενων πεδίων τύπου Ώρα"}, {"CDateOperandExpressionMsg4", "\". Οι σταθερές τιμές σε φόρμουλες υπολογιζόμενων πεδίων τύπου Ημερομηνία πρέπει να έχουν τη μορφή <ακέραια_τιμή>x, όπου x ένας από τους {'d', 'm', 'y'} χαρακτήρες"}, {"CDateOperandExpressionMsg5", "Αδύνατος ο υπολογισμός της φόρμουλας \""}, {"CDateOperandExpressionMsg6", "\" δεν μπορεί να μετατραπεί σε Ώρα"}, {"CDateOperandExpressionMsg7", "\". Οι σταθερές τιμές σε φόρμουλες υπολογιζόμενων πεδίων τύπου Ώρα πρέπει να έχουν τη μορφή <ακέραια_τιμή>x, όπου x ένας από τους {'h', 'm'} χαρακτήρες"}, {"CDateOperandExpressionMsg8", "Λάθος φόρμουλα τύπου Ημερομηνίας \""}, {"CDateOperandExpressionMsg9", "Άκυρος τελεστής \""}, {"CDateOperandExpressionMsg10", "\". Δεν είναι δυνατή η πρόσθεση δύο τιμών τύπου Ημερομηνία/Ώρα"}, {"CDateOperandExpressionMsg11", "\". Δεν είναι δυνατή η προσθήκη των \""}, {"CDateOperandExpressionMsg12", "\" και \""}, {"CDateOperandExpressionMsg13", "Λάθος φόρμουλα"}, {"CDateOperandExpressionMsg14", "Δεν είναι δυνατή η πρόσθεση δύο τιμών τύπου Ημερομηνία/Ώρα"}, {"CDoubleNumberFormatMsg1", "\" δεν μπορεί να μετατραπεί σε Αριθμό"}, {"ElementaryLogicalExceptionMsg1", "Μη αποδεκτό τελεστέος: "}, {"ElementaryLogicalExceptionMsg2", "Λανθασμένη μορφή ημερομηνίας. Το '*' μπορεί να χρησιμοποιηθεί μόνο στη θέση ημερών, μηνών, και ετών και όχι μέσα σε αυτά"}, {"ElementaryLogicalExceptionMsg3", "Invalid type: \""}, {"ElementaryLogicalExceptionMsg4", "Λανθασμένη μορφή ώρας. Το '*' μπορεί να χρησιμοποιηθεί μόνο στη θέση λεπτών και ωρών και όχι μέσα σε αυτά"}, {"ElementaryLogicalExceptionMsg5", "Λάθος τελεστέος \""}, {"ElementaryLogicalExceptionMsg6", "\". Οι τελεσταίοι μορφής \"μάσκας\" χρησιμοποιούνται μόνο με το τελεστή \"=\""}, {"ElementaryLogicalExceptionMsg7", "Ο τελεστής \""}, {"ElementaryLogicalExceptionMsg8", "\" δε μπορεί να χρησιμοποιηθεί σε τύπου "}, {"ElementaryLogicalExceptionMsg9", " πεδία"}, {"FieldELEMsg1", "Τα πεδία τύπου URL \""}, {"FieldELEMsg2", "\" μπορεί να συγκριθεί μόνο με πεδία τύπου \"URL\" ή \"Αλφαριθμητικό\""}, {"FieldELEMsg3", "Μόνο πεδία τύπου \"Αριθμός\" or \"Ακέραιος\" μπορούν να συγκριθούν με το πεδίο \""}, {"FieldELEMsg4", "\" δεν μπορούν να συγκριθούν με άλλα πεδία"}, {"FieldELEMsg5", "Πεδία τύπου \"Εικόνας\" ή \"Ήχου\" δεν μπορούν να συγκριθούν με το πεδίο \""}, {"FieldELEMsg6", "Μόνο πεδία τύπου \"Ημερομηνία\" μπορούν να συγκριθούν με το πεδίο \""}, {"FieldELEMsg7", "Μόνο πεδία τύπου \"Ώρα\" μπορούν να συγκριθούν με το πεδίο \""}, {"LogicalExpressionMsg1", "Μη υποστηριζόμενος τρόπος επιλογής"}, {"LogicalExpressionMsg2", "Άκυρη διατύπωση ερώτησης. Δεν κλείνουν τα εισαγωγικά"}, {"LogicalExpressionMsg3", "Άκυρη διατύπωση ερώτησης. Οι παρενθέσεις δεν ταιριάζουν"}, {"ParenthesizedELEMsg1", "Άκυρη διατύπωση ερώτησης. Δεν κλείνουν τα εισαγωγικά"}, {"ParenthesizedELEMsg2", "Άκυρη διατύπωση ερώτησης"}, {"ParenthesizedELEMsg3", "Άκυρη διατύπωση ερώτησης. Απουσιάζει ο τελεστής"}, {"RecordMsg1", "Οι δείκτες εγγραφών δεν μπορεί να είναι αρνητικοί αριθμοί"}, {"CTableFieldMsg1", "Δεν είναι επιτρεπτή η αλλαγή της ιδιότητας \"Κλειδί\" του πεδίου"}, {"CTableFieldMsg2", "Δεν είναι επιτρεπτή η αλλαγή του τύπου του πεδίου"}, {"CTableFieldMsg3", "Δεν είναι επιτρεπτή η αλλαγή της ιδιότητας \"Μεταβαλλόμενο\" του πεδίου"}, {"CTableFieldMsg4", "Δεν είναι επιτρεπτή η αλλαγή της ιδιότητας \"Διαγράψιμο\" του πεδίου"}, {"CTableFieldMsg5", "Δεν είναι επιτρεπτή η μετατροπή του πεδίου σε μη-υπολογιζόμενο"}, {"CTableFieldMsg6", "Δεν είναι επιτρεπτή η μεταβολή τη ιδιότητας \"Κρυφό\" του πεδίου"}, {"CTableFieldMsg7", "Δεν είναι επιτρεπτή η αλλαγή της φόρμουλας του υπολογιζόμενου πεδίου"}, {"Database1", ". Η βάση δεδομένων \""}, {"DBLocked", "\" είναι κλειδωμένη."}, {"Database", "Βάση Δεδομένων"}, {"Table", "Πίνακας"}, {"ImportTable", "Εισαγωγή πίνακα"}, {"SaveDB", "H βάση δεδομένων έχει αλλάξει. Θέλετε να αποθηκεύσετε τις αλλαγές;"}, {"WarnClose", "Προσοχή! Η ψηφίδα Βάση Δεδομένων κλείνει..."}, {"ConstructorTimer", "Κατασκευή βάσης"}, {"LoadTimer", "Ανάκτηση βάσης"}, {"SaveTimer", "Αποθήκευση βάσης"}, {"InitESlateAspectTimer", "Κατασκευή αβακιακής πλευράς βάσης"}, {"FieldMapTimer", "Ανάκτηση FieldMap βάσης"}, }; }
vpapakir/myeslate
widgetESlate/src/gr/cti/eslate/database/engine/DBResourceBundle_el_GR.java
889
import java.util.ArrayList; import java.io.Serializable; /** Κλάση που αναπαριστά ένα ορθογώνιο */ public class Rectangle implements Serializable { private double min_x; private double max_x; private double min_y; private double max_y; /** * Κατασκευαστής της κλάσης με 4 ορίσματα */ public Rectangle(double x1, double x2, double y1, double y2){ this.min_x =x1; this.max_x =x2; this.min_y =y1; this.max_y =y2; } /** * Μέθοδος που επιστρέφει και τις 4 τιμές του ορθογωνίου * σε μία λίστα 4ων κελιών */ public ArrayList<Double> getAllValues(){ ArrayList<Double> values = new ArrayList<>(4); values.add(min_x); values.add(max_x); values.add(min_y); values.add(max_y); return values; } public double getMin_x(){ return min_x; } public double getMax_x(){ return max_x; } public double getMin_y(){ return min_y; } public double getMax_y(){ return max_y; } /** * Μέθοδος υπολογισμού εμβαδού του MBR */ public double getArea(){ return (max_x - min_x) * (max_y - min_y); } /** * Μέθοδος υπολογισμού της περιμέτρου του MBR */ public double getPerimeter(){ return 2 * (max_x - min_x) + 2 * (max_y - min_y); } /** * Μέθοδος που υπολογίζει την επικάλυψη που υπάρχει μεταξύ δύο ορθογωνίων */ public double calculate_overlap(Rectangle second_rectangle){ double x1 = second_rectangle.getMin_x(); double x2 = second_rectangle.getMax_x(); double y1 = second_rectangle.getMin_y(); double y2 = second_rectangle.getMax_y(); double overlap_x = Math.max(0,Math.min(max_x,x2)- Math.max(min_x,x1)); double overlap_y = Math.max(0,Math.min(max_y,y2)-Math.max(min_y,y1)); if(overlap_x == 0){ return overlap_y; } if(overlap_y == 0){ return overlap_x; } return overlap_x * overlap_y; } /** * Η μέθοδος αυτή υπολογίζει την επέκταση του ορθογωνίου έπειτα από την προσθήκη του σημείου (x,y) * @param x η τιμή του x του προστιθέμενου σημείου * @param y η τιμή του y του προστιθέμενου σημείου */ public double calculate_new_area(double x, double y){ if(min_x <= x && x <= max_x && y > max_y){ return (max_x - min_x) * (y- min_y); } else if(min_y <= y && y <= max_y && x > max_x){ return (x - min_x) * (max_y - min_y); } else if(min_x <= x && x <= max_x && y < min_y){ return (max_x - min_x) * (max_y - y); } else if(min_y <= y && y <= max_y && x < min_x){ return (max_x - x) * (max_y - min_y); } else if(x < min_x && y > max_y){ return (max_x - x) * (y - min_y); } else if(x > max_x && y > max_y){ return (x - min_x) * (y - min_y); } else if(x > max_x && y < min_y){ return (x - min_x) * (max_y - y); } else if(x < min_x && y < min_y){ return (max_x - x) * (max_y - y); } else if(x >= min_x && x <= max_x && y >= min_y && y <= max_y){ return (max_x - min_x) * (max_y - min_y); } else { System.out.println("Error in calculating area"); return -1; } } /** * Μέθοδος που προσθέτει ένα καινούργιο σημείο σε ένα ορθογώνιο και αλλάζει τις τιμές min_x, max_x, min_y, max_y * @param x η τιμή του άξονα x του σημείου που θέλουμε να προσθέσουμε * @param y η τιμή του άξονα y του σημείου που θέλουμε να προσθέσουμε */ public void setNewDimensions(double x, double y){ if(min_x == Double.MAX_VALUE && max_x == Double.MIN_VALUE && min_y == Double.MAX_VALUE && max_y == Double.MIN_VALUE){ min_x = x; min_y = y; max_x = x; max_y = y; return; } if(min_x <= x && x <= max_x && y > max_y) max_y = y; else if(min_y <= y && y <= max_y && x < min_x) min_x = x; else if(min_x <= x && x <= max_x && y < min_y) min_y = y; else if(min_y <= y && y <= max_y && x > max_x) max_x = x; else if(x < min_x && y > max_y){ min_x = x; max_y = y; }else if(x > max_x && y < min_y){ max_x = x; min_y = y; }else if(x > max_x && y > max_y){ max_x = x; max_y = y; } else if(x < min_x && y < min_y){ min_x = x; min_y = y; } else if(x <= max_x && x >= min_x && y >= min_y && y <= max_y){ } else System.out.println("Error in setting dimensions"); } /** * Μέθοδος που αναπροσαρμόζει τις τιμές ενός ορθογωνίου όταν προστεθεί σε αυτό ένας επιπλέον κόμβος * @param x1 η μικρότερη τιμή στον άξονα των x * @param x2 η μεγαλύτερη τιμή στον άξονα των x * @param y1 η μικρότερη τιμή στον άξονα των y * @param y2 η μεγαλύτερη τιμή στον άξονα των y */ public void setNewDimensions(double x1, double x2, double y1, double y2){ if(min_x == Double.MAX_VALUE && max_x == Double.MIN_VALUE && min_y == Double.MAX_VALUE && max_y == Double.MIN_VALUE){ min_x = x1; max_x = x2; min_y = y1; max_y = y2; return; } if(x1 < min_x){ min_x = x1; } if(x2 > max_x){ max_x = x2; } if(y1 < min_y){ min_y = y1; } if(y2 > max_y){ max_y = y2; } } /** * Μέθοδος που υπολογίζει την απόσταση μεταξύ ενός σημείου και ενός ορθογωνίου * @param point σημείο που θέλουμε να μετρήσουμε πόσο μακριά είναι από ένα ορθογώνιο */ public double distance_between_point_and_MBR(Point point){ double x = point.getLat(); double y = point.getLon(); if(min_x <= x && x <= max_x && y > max_y){ return y - max_y; } else if(min_y <= y && y <= max_y && x > max_x){ return x - max_x; } else if(min_x <= x && x <= max_x && y < min_y){ return min_y - y; } else if(min_y <= y && y <= max_y && x < min_x){ return min_x - x; } else if(x < min_x && y > max_y){ return Math.abs(min_x - x) + Math.abs(max_y - y); } else if(x > max_x && y > max_y){ return Math.abs(max_x - x) + Math.abs(max_y - y); } else if(x > max_x && y < min_y){ return Math.abs(max_x - x) + Math.abs(min_y - y); } else if(x < min_x && y < min_y){ return Math.abs(min_x - x) + Math.abs(min_y - y); } return 0; } }
NikosVogiatzis/UniProjects
java Rstartree/Rstartree/Rtree/src/Rectangle.java
890
package gr.cti.eslate.base.container; import java.util.ListResourceBundle; /** * User: yiorgos * Date: 17 Δεκ 2007 * Time: 11:52:53 πμ */ public class ContainerBundle_el_GR extends ListResourceBundle { public Object [][] getContents() { return contents; } static final Object[][] contents={ {"ESlate", "Αβάκιο"}, {"Yes", "Ναι"}, {"No", "Όχι"}, {"Cancel", "Άκυρο"}, {"MicroworldMenu", "Μικρόκοσμος"}, {"MicroworldNew", "Νέος"}, {"MicroworldLoad", "Άνοιγμα"}, {"MicroworldLoadLocal", "Άνοιγμα τοπικού μικρόκοσμου..."}, {"MicroworldLoadRemote", "Άνοιγμα απομακρυσμένου μικρόκοσμου..."}, {"MicroworldReopen", "Άνοιγμα εκ νέου"}, {"MicroworldNavigate", "Πλοήγηση"}, {"MicroworldBack", "Προηγούμενος"}, {"MicroworldForward", "Επόμενος"}, {"MicroworldHistory", "Ιστορία..."}, {"MicroworldSave", "Αποθήκευση"}, {"MicroworldSaveAs", "Αποθήκευση ως"}, {"MicroworldSaveAsLocal", "Αποθήκευση τοπικού μικρόκοσμου..."}, {"MicroworldSaveAsRemote","Αποθήκευση απομακρυσμένου μικρόκοσμου..."}, {"MicroworldRemoveAll", "Αφαίρεση ψηφίδων"}, {"MicroworldClose", "Κλείσιμο"}, {"MicroworldRename", "Αλλαγή τίτλου..."}, {"MicroworldNewView", "Νέα όψη"}, {"MicroworldViewMenu", "Όψεις"}, {"MicroworldPageSetup", "Διαμόρφωση σελίδας..."}, {"Print", "Εκτύπωση"}, {"PrintPrinter", "Εκτυπωτής..."}, {"PrintPDF", "PDF αρχείο..."}, {"PrintRTF", "RTF αρχείο..."}, {"PrintFile", "Αρχείο..."}, {"MicroworldPack", "Πακετάρισμα"}, {"MicroworldPackUp", "Πάνω πλευρά"}, {"MicroworldPackDown", "Κάτω πλευρά"}, {"MicroworldPackLeft", "Αριστερή πλευρά"}, {"MicroworldPackRight", "Δεξιά πλευρά"}, {"MicroworldPackAll", "Όλες τις πλευρές"}, {"MicroworldFTP", "Ανταλλαγή αρχείων..."}, {"MicroworldExit", "Έξοδος"}, {"MicroworldProperties", "Ιδιότητες..."}, // {"MicroworldInterface", "Εμφάνιση..."}, {"MicroworldLayers", "Επίπεδα..."}, {"MicroworldComponentLayers", "Επίπεδα ψηφίδων..."}, {"ComponentMenu", "Ψηφίδα"}, {"ComponentNew", "Νέα"}, {"ComponentCut", "Αποκοπή"}, {"ComponentCopy", "Αντιγραφή"}, {"ComponentPaste", "Επικόλληση"}, {"ComponentRemove", "Αφαίρεση"}, {"ComponentRename", "Αλλαγή ονόματος..."}, {"ComponentSave", "Αποθήκευση..."}, {"ComponentLoad", "Ανάκτηση..."}, {"InvisibleComponentRename", "Αλλαγή ονόματος"}, {"ComponentPrint", "Εκτύπωση..."}, {"ComponentSettings", "Ρυθμίσεις..."}, {"ComponentCustomizer", "Προσαρμοστής..."}, {"ComponentHelp", "Βοήθεια"}, {"ComponentAbout", "Περί της ψηφίδας"}, {"ComponentResizable", "Μεταβαλλόμενο μέγεθος"}, {"ComponentFrozen", "Παγιωμένη"}, {"ComponentActivatableByMousePress", "Ενεργοποίηση με click"}, {"FrameTitleDisplayed", "Μπάρα ψηφίδας ορατή"}, {"ComponentBarProperties","Ρυθμίσεις μπάρας"}, {"MinimizeVisible", "Πλήκτρο 'Απόκρυψη' ορατό"}, {"MaximizeVisible", "Πλήκτρο 'Μεγιστοποίηση' ορατό"}, {"CloseVisible", "Πλήκτρο 'Διαγραφή' ορατό"}, {"PlugVisible", "Πλήκτρο 'Σύνδεσμοι' ορατό"}, {"HelpVisible", "Πλήκτρο 'Βοήθεια' ορατό"}, {"InfoVisible", "Πλήκτρο 'Πληροφορίες' ορατό"}, {"ComponentNameChangeableFromMenuBar", "Επιτρέπεται η αλλαγή ονόματος"}, {"ComponentNameChangeable", "Δυνατότητα αλλαγής ονόματος"}, {"Components", "Ψηφίδες"}, {"PreferencesMenu", "Εργαλεία"}, // {"PreferencesFreeze", "Παγίωση"}, {"ShowComponentBarMI", "Γραμμή εργασίας"}, {"PreferencesContainer", "Ρυθμίσεις Αβακίου..."}, {"PinView", "Διαχείριση συνδέσμων..."}, {"ComponentEditor", "Διαχείριση ψηφίδων..."}, {"ViewEditor", "Διαχείριση όψεων..."}, {"PerformanceMonitor", "Μέτρηση απόδοσης μικρόκοσμου"}, {"PerformanceMonitorStart", "Έναρξη"}, {"PerformanceMonitorStop", "Παύση"}, {"PerformanceMonitorEdit", "Διαχείριση..."}, {"MicroworldHelpMgmt", "Bοήθεια μικρόκοσμου"}, {"MicroworldHelpCreate", "Δημιουργία..."}, {"MicroworldHelpEdit", "Διαχείριση..."}, {"MicroworldHelpClear", "Καθαρισμός"}, // {"EventEditor", "Διαχείριση γεγονότων..."}, // {"ArrangeWindows", "Τακτοποίηση παραθύρων"}, {"PreferencesGrid", "Πλέγμα..."}, {"PreferencesL&F", "Θέμα περιβάλλοντος"}, {"PreferencesConsolesEnabled", "Χρήση κονσολών"}, {"PreferencesConsoles", "Κονσόλες..."}, {"PreferencesLogoConsole","Logo κονσόλα..."}, {"HelpMenu", "Βοήθεια"}, {"ESlateHelp", "Αβάκιο"}, {"AboutESlate", "Περί του Αβακίου"}, {"MicroworldHelp", "Μικρόκοσμος"}, {"Component", "Η ψηφίδα"}, {"Error", "Λάθος"}, {"Warning", "Προειδοποίηση"}, {"Info", "Πληροφορία"}, {"ContainerMsg1", " δεν είναι γνωστή στο Αβάκιο"}, {"ContainerMsg2", "Δεν είναι δυνατή η δημιουργία ψηφίδας τύπου "}, {"ContainerMsg3", "Ο constuctor της ψηφίδας πετάει το exception: "}, {"ContainerMsg4", " διότι πρόκειται είτε για abstract κλάση είτε για interface"}, {"ContainerMsg5", ". Δεν είναι επιτρεπτή η πρόσβαση στο άνευ παραμέτρων constructor"}, {"ContainerMsg6", ". Πρόβλημα: "}, {"ContainerMsg7", "Αποθήκευση μικρόκοσμου"}, {"ContainerMsg8", "Ανάκτηση μικρόκοσμου"}, {"ContainerMsg9", "Άκυρη μορφή διεύθυνσης "}, {"ContainerMsg10", "Παρακαλώ περιμένετε..."}, {"ContainerMsg11", "Αποτυχία αποθήκευσης μικρόκοσμου λόγω σφάλματος δικτύου"}, {"ContainerMsg12", "Αποτυχία ανοίγματος μικρόκοσμου λόγω σφάλματος δικτύου"}, {"ContainerMsg13", "Λάθος URL \""}, {"ContainerMsg14", "Άγνωστος ή μη διαθέσιμος δικτυακός τόπος \""}, {"ContainerMsg15", "Αδυναμία επαφής με τον δικτυακό τόπο \""}, {"ContainerMsg16", "Σφάλμα κατά την αποθήκευση του μικρόκοσμου στο αρχείο \""}, {"ContainerMsg17", "Σφάλμα κατά τo άνοιγμα του αρχείου μικρόκοσμου \""}, {"ContainerMsg18", "Αδύνατη η μεταφορά και αποθήκευση του αρχείου λόγω μεγάλου μεγέθους"}, {"ContainerMsg19", "Θέλετε να αποθηκευτεί ο μικρόκοσμος"}, {"ContainerMsg20", "Αποθήκευση μικρόκοσμου"}, {"ContainerMsg21", "Αλλαγή ονόματος ψηφίδας"}, {"ContainerMsg22", "Όνομα ψηφίδας"}, {"ContainerMsg23", "Αλλαγή τίτλου μικρόκοσμου"}, {"ContainerMsg24", "Τίτλος μικρόκοσμου"}, {"ContainerMsg25", " δεν μπορεί να δημιουργηθεί από το αρχείο στο οποίο αποθηκεύτηκε"}, {"ContainerMsg26", "Σφάλμα κατά την αποθήκευση του μικρόκοσμου."}, {"ContainerMsg27", "Eπαναφορά της αποθηκευμένης κατάστασης του μικρόκοσμου:\n \""}, {"ContainerMsg28", "Είστε σίγουροι ότι θέλετε να αφαιρέσετε όλες τις ψηφίδες του μικρόκοσμου;"}, {"ContainerMsg29", "Αφαίρεση ψηφίδων"}, {"ContainerMsg30", "Είστε σίγουροι ότι θέλετε να αφαιρέσετε την ψηφίδα \""}, {"ContainerMsg31", "Αφαίρεση ψηφίδας"}, {"ContainerMsg32", "\";"}, {"ContainerMsg33", "Πρόβλημα κατά το κλείσιμο της ψηφίδας"}, {"ContainerMsg34", "Έγινε προσπάθεια αντιμετώπισής του... "}, {"ContainerMsg35", "Πρόβλημα κατά την απόρριψη του handle της ψηφίδας"}, {"ContainerMsg36", "Δεν ήταν δυνατή η ολοκλήρωση της διαδικασίας εκτύπωσης"}, {"ContainerMsg37", "Δεν στάθηκε δυνατή η φωτογράφηση της ψηφίδας"}, {"ContainerMsg38", "Επιλογή PDF αρχείου"}, {"ContainerMsg39", "Επιλογή RTF αρχείου"}, {"ContainerMsg40", "Το αρχείο"}, {"ContainerMsg41", "δεν υπάρχει"}, {"ContainerMsg42", "Μη αποκαταστάσιμο σφάλμα κατά το άνοιγμα του αρχείου μικρόκοσμου \""}, {"ContainerMsg43", "Καταγράφηκε νέα όψη με το όνομα \""}, {"ContainerMsg44", "\""}, {"ContainerMsg45", " Το αρχείο δεν είναι εγγράψιμο."}, {"ContainerMsg46", "Δεν είναι εκκίνηση της ψηφίδας"}, {"ContainerMsg47", "Δεν υπάρχει εγκατεστημένο θέμα περιβάλλοντος με όνομα "}, {"ContainerMsg48", "Άγνωστη κλάση θέματος περιβάλλοντος "}, {"ContainerMsg49", "Δεν στάθηκε δυνατή η ενεργοποίηση του θέματος περιβάλλοντος "}, {"ContainerMsg50", "Το θέμα περιβάλλοντος \""}, {"ContainerMsg51", "\" δεν υποστηρίζεται σε αυτή την πλατφόρμα"}, {"ContainerMsg52", "Στάθηκε αδύνατη η μεταφορά του απομακρυσμένου αρχείου"}, {"ContainerMsg53", "Δεν υπάρχει ψηφίδα με όνομα \""}, {"ContainerMsg54", "\" στον μικρόκοσμο."}, {"ContainerMsg55", "Η ψηφίδα \""}, {"ContainerMsg56", "\" δεν είναι δυνατό να εκτυπωθεί, διότι έχει αποκρυφτεί."}, {"ContainerMsg57", "Επιλέξτε το αρχείο στο οποίοθα γίνει η εκτύπωση"}, {"ContainerMsg58", "Δε στάθηκε δυνατή η πλήρης αποθήκευση των ήχων του μικρόκοσμου. Αδύνατη η δημιουργία καταλόγου ήχων στο αρχείο μικροκόσμου."}, {"ContainerMsg59", "Δε στάθηκε δυνατή η πλήρης αποθήκευση των ήχων του μικρόκοσμου."}, {"ContainerMsg60", "Κάποιοι ήχοι δεν αποθηκεύτηκαν στο αρχείο του μικρόκοσμου. Οι ήχοι αυτοί θα συνεχίσουν να χρησιμοποιούνται από τα εξωτερικά αρχεία τους."}, {"ContainerMsg61", "Λίστα ήχων που δεν αποθηκεύτηκαν"}, {"ContainerMsg62", "Δε στάθηκε δυνατή η αποθήκευση του θέματος ήχων στο αρχείο: \n\""}, {"ContainerMsg63", "Δε στάθηκε δυνατή η ανάγνωση του αρχείου ήχων του Αβακίου: \n\""}, {"ContainerMsg64", "Δεν στάθηκε δυνατό το παίξιμο του ήχου \""}, {"ContainerMsg65", "\" από το αρχείο θέματος ήχων: \n\""}, {"ContainerMsg66", "Αδύνατη η ανάθεση θέματος περιβάλλοντος στον μικροκόσμο.\nΆγνωστη κλάση θέματος περιβάλλοντος:\n"}, {"ContainerMsg67", "δεν μπορεί να αποθηκευτεί. Δεν είναι αποθηκεύσιμη ψηφίδα."}, {"ContainerMsg68", "δεν μπορεί να αποθηκευτεί. Πρόβλημα κατά την αποθήκευση της κατάστασης της ψηφίδας."}, {"ContainerMsg69", "Η κλάση"}, {"ContainerMsg70", "δεν υπάρχει στο classpath."}, {"ContainerMsg71", "Πρόβλημα κατά το φόρτωμα της κλάσης"}, {"ContainerMsg72", "έχει αλλάξει με μη συμβατό τρόπο."}, {"ContainerMsg73", "Η κλάση ενώ ήταν Externalizable, δεν είναι πια."}, {"ContainerMsg74", "Η κλάση ενώ ήταν Serializable, δεν είναι πια."}, {"ContainerMsg75", "Δεν στάθηκε δυνατή η αποκατάσταση της κατάστασης ψηφίδας της κλάσης"}, {"ContainerMsg76", "Δεν στάθηκε δυνατή η αποκατάσταση της Αβακιακής πλευράς της ψηφίδας"}, {"ContainerMsg77", "Παρουσιάστηκε πρόβλημα κατά την ανάκτηση ψηφίδας από το αρχείο"}, {"ContainerMsg78", "Η εισαχθείσα ψηφίδα"}, {"ContainerMsg79", "χρησιμοποιεί ήχους, οι οποίοι δεν μπόρεσαν να διαβαστούν, διότι ο μικρόκοσμος δεν έχει αποθηκευτεί ακόμη για πρώτη φορά."}, {"ContainerMsg80", "Αν θέλετε να εισαχθεί η ψηφίδα με τους ήχους της, πρέπει πρώτα να αποθηκεύσετε τον μικρόκοσμο και μετά να εισάγετε την ψηφίδα."}, {"ContainerMsg81", "δεν μπορεί να αντιγραφεί στο πρόχειρο. Παρουσιάστηκε πρόβλημα κατά την αντιγραφή της."}, {"ContainerMsg82", "Πρόβλημα κατά την επικόλληση ψηφίδας από το πρόχειρο."}, {"ContainerMsg83", "Το πρόχειρο του Αβακίου είναι άδειο."}, {"ContainerMsg84", "Το πρόχειρο του Αβακίου δεν περιέχει κάποια ψηφίδα."}, {"ContainerMsg85", "Δε στάθηκε δυνατή η σύνταξη της βοήθειας του μικρόκοσμου."}, {"ContainerMsg86", "To αρχειο του μικροκόσμου μπορεί να έχει καταστραφεί ως αποτέλεσμα του λάθους στην διαδικασία αποθήκευσης.\nΤο Αβάκιο έχει κρατήσει αντίγραφο του αρχείου του μικρόκοσμου από την τελευταία επιτυχημένη αποθήκευση.\nΘέλετε να αποκατασταθεί το αντιγραφό;"}, {"ContainerMsg87", "Το αντίγραφο ασφαλείας αποκαταστάθηκε στο αρχείο"}, {"ContainerMsg88", "Δεν στάθηκε δυνατή η αποκατάσταση του αντιγράφου ασφαλείας του μικρόκοσμου."}, {"ContainerMsg89", "Παρουσιάστηκε πρόβλημα κατά τη διαχείριση της βοήθειας του μικρόκοσμου."}, {"Quote", "\""}, {"LoadRemoteMwdMsg1", "Άνοιγμα απομακρυσμένου μικρόκοσμου"}, {"LoadRemoteMwdMsg2", "Web site"}, {"WebSiteLocalDirName", "Δικτυακοί τόποι"}, {"Restore", "Αποκατάσταση"}, {"Minimize", "Απόκρυψη"}, {"MinimizeAll", "Απόκρυψη όλων"}, {"BarOffAll", "Απόκρυψη μπαρών"}, {"BarOnAll", "Εμφάνιση μπαρών"}, {"Maximize", "Μεγιστοποίηση"}, {"Close", "Κλείσιμο"}, {"BarOff", "Μπάρα ορατή"}, {"OK", "Εντάξει"}, {"Cancel", "Άκυρο"}, {"Apply", "Εφαρμογή"}, {"ShowComponentBar", "Εμφάνιση μπάρας ψηφίδων"}, {"HideComponentBar", "Απόκρυψη μπάρας ψηφίδων"}, {"ESlateHelpTitle", "Βοήθεια Αβακίου"}, {"About", "Περί του Αβακίου"}, {"Customizer", "Προσαρμοστής"}, {"Customizer1", "Ο προσαρμοστής δεν είναι ορατός. Ένας χρήσιμος προσαρμοστής πρέπει οπωσδήποτε να είναι ορατός."}, {"Customizer2", "Ο συγκεκριμένος προσαρμοστής δεν υλοποιεί το \"java.beans.Customizer\" interface."}, {"Customizer3", "Αδύνατη η αρχικοποίηση του προσαρμοστή"}, {"ComponentEditorTitle", "Διαχείριση ψηφίδων"}, {"Loading1", "Αρχικοποίηση μικρόκοσμου..."}, {"Loading2", "Εκκίνηση ψηφίδας "}, {"Saving1", "Αποθήκευση μικρόκοσμου..."}, {"View", "Όψη"}, {"ViewDefined", "Καταγραφή όψης"}, {"Loading icons", "Ανάκτηση εικονιδίων ψηφίδων. Παρακαλώ περιμένετε..."}, {"ComponentPins", "Σύνδεσμοι"}, {"NativeL&F", "Τρέχουσας πλατφόρμας"}, {"JavaL&F", "Metal"}, {"Microworld", "Μικρόκοσμος"}, {"?", ";"}, ////nikosM {"OnServer", " στον "}, ////nikosM end {"PrintErrorMsg1", "Δεν στάθηκε δυνατή η εκτύπωση. Ο κατάλογος \"bin\" της εγκατάστασης του Αβακίου δεν υπάρχει."}, {"PrintErrorMsg2", "Δεν στάθηκε δυνατή η εκτύπωση. Το εκτελέσιμο αρχείο"}, {"PrintErrorMsg3", "δεν υπάρχει στον κατάλογο \"bin\" της εγκατάστασης του Αβακίου."}, {"ErrorSound", "Λάθος"}, {"InfoSound", "Ειδοποίηση"}, {"QuestionSound", "Ερώτηση"}, {"PlugSound", "Σύνδεση συνδέσμων"}, {"UnplugSound", "Αποσύνδεση συνδέσμων"}, {"StartSound", "Έναρξη Αβακίου"}, {"EndSound", "Κλείσιμο Αβακίου"}, {"ComponentNewSound", "Δημιουργία ψηφίδας"}, {"ComponentShownSound", "Εμφάνιση ψηφίδας"}, {"ComponentHiddenSound", "Απόκρυψη ψηφίδας"}, {"ComponentClosedSound", "Κλείσιμο ψηφίδας"}, {"MwdOpenedSound", "Άνοιγμα μικρόκοσμου"}, {"MwdClosedSound", "Κλείσιμο μικρόκοσμου"}, {"ViewChangedSound", "Αλλαγή όψης μικρόκοσμου"}, {"ComponentActivatedSound", "Ενεργοποίηση ψηφίδας"}, {"ComponentMaximizedSound", "Μεγιστοποίηση ψηφίδας"}, {"MicroworldLockedException", "O μικρόκοσμος είναι κλειδωμένος και δεν είναι δυνατή η αλλαγή των ρυθμίσεών του"}, {"Microworld current view", "Τρέχουσα όψη μικρόκοσμου"}, {"SaveComponent", "Αποθήκευση ψηφίδας"}, {"LoadComponent", "Ανάκτηση ψηφίδας"}, {"CreatingMwdBackup", "Δημιουργία αντιγράφου ασφαλείας μικρόκοσμου"}, {"BackupCopy", "ΑντίγραφοΜικρόκοσμου"}, {"MicroworldSaveTimer", "Aποθήκευση μικρόκοσμου"}, {"MicroworldLoadTimer", "Ανάκτηση μικρόκοσμου"}, {"MicroworldCloseTimer", "Κλείσιμο μικρόκοσμου"}, {"ViewSwitchTimer", "Αλλαγή όψης"}, {"MicroworldLoadGroup", "Ομάδα μετρητών φορτώματος μικρόκοσμου"}, {"FileReadTimer", "Ανάγνωση αρχείου μικρόκοσμου"}, {"ComponentInstantiationTimer", "Εκκίνηση ψηφίδων"}, {"HandleRegistrationTimer", "Registration handles ψηφίδων"}, {"FrameIconCreationTimer", "Δημιουργία παραθύρων και εικονιδίων"}, {"ScriptSoundLoadTimer", "Φόρτωμα scripts & ήχων"}, {"MwdPropertiesRestoreTimer", "Αποκατάσταση ιδιοτήτων μικροκόσμου"}, {"MwdLoadedListenerTimer", "Γεγονός ανοίγματος μικρόκοσμου"}, {"loadmwtip", "<html><strong>Πατήστε:</strong><ul><li>Ctrl+L, για να ανοίξετε ένα μικρόκοσμο που βρίσκεται στο PC σας</li><li>Ctrl+R, για να ανοίξετε ένα μικρόκοσμο που βρίσκεται σε απομακρυσμένο εξυπηρετητή</li></ul></html>"}, }; }
vpapakir/myeslate
widgetESlate/src/gr/cti/eslate/base/container/ContainerBundle_el_GR.java
892
/* LanguageTool, a natural language style checker * Copyright (C) 2005 Daniel Naber (http://www.danielnaber.de) * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 * USA */ package org.languagetool.rules.el; import org.languagetool.AnalyzedTokenReadings; import org.languagetool.Language; import org.languagetool.rules.Example; import org.languagetool.rules.WordRepeatBeginningRule; import java.util.*; import java.util.stream.*; /** * Adds a list Greek adverbs to {@link WordRepeatBeginningRule}. * * @author Georgios Sideris */ public class GreekWordRepeatBeginningRule extends WordRepeatBeginningRule { public GreekWordRepeatBeginningRule(ResourceBundle messages, Language language) { super(messages, language); addExamplePair(Example.wrong("Επίσης, παίζω ποδόσφαιρο. <marker>Επίσης</marker>, παίζω μπάσκετ."), Example.fixed("Επίσης, παίζω ποδόσφαιρο. <marker>Επιπλέον</marker>, παίζω μπάσκετ.")); } @Override public String getId() { return "GREEK_WORD_REPEAT_BEGINNING_RULE"; } //adverbs used to add to what the previous sentence mentioned (English example: Also) private static final Set<String> ADD_ADVERBS = new HashSet<>(); //adverbs used to express contrast to what the previous sentence mentioned (English example: Contrarily) private static final Set<String> CONTRAST_ADVERBS = new HashSet<>(); // adverbs used to explain what the previous sentence mentioned (English example: Specifically) private static final Set<String> EXPLAIN_ADVERBS = new HashSet<>(); static { ADD_ADVERBS.add("Επίσης"); ADD_ADVERBS.add("Επιπρόσθετα"); ADD_ADVERBS.add("Ακόμη"); ADD_ADVERBS.add("Επιπλέον"); ADD_ADVERBS.add("Συμπληρωματικά"); CONTRAST_ADVERBS.add("Αντίθετα"); CONTRAST_ADVERBS.add("Ωστόσο"); CONTRAST_ADVERBS.add("Εντούτοις"); CONTRAST_ADVERBS.add("Εξάλλου"); EXPLAIN_ADVERBS.add("Δηλαδή"); EXPLAIN_ADVERBS.add("Ειδικότερα"); EXPLAIN_ADVERBS.add("Ειδικά"); EXPLAIN_ADVERBS.add("Συγκεκριμένα"); } @Override public boolean isException(String token) { return super.isException(token) || token.equals("Ο") || token.equals("Η") || token.equals("Το") || token.equals("Οι")|| token.equals("Τα") || token.equals("Ένας") || token.equals("Μία") || token.equals("Ένα"); } @Override protected boolean isAdverb(AnalyzedTokenReadings token) { return ADD_ADVERBS.contains(token.getToken()) || CONTRAST_ADVERBS.contains(token.getToken()) || EXPLAIN_ADVERBS.contains(token.getToken()); } @Override protected List<String> getSuggestions(AnalyzedTokenReadings token) { String tok = token.getToken(); if (ADD_ADVERBS.contains(tok)) { return ADD_ADVERBS.stream() .filter(adv -> !adv.equals(tok)) .collect(Collectors.toList()); } else if (CONTRAST_ADVERBS.contains(tok)) { return CONTRAST_ADVERBS.stream() .filter(adv -> !adv.equals(tok)) .collect(Collectors.toList()); } else if (EXPLAIN_ADVERBS.contains(tok)) { return EXPLAIN_ADVERBS.stream() .filter(adv -> !adv.equals(tok)) .collect(Collectors.toList()); } return Collections.emptyList(); } }
Softcatala/languagetool
languagetool-language-modules/el/src/main/java/org/languagetool/rules/el/GreekWordRepeatBeginningRule.java
893
package com.example.eshop3; import androidx.annotation.NonNull; import androidx.room.ColumnInfo; import androidx.room.Entity; import androidx.room.ForeignKey; import androidx.room.PrimaryKey; /* Δημιορυγώ τον πίνακα Pwliseis με τις στήλες pwlid,pwl_onoma,posoA,posoB,posoC,posoD Κυριως κλειδι είναι ένας συνδιασμός όλων των στειλών του πίνακα. Το ξένο κλειδί βρίσκεται στη κλάση Pelates και κάνω αντιστόιχηση το pid εκείνης της κλάσης με το pwlid αυτης της κλασης., επισης εισάγωγω την onDelete και onUpdate.Cascade.Δηλαδή τι θα γίνει σε περίπτωση διαγρφής ή ενημέρωσης στον πίνακα Πελάτες */ @Entity (tableName = "pwliseis", primaryKeys = {"pwlid","pwl_onoma","posoA"}, foreignKeys = { @ForeignKey(entity = Pelates.class, parentColumns = "pid", childColumns = "pwlid", onDelete = ForeignKey.CASCADE, onUpdate = ForeignKey.CASCADE)}) public class Pwliseis { @ColumnInfo (name = "pwlid") @NonNull private int ppid; @ColumnInfo (name = "pwl_onoma") @NonNull private String onoma; @ColumnInfo (name = "posoA") private int posoA; @ColumnInfo (name = "posoB") private int posoB; @ColumnInfo (name = "posoC") private int posoC; @ColumnInfo (name = "posoD") private int posoD; public int getPpid() { return ppid; } public void setPpid(int ppid) { this.ppid = ppid; } public String getOnoma() { return onoma; } public void setOnoma(String onoma) { this.onoma = onoma; } public int getPosoA() { return posoA; } public void setPosoA(int posoA) { this.posoA = posoA; } public int getPosoB() { return posoB; } public void setPosoB(int posoB) { this.posoB = posoB; } public int getPosoC() { return posoC; } public void setPosoC(int posoC) { this.posoC = posoC; } public int getPosoD() { return posoD; } public void setPosoD(int posoD) { this.posoD = posoD; } }
EfthimisKele/E_Shop
app/src/main/java/com/example/eshop3/Pwliseis.java
894
package gr.aueb.softeng.view.Owner.RestaurantDetails; import gr.aueb.softeng.dao.RestaurantDAO; import gr.aueb.softeng.domain.Restaurant; public class RestaurantDetailsPresenter { private RestaurantDAO restaurantDAO; private Restaurant restaurant; private RestaurantDetailsView view; /** * Αρχικοποιεί το restaurant dao για να μπορούμε να αποθηκεύσουμε εστιατόρια και να τα ανακτήσουμε από την στατική μας λίστα * @param restaurantDAO Instance του DAO */ public RestaurantDetailsPresenter(RestaurantDAO restaurantDAO){ this.restaurantDAO = restaurantDAO; } /** * Αρχικοποιεί το view απο το οποίο θα χρησιμοποιήσουμε τις μεθόδους του interface του * @param v Instance του view */ public void setView(RestaurantDetailsView v) { this.view = v; } /** * Βρίσκει μέσω του μοναδικού id απο την λίστα με τα εστιατόρια του dao το αντικείμενο του εστιατορίου * που ψάχνουμε * @param restaurantId το id του εστιατορίου που θέλουμε να εμφανίσουμε τα στοιχεία του */ public void setRestaurant(int restaurantId) { restaurant = restaurantDAO.find(restaurantId); } /** * Καλεί τις μεθόδους του view που εμφανίζουν στην οθόνη τα στοιχεία του εστιατορίου */ public void setDetails(){ view.setRestName("Name: "+ restaurant.getRestaurantName()); view.setRestId("Id: "+String.valueOf(restaurant.getId())); view.setRestTables("Total tables: "+ String.valueOf(restaurant.getTotalTables())); view.setRestAddressStreet("Address Street: "+restaurant.getAddress().getStreetName()); view.setRestAddressNumber("Address Number: "+String.valueOf(restaurant.getAddress().getStreetNumber())); view.setRestAddressCity("Address City: "+restaurant.getAddress().getCity()); view.setRestZip("Address ZC: "+String.valueOf(restaurant.getAddress().getZipCode())); } /** * Καλείται για να εξάγει τα στατιστικά όταν πατηθεί το κουμπί εξαγωγής στατιστικών */ public void onExtractStats(){ view.extractStats(); } /** * Καλείται όταν θέλουμε να επιστρέψουμε στην αρχική οθόνη */ public void OnBack(){ view.goBack(); } /** * Καλείται για να προστεθεί ένας νέος μάγειρας όταν πατηθεί το κουμπί της εισαγωγής νέου μάγειρα απο τον ιδιοκτήτη */ public void onAddChef(){view.addChef();} public RestaurantDetailsView getView(){ return this.view; } public Restaurant getRestaurant(){ return this.restaurant; } }
vleft02/Restaurant-Application
app/src/main/java/gr/aueb/softeng/view/Owner/RestaurantDetails/RestaurantDetailsPresenter.java
895
package gr.cti.eslate.database.engine; import java.util.ListResourceBundle; public class CTableResourceBundle_el_GR extends ListResourceBundle { public Object [][] getContents() { return contents; } static final Object[][] contents={ {"Alphanumeric", "Αλφαριθμητικός"}, {"Number", "Αριθμός"}, {"Double", "Αριθμός"}, {"Image", "Εικόνα"}, {"URL", "URL"}, {"Boolean", "Αληθές/Ψευδές"}, {"Date", "Ημερομηνία"}, {"Time", "Ώρα"}, {"true", "Αληθές"}, {"false", "Ψευδές"}, {"CTableMsg1", "Δεν προσδιορίστηκε όνομα για το νέο πεδίο"}, {"CTableMsg2", "\" δεν εισήχθη. Υπάρχει άλλο πεδίο ορισμένο στον πίνακα με το ίδιο όνομα"}, {"CTableMsg3", "Δεν είναι δυνατή η προσθήκη πεδίου-κλειδιού σε μη άδειο πίνακα"}, {"CTableMsg4", "\" δεν ορίστηκε "}, {"CTableMsg5", "\" δεν ορίστηκε. Δεν είναι δυνατή η προσθήκη πεδίου-κλειδιού σε μη άδειο πίνακα"}, {"CTableMsg6", "Δεν είναι δυνατή η αλλαγή της φόρμουλας του πεδίου \""}, {"CTableMsg7", "\", επειδή το συγκεκριμένο πεδίο δεν υπάρχει"}, {"CTableMsg8", "Δεν προσδιορίσθηκε φόρμουλα για το πεδίο \""}, {"CTableMsg9", "Δεν βρέθηκε δεξιά αγκύλη(])"}, {"CTableMsg10", "Λάθος φόρμουλα \""}, {"CTableMsg11", "Μη σωστός ακέραιος αριθμός: "}, {"CTableMsg12", "Μη σωστός αριθμός: "}, {"CTableMsg13", "Μόνο πεδία τύπου \"Αριθμός\" ή \"Ακέραιος\" μπορούν να χρησιμοποιηθούν για τον υπολογισμό του πεδίου \""}, {"CTableMsg14", "\" έχει \""}, {"CTableMsg15", "\" τύπο"}, {"CTableMsg16", "Μόνο πεδία τύπου \"Αληθές/Ψευδές\" μπορούν να χρησιμοποιηθούν για τον υπολογισμό του πεδίου \""}, {"CTableMsg17", "Μόνο πεδία τύπου \"Ημερομηνία\" ή \"Ακέραιος\" ή \"Αριθμός\" μπορούν να χρησιμοποιηθούν για τον υπολογισμό του πεδίου \""}, {"CTableMsg18", "Μόνο πεδία τύπου \"Ώρα\" ή \"Ακέραιος\" μπορούν να χρησιμοποιηθούν για τον υπολογισμό του πεδίου \""}, {"CTableMsg19", "Πεδία τύπου \"Εικόνας\" ή \"Ήχου\" δεν μπορούν να χρησιμοποιηθούν για αναζήτηση στο πεδίο \""}, {"CTableMsg20", "Μη αποδεκτή πρόσθεση δύο τιμών τύπου Ημερομηνία/Ώρα"}, {"CTableMsg21", "Μόνο πεδία τύπου \"URL\" or \"Αλφαριθμητικό\" μπορούν να χρησιμοποιηθούν για τον υπολογισμό του πεδίου \""}, {"CTableMsg22", "Πεδία τύπου \"Εικόνας\" δεν μπορούν να χρησιμοποιηθούν σε φόρμουλες υπολογιζόμενων πεδίων"}, {"CTableMsg23", "Πεδία τύπου \""}, {"CTableMsg24", "\" δεν μπορούν να χρησιμοποιηθούν σε φόρμουλες υπολογιζόμενων πεδίων"}, {"CTableMsg25", "Η νέα φόρμουλα διαφοροποιεί τον τύπο του υπολογιζόμενου πεδίου. Υπάρχουν άλλα υπολογιζόμενα πεδία που εξαρτώνται από αυτό, τα οποία είναι δυνατό να αναιρέσει αυτά τα πεδία"}, {"CTableMsg26", "Ακύρωση αλλαγής κελλιού: Υπολογίστηκε μηδενική τιμή για το υπολογιζόμενο πεδίο \""}, {"CTableMsg27", "Ακύρωση αλλαγής κελλιού. Διπλή τιμή κλειδιού \""}, {"CTableMsg28", "\" για το υπολογιζόμενο πεδίο \""}, {"CTableMsg29", "Ακύρωση αλλαγής κελλιού. Διπλή URL τιμή κλειδιού \""}, {"CTableMsg30", "Μηδενική τιμή υπολογίστηκε για το πεδίο \""}, {"CTableMsg31", "Διπλή τιμή \""}, {"CTableMsg32", "Δεν προσδιορίστηκε όνομα πεδίου"}, {"CTableMsg33", "Δεν υπάρχει πεδίο με όνομα \""}, {"CTableMsg34", "\" δεν είναι διαγράψιμο"}, {"CTableMsg35", "Δεν είναι δυνατή η διαγραφή του πεδίου. Υπάρχουν υπολογιζόμενα πεδία στον πίνακα που εξαρτώνται από το συγκεκριμένο πεδίο"}, {"CTableMsg36", "Το πεδίο δεν μπορεί να διαγραφεί, διότι δεν είναι δυνατή η διαγραφή εγγραφών στον πίνακα. Το πεδίο είναι μέρος του κλειδιού του πίνακα, οπότε η διαγραφή του μπορεί να οδηγήσει στην διαγραφή εγγραφών"}, {"CTableMsg37", "Ακύρωση της εισαγωγής εγγραφής. Δεν μπορούν να προστεθούν εγγραφές από τον πίνακα"}, {"CTableMsg38", "Ακύρωση της εισαγωγής εγγραφής. Δεν έχουν οριστεί πεδία στον πίνακα!"}, {"CTableMsg39", "Η εγγραφή δεν είναι αποδεκτή: "}, {"CTableMsg40", ". Δεν είναι δυνατή η μετατροπή της σε Ημερομηνία"}, {"CTableMsg41", ". Δεν είναι δυνατή η μετατροπή της σε Ώρα"}, {"CTableMsg42", "Μη αποδεκτή τιμή \""}, {"CTableMsg43", "\". Δεν είναι δυνατή η μετρατροπή της σε "}, {"CTableMsg44", "Η εισαγωγή εγγραφής απέτυχε: \""}, {"CTableMsg45", "Η εισαγωγή της εγγραφής απέτυχε διότι το κλειδί της εγγραφής περιέχει μία ή περισσότερες μηδενικές τιμές"}, {"CTableMsg46", "Η εισαγωγή της εγγραφής απέτυχε διότι το κλειδί της ήδη υπάρχει"}, {"CTableMsg47", "Δεν είναι δυνατή η διαγραφή εγγραφών από τον πίνακα"}, {"CTableMsg48", "Άκυρος δείκτης εγγραφής: "}, {"CTableMsg49", "Δεν είναι δυνατή η προσθήκη εγγραφής σε πίνακα που περιέχει μη μεταβαλλόμενα πεδία κλειδιά, π.χ το πεδίο \""}, {"CTableMsg50", "Η εγγραφή αυτή είναι άκυρη"}, {"CTableMsg51", "Άκυρος δείκτης πεδίου"}, {"CTableMsg52", "Άκυρη διεύθυνση κελλιού. Δείκτης πεδίου: "}, {"CTableMsg53", ", δείκτης εγγραφής: "}, {"CTableMsg54", "Άκυρη διεύθυνση κελλιού. Όνομα πεδίου: "}, {"CTableMsg55", "Η εγγραφή "}, {"CTableMsg56", " ή το πεδίο "}, {"CTableMsg57", " δεν είναι έγκυρο"}, {"CTableMsg58", "Ακύρωση αλλαγής τιμής κελλιού: Δόθηκε μηδενική τιμή για κελλί του πεδίου \""}, {"CTableMsg59", "\", το οποίο ανήκει στο κλειδί του πίνακα"}, {"CTableMsg60", "Ακύρωση αλλαγής κελλιού. Η τιμή κειδιού \""}, {"CTableMsg61", "\" ήδη υπάρχει"}, {"CTableMsg62", "Το πεδίο δεν είναι έγκυρο"}, {"CTableMsg63", "Άκυρη διεύθυνση κελλιού. Το δοθέν CTableField δεν είναι έγκυρο"}, {"CTableMsg64", "Δόθηκε άκυρη εγγραφή"}, {"CTableMsg65", "Δεν υπάρχει πεδίο με όνομα \""}, {"CTableMsg66", "\" στον πίνακα"}, {"CTableMsg67", "Πεδία τύπου \"Εικόνας\" δεν μπορούν να είναι μέρος του κλειδιού του πίνακα"}, {"CTableMsg68", "\" ανήκει ήδη στο κλειδί του πίνακα"}, {"CTableMsg69", "\" δεν μπορεί να γίνει μέρος του κλειδιού του πίνακα, διότι περιέχει άδεια κελλιά"}, {"CTableMsg70", "Δεν είναι δυνατή η διαγραφή εγγραφών προκειμένου να οριστεί το κλειδί, διότι δεν επιτρέπεται η διαγραφή εγγραφών στον πίνακα"}, {"CTableMsg71", "\" δεν ανήκει στο κλειδί του πίνακα"}, {"CTableMsg72", "Δεν είναι δυνατή η αλλαγή του τύπου του πεδίου \""}, {"CTableMsg73", "\" διότι είναι υπολογιζόμενο"}, {"CTableMsg74", "\" διότι ανήκει στο κλειδί του πίνακα"}, {"CTableMsg75", "\" διότι δεν είναι μεταβαλλόμενο"}, {"CTableMsg76", "\" διότι υπάρχουν υπολογιζόμενα πεδία, που εξαρτώνται από αυτό"}, {"CTableMsg77", "Άκυρος τύπος πεδίου: "}, {"CTableMsg78", "\" έχει τον ίδιο τύπο με τον προσδιορισθέν"}, {"CTableMsg79", "Ο τύπος του πεδίου \""}, {"CTableMsg80", "\" δεν μπορεί να αλλάξει από \"Ακέραιος\" to \""}, {"CTableMsg81", "Άκυρο όνομα πεδίου \""}, {"CTableMsg82", "Το όνομα "}, {"CTableMsg83", " έχει δοθεί ήδη σε άλλο πεδίο του ίδιου πίνακα"}, {"CTableMsg84", "Ο τίτλος \""}, {"CTableMsg85", "\" ανήκει ήδη σε άλλο πίνακα της βάσης"}, {"CTableMsg86", "Αδύνατη η αφαίρεση του πεδίου, διότι δεν είναι επιτρεπτή η διαγραφή εγγραφών από τον πίνακα"}, {"CTableMsg87", "Δεν είναι επιτρεπτή η διαγραφή πεδίων από τον πίνακα"}, {"CTableMsg88", "Δεν είναι επιτρεπτή η προσθήκη πεδίων στον πίνακα"}, {"CTableMsg89", "Δεν είναι επιτρεπτή η αλλαγή των δεδομένων του πίνακα"}, {"CTableMsg90", "Δεν είναι επιτρεπτή η αλλαγή του κλειδιού του πίνακα"}, {"CTableMsg91", "Δεν είναι επιτρεπτή η μεταβολή της ιδιότητας \"Κρυφός\" του πίνακα"}, {"CTableMsg92", "Η εισαγωγή της εγγραφής δεν είναι δυνατή, διότι ένα από τα πεδία-κλειδιά είναι επίσης κρυφό και ο πίνακας δεν προβάλλει τα κρυφά πεδία"}, {"CTableMsg93", "Αδύνατη η προσθήκη νέας εγγραφής. Ο πίνακας έχει κλειδί και δεν επιτρέπεται η αλλαγή των περιεχομένων του"}, {"CTableMsg94", "\" δεν μπορεί να αλλάξει σε \""}, {"CTableMsg95", "\" δεν μπορεί να αλλάξει από \"Αριθμός\" σε \""}, {"CTableMsg96", "\" δεν μπορεί να αλλάξει από \"Αληθές/Ψευδές\" σε \""}, {"CTableMsg97", "\" δεν μπορεί να αλλάξει από \"URL\" σε \""}, {"CTableMsg98", "Δεν είναι δυνατή η ταξινόμηση πινάκων ως προς πεδία τύπου \"Εικόνας\""}, {"CTableMsg99", "Αδύνατη η προσθήκη νέας εγγραφής διότι δεν έχει ολοκληρωθεί η εισαγωγή της προηγούμενης εγγραφής"}, {"CTableMsg100", "Το πεδίο \""}, {"CTableMsg101", "\" δεν υπάρχει στον πίνακα "}, {"CTableMsg102", "Ένας πίνακας δεν μπορεί να μην έχει τίτλο"}, {"CTableMsg103", "Οι ιδιότητες των πεδίων δεν μπορούν να μεταβληθούν στον πίνακα"}, {"CTableMsg104", "Δεν επιτρέπεται η αλλαγή του ονόματος του πίνακα"}, {"CTableMsg105", "Το κλειδί της εγγραφής δεν είναι μοναδικό στον πίνακα."}, {"CTableMsg106", "Δόθηκε μηδενική τιμή για κελλί του πεδίου \""}, {"CTableMsg107", "\", το οποίο ανήκει στο κλειδί του πίνακα"}, {"ImageFieldMsg1", "Εικόνες ή αλλαγές σε εικόνες που δεν έχουν αποθηκευτεί σε αρχεία θα χαθούν. Θέλετε να συνεχίσετε;"}, {"Table", "Πίνακας"}, {"Record", "Εγγραφή"}, {"of", "του"}, {"Error", "Λάθος"}, {"ConstructorTimer","Κατασκευή πίνακα"}, {"LoadTimer", "Ανάκτηση πίνακα"}, {"SaveTimer", "Αποθήκευση πίνακα"}, {"InitESlateAspectTimer", "Κατασκευή αβακιακής πλευράς πίνακα"}, {"FieldMapTimer", "Ανάκτηση FieldMap πίνακα"}, {"TableView", "Όψη πίνακα"}, {"TableViewMsg1", "\" δεν υπάρχει σε αυτή την Όψη Πίνακα."}, {"View", "Όψη πίνακα"}, {"ViewOf", "Όψη πίνακα"}, }; }
vpapakir/myeslate
widgetESlate/src/gr/cti/eslate/database/engine/CTableResourceBundle_el_GR.java
896
package users; import accommodations.Accommodations; import java.io.*; import java.util.ArrayList; /** * Στη συγκεκριμένη κλάση αρχικοποιόυνται οι χρήστες και αποθηκέυονται ανάλογα με τον τύπο τους σε μία απο τις * τρείς Λίστες {@link ArrayList<Admins> allAdmins}, {@link ArrayList<Providers> allProviders}, {@link ArrayList<Admins> allCustomers)}. Οι λίστες αυτές είναι του αντίστοιχου τύπο({@link users.Users} * ,{@link users.Providers}, {@link users.Customers}) και τύπου static ώστε ανεξάρτητα από το αντικείμενο {@link users.Users}( ή των υποκλάσεων του) που χρησιμοποιούμε * οι τιμές να είναι παντού ίδιες. * Τα πεδία είναι τα κοινά στοιχεία που έχουν και οι τρεις χρήστες * <p> * Υλοποιείται: * η σύνδεση του χρήστη στην εφαρμογή -> {@link #Login(String, String, Role)}, * η εγγραφή χρήστη στην εφαρμογή -> {@link #Register(String, String, String, String, String)} * * </p> */ public class Users implements Serializable { private static ArrayList<Admins> allAdmins; private static ArrayList<Providers> allProviders; private static ArrayList<Customers> allCustomers; private static Accommodations accommodations; private String messages; private final Role role; private final String username; private final String password; private final String gender; /** * Default constructor * Αρχικοποιεί τις τιμές των πεδίων σε null και δημιουργεί τις κενές λίστες. * Στο τέλος καλείται η {@link #DefaultUsers()}, γιά την δημιουργία των default * χρηστών */ public Users() { accommodations = new Accommodations(); allAdmins = new ArrayList<>(); allProviders = new ArrayList<>(); allCustomers = new ArrayList<>(); this.messages = null; this.username = null; this.password = null; this.role = null; this.gender = null; DefaultUsers(); } /** * Constructor που χρησιμοποιείται για την δημιουργία αντικειμένων τύπου {@link Admins}, {@link Providers}, {@link Customers} * * @param username Όνομα χρήστη * @param password Κωδικός χρήστη * @param role Τύπος χρήστη * @param Gender Φύλο χρήστη */ public Users(String username, String password, String role, String Gender) { this.username = username; this.password = password; this.role = RoleVerifier(role); this.gender = Gender; } /** * Μέθοδος που μετατρέπει τον ρόλο/τύπο που έχει εισάγει ο χρήστης σε έναν από τους * διαθέσιμους ρόλους που περιέχει η απαρίθμηση (enumeration) Role. * * @param role Τύπος χρήστη σε συμβολοσειρά (Admin/Provider/Customer). * @return Τύπος χρήστη ({@link Admins}/{@link Providers}/{@link Customers}) μεταφρασμένο σε απαρίθμηση (enumeration). */ public Role RoleVerifier(String role) { return switch (role.toUpperCase()) { case "ADMIN" -> Role.ADMIN; case "PROVIDER" -> Role.PROVIDER; case "CUSTOMER" -> Role.CUSTOMER; default -> Role.NOROLE; }; } public ArrayList<Providers> getAllProviders() { return allProviders; } public ArrayList<Customers> getAllCustomers() { return allCustomers; } public ArrayList<Admins> getAllAdmins() { return allAdmins; } public String getGender() { return this.gender; } public String getPassword() { return this.password; } public Role getRole() { return this.role; } public String getUsername() { return this.username; } public Accommodations getAccommodations() { return accommodations; } public String getMessages() { if (messages == null) { return "You have no messages!"; } return messages; } /** * Η μέθοδος αυτή επιστρέφει τη συμβολοσειρά των μηνυμάτων * Χρησιμοποιείται όταν ένας χρήστης θέλει να δει αν έχει εισερχόμενα μηνύματα * * @param messages Συμβολοσειρά με τα μηνύματα */ public void setMessages(String messages) { this.messages = messages; } /** * Η μέθοδος αυτή επιτρέπει τη σύνδεση του χρήστη στην εφαρμογή.Ανάλογα με την μεταβλητή givenRole * το πρόγραμμα ανατρέχει στην αντίστοιχη Λίστα που έχουμε αποθηκεύσει χρήστες ίδιου τύπου. Έπειτα ελέγχει * αν ταυτίζονται το όνομα(given_username) και ο κωδικός (given_password) με κάποιον από τους υπάρχοντες χρήστες. * * @param Login_username Όνομα χρήστη * @param Login_password Κωδικός χρήστη * @param givenRole Τύπος/ρόλος χρήστη * @return -1 Αν το Login είναι ανεπιτυχές. Την θέση στη λίστα που υπάρχει ο χρήστης αν συνδεθεί επιτυχώς */ public int Login(String Login_username, String Login_password, Role givenRole) { int i = 0; switch (givenRole) { case ADMIN: for (Admins index : allAdmins) { if (index.getUsername().equals(Login_username) && index.getPassword().equals(Login_password) && index.getRole().equals(givenRole)) { return i; } i++; } case PROVIDER: i = 0; for (Providers index : allProviders) { if (index.getUsername().equals(Login_username) && index.getPassword().equals(Login_password) && index.getRole().equals(givenRole)) { return i; } i++; } case CUSTOMER: i = 0; for (Customers index : allCustomers) { if (index.getUsername().equals(Login_username) && index.getPassword().equals(Login_password) && index.getRole().equals(givenRole)) { return i; } i++; } default: return -1; } } public boolean Register(String username, String password, String role, String gender, String compName) { boolean usrExists = false; switch (RoleVerifier(role)) { case PROVIDER -> { for (Providers provider : allProviders) { if (provider.getUsername().equals(username)) { usrExists = true; break; } } if (!usrExists) { allProviders.add(new Providers(username, password, Role.PROVIDER.toString(), gender, compName)); try (ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream("providers.bin"))) { out.writeObject(allProviders); } catch (IOException e) { e.printStackTrace(); } } } case CUSTOMER -> { for (Customers customer : allCustomers) { if (customer.getUsername().equals(username)) { usrExists = true; break; } } if (!usrExists) { allCustomers.add(new Customers(username, password, Role.CUSTOMER.toString(), gender)); try (ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream("customers.bin"))) { out.writeObject(allCustomers); } catch (IOException e) { e.printStackTrace(); } } } } return usrExists; } /** * Μέθοδος αυτή δημιουργεί τους default χρήστες κι έπειτα τους εισάγει στην αντίστοιχη λίστα */ public void DefaultUsers() { // Admins admin = new Admins("Nikos", "Nikos12345", "Admin", "male"); // allAdmins.add(admin); // try(ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream("admins.bin"))) // { // out.writeObject(allAdmins); // } catch(IOException e) // { // e.printStackTrace(); // } try (ObjectInputStream in = new ObjectInputStream(new FileInputStream("admins.bin"))) { allAdmins = (ArrayList<Admins>) in.readObject(); } catch (IOException | ClassNotFoundException e) { e.printStackTrace(); } // Providers provider = new Providers("Dimitris", "Dimitris12345", "Provider", "male", "Lucy"); // Providers provider1 = new Providers("Giorgos", "Giorgos12345", "Provider", "male", "Vogiatzis"); // Providers provider2 = new Providers("Kostas", "Kostas12345", "Provider", "male", "Titania"); // Providers provider3 = new Providers("Takis", "Takis12345", "Provider", "male", "Papadopoulos"); // // provider.activate(); // provider1.activate(); // provider2.activate(); // provider3.activate(); // // allProviders.add(provider); // allProviders.add(provider1); // allProviders.add(provider2); // allProviders.add(provider3); // // try(ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream("providers.bin"))) // { // out.writeObject(allProviders); // } catch(IOException e) // { // e.printStackTrace(); // } try (ObjectInputStream in = new ObjectInputStream(new FileInputStream("providers.bin"))) { allProviders = (ArrayList<Providers>) in.readObject(); } catch (IOException | ClassNotFoundException e) { e.printStackTrace(); } // Customers customer = new Customers("Maria", "Maria12345", "Customer", "female"); // Customers customer1 = new Customers("Makis", "Makis12345", "Customer", "male"); // // allCustomers.add(customer); // allCustomers.add(customer1); // // customer.activate(); // customer1.activate(); // try(ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream("customers.bin"))) // { // out.writeObject(allCustomers); // } catch(IOException e) // { // e.printStackTrace(); // } try (ObjectInputStream in = new ObjectInputStream(new FileInputStream("customers.bin"))) { allCustomers = (ArrayList<Customers>) in.readObject(); } catch (IOException | ClassNotFoundException e) { e.printStackTrace(); } } /** * Βασικοί (διαθέσιμοι) τύποι χρηστών. */ enum Role { ADMIN, PROVIDER, CUSTOMER, NOROLE } }
NikosVogiatzis/UniProjects
java mybooking/mybooking-main/src/users/Users.java
897
package jukebox.jukebox; // Η κλάση checkArguments υλοποιεί τις μεθόδους του interface Arguments public class checkArguments implements Arguments { // Οι τρείς πίνακες από String περιέχουν τα file extentions, τα list extentions και τα διάφορα strategies // Το int NumbOfArg περιέχει τον μέγιστο αριθμό των arguments που θέλουμε να έχει το πρόγραμμα private int NumbOfArg; private final String[] files = {"mp3"}; private final String[] lists = {"m3u"}; private final String[] strats = {"loop", "random", "order"}; // Ο ένας constructor είναι υπεύθυνος για την αρχικοποίηση του NumbOfArg // Ο άλλος δεν κάνει τίποτα απλά υπάρχει για να καλείται η κλάση σε άλλες κλάσεις χωρίς να πρέπει να του δώσουμε αριθμό arguments public checkArguments(int NumbOfArg) { this.NumbOfArg = NumbOfArg; } public checkArguments() { } // Η checkArgNumb τσεκάρει αν ο αριθμός των arguments που έδωσε ο χρήστης είναι από 1 μέχρι και NumbOfArg, // όπου Numb ο αριθμός των arguments που έδωσε ο χρήστης, και επιστρέφει λογικό true or false public boolean checkArgNumb(int Numb) { return Numb >= 1 && Numb <= NumbOfArg; } // Η checkStrat τσεκάρει αν η στρατηγική που έδωσε ο χρήστης υπάρχει σαν στρατηγική, // όπου StratInput το δεύτερο argument που έδωσε ο χρήστης και strats ο πίνακας με τις διάφορες στρατηγικές, // και επιστρέφει σε String με lowercase την στρατηγική αν υπάρχει αλλιώς επιστρέφει "" // Η τοπική μεταβλητή Strat είναι για το πέρασμα όλου του πίνακα public String checkStrat(String StratInput) { for (String Strat : strats) { if (StratInput.toLowerCase().equals(Strat)) { return StratInput.toLowerCase(); } } return ""; } // Η checkFileType τσεκάρει αν αυτό που έδωσε ο χρήστης είναι στα υποστηριζόμενα αρχεία του προγράμματος, // όπου FileInput το πρώτο argument που έδωσε ο χρήστης και files ο πίνακας με τα υποστηριζόμενα αρχεία, // και επιστρέφει λογικό true or false // H τοπική μεταβλητή File είναι για το πέρασμα όλου του πίνακα public boolean checkFileType(String FileInput) { for (String File : files) { if (FileInput.lastIndexOf(".") != -1) { // Βλέπει αν υπάρχει "." στο FileInput if (FileInput.substring(FileInput.lastIndexOf(".") + 1).contains(File)) { // Βλέπει αν μετά την τελευταία "." που υπάρχει return true; // περιέχει κάποιο από τα υποστηριζόμενα αρχεία που } // βρίσκονται στον πίνακα } } return false; } // Η checkListType τσεκάρει αν αυτό που έδωσε είναι στις υποστηριζόμενες λίστες του προγράμματος, // όπου ListInput το πρώτο argument που έδωσε ο χρήστης και lists ο πίνακας με τις υποστηριζόμενες λίστες, // και επιστρέφει λογικό true or false // Η τοπική μεταβλητή List είναι για το πέρασμα όλου του πίνακα public boolean checkListType(String ListInput) { for (String List : lists) { if (ListInput.lastIndexOf(".") != -1) { // Βλέπει αν υπάρχει "." στο ListInput if (ListInput.substring(ListInput.lastIndexOf(".") + 1).contains(List)) { // Βλέπει αν μετά την τελευταία "." που υπάρχει return true; // περιέχει κάποιο από τις υποστηριζόμενες λίστες που } // βρίσκονται στον πίνακα } } return false; } public boolean checkDirectory(String Input) { return !Input.substring(Input.lastIndexOf("\\") + 1).contains("."); } // Η other εκτελεί ένα print αναλόγως την περίπτωση // Όπου Input και StratInput το πρώτο και δεύτερο argument που έδωσε ο χρήστης public void other(String StratInput, String Input) { if (checkStrat(StratInput).equals("")) { // Αν αυτό που επιστρέψει η checkStrat είναι ίσο με "", δηλαδή System.out.println(">>> Strategy not found"); // αυτό που έδωσε ο χρήστης δεν υπάρχει σαν στρατηγική τότε } // κάνει print ότι δεν υπάρχει η στρατηγική που έδωσε else if (checkFileType(Input)) { System.out.println(">>> Cannot use " + StratInput + " with file"); // Αλλιώς αν το πρώτο argument που έδωσε ο χρήστης έιναι αρχείο } // κάνει print ότι δεν μπορεί να χρησιμοποιήσει την συγκεκριμένη else if (checkListType(Input)) { // στρατηγική με file και αντίστοιχα για list System.out.println(">>> Cannot use " + StratInput + " with List"); } } }
VasileiosKokki/Jukebox_University
JukeBox2/src/main/java/jukebox/jukebox/checkArguments.java
898
public class Customer { private final int MAX_PAYMENTS = 10; // Αν θέλουμε παραλείπουμε τη σταθερά αλλά πρέπει να χρησιμοποιούμε παντού το μέγεθος πίνακα που δίνεται (10) private int id; private double balance; private Payment[] payments; // Έχουμε Σύνθεση και όχι κανονική Κληρονομικότητα. Αφού ο πελάτης "έχει έναν" πίνακα πληρωμών και ΔΕΝ "είναι ένας" πίνακας πληρωμών. // Default Constructor public Customer() { } // Full Constructor public Customer(int newId, double newBalance) { this.id = newId; this.balance = newBalance; this.payments = new Payment[MAX_PAYMENTS]; // Δημιουργία του πίνακα αντικειμένων Payment. for (int i = 0; i < MAX_PAYMENTS; i++) { // Αρχικοποίηση όλων των θέσεων του πίνακα με 0. Θα χρειαστεί παρακάτω στη μέθοδο AddPayment(). this.payments[i] = new Payment(); // Δημιουργία νέου αντικειμένου Payment στη θέση [i] του πίνακα payments. this.payments[i].setvAT(0); this.payments[i].setPaidAmount(0); } } public void AddPayment(double paymnt) { /* Οι παρακάτω γραμμές μπορούν να βελτιωθούν ώστε αν το balance είναι 0 (άρα δεν υπάρχει υπόλοιπο χρωστούμενο ποσό) να μην τις εκτελεί καθόλου. Προς το παρόν υλοποιείται στη main πριν την κλήση της AddPayment. */ try { if (paymnt > this.balance) // Αν η πληρωμή που δόθηκε με παράμετρο (paymnt) είναι μεγαλύτερη απ' το υπόλοιπο πόσο (balance)... throw new CustomerBalanceException(); // ... "πετάει" το exception που ζητάει η άσκηση. for (int i = 0; i < payments.length; i++) if (payments[i].getAmmountWithVAT() == 0) { // Βρίσκει την επόμενη κενή θέση του πίνακα πληρωμών (payments) ώστε να καταχωρήσει τη νέα πληρωμή (paymnt). // 1ος τρόπος payments[i].setId(i); payments[i].setvAT(paymnt * 0.24); // Το ποσοστό του φόρου είναι σταθερό 24%. *** ΚΑΛΟ ΕΙΝΑΙ ΝΑ ΤΟ ΔΙΕΥΚΡΙΝΗΣΕΙ Ο ΚΑΘΗΓΗΤΗΣ. payments[i].setPaidAmount(paymnt - payments[i].getvAT()); // 2ος τρόπος. Εναλλακτικά μπορεί να γίνει και με την παρακάτω μέθοδο αρκεί να απενεργοποιηθούν οι δυο γραμμές του 1ου τρόπου. //this.setPayments(i, paymnt - (paymnt * 0.24), paymnt * 0.24); // Το ποσοστό του φόρου είναι σταθερό 24%. *** ΚΑΛΟ ΕΙΝΑΙ ΝΑ ΤΟ ΔΙΕΥΚΡΙΝΗΣΕΙ Ο ΚΑΘΗΓΗΤΗΣ. this.balance = this.balance - paymnt; // Αφαιρεί από το υπόλοιπο (balance), την πληρωμή που δόθηκε με παράμετρο (paymnt). break; // Αφού έχει καταχωρηθεί μια πληρωμή σε κενή θέση του πίνακα, "σπάει" η επανάληψη for. } } catch (CustomerBalanceException msg) { // "Πιάνει" το exception που ζητάει η άσκηση. System.out.println("Exception! Το ποσό πληρωμής είναι μεγαλύτερο από το υπόλοιπο. Η πληρωμή δεν καταχωρήθηκε."); // Εμφανίζει το μήνυμα του exception που ζητάει η άσκηση. } } // Μέθοδοι get, set & toString public void setId(int id) { this.id = id; } public int getId() { return this.id; } public void setBalance(double balance) { this.balance = balance; } public double getBalance() { return this.balance; } public String getPayments(int i) { // GIA ELEGXO KAI DIORTHOSI return this.payments[i].toString(); } public void setPayments(int i, double newPaidAmmount, double newVAT) { this.payments[i].setPaidAmount(newPaidAmmount); this.payments[i].setvAT(newVAT); } public String toString() { String tmpStr = ""; // Δήλωση προσωρινού String για την επιστροφή των πληροφοριών που ζητάει η άσκηση. for (int i = 0; i < payments.length; i++) // "Δημιουργία" του String επιστροφής που ζητάει η άσκηση με την πρόσθεση όλων των γραμμών του πίνακα πληρωμών (payments). tmpStr = tmpStr + "Payment no[" + i +"]: " + this.payments[i].getAmmountWithVAT() + "\n"; return "id: " + this.id + ", Payments: \n" + tmpStr; // Επιστροφή του id και του προσωρινού String που δημιουργήθηκε παραπάνω. } }
panosale/DIPAE_OOP_2nd_Term-JAVA
PaliaThemata/OOP_E22-23/src/Customer.java
899
package users; import accommodations.Accommodations; import accommodations.HotelRooms; import accommodations.PrivateAccommodation; import accommodations.reservervations.Date; import javax.swing.*; import java.io.FileOutputStream; import java.io.IOException; import java.io.ObjectOutputStream; import java.util.*; /** * Η κλάση {@link users.Providers} υλοποιεί τον τύπο χρήστη του παρόχου * Εισάγει καταλύματα στην εφαρμογή {@link #AddHotelRoom(String, String, String, String, String, String, List, String)} * , {@link #AddPrivateAccommodation(String, String, String, String, String, List, String)} * επεξεργάζεται καταλύματα {@link #EditRoom(String, String, String, String, String, String, HotelRooms)}, * {@link #EditAccommodation(String, String, String, String, String, PrivateAccommodation)}, * διαγράφει καταλύματα: {@link #DeleteAccommodation(String)} * και βρίσκει τις ενεργές κρατήσεις για τα καταλύματα του παρόχου: Για τα δωμάτια -> {@link #RoomReservations()}, * για τα ιδιωτικά καταλύματα {@link #PrivateReservations()}. * * @author Νίκος Βογιατζής * @version 9/1/2022 */ public class Providers extends Users { private final String providersBrandName; private boolean activated; /** * Κατασκευαστής που δημιουργεί νέο χρήστη τύπου {@link Providers} * * @param username (Μοναδικό) Όνομα παρόχου. * @param password Κωδικός χρήστη. * @param role Ρόλος χρήστη. * @param Gender Γένος χρήστη. * @param companyName (Μοναδική) Επωνυμία παρόχου (χρησιμοποιείται για την ταύτιση των καταλυμάτων που έχει παραχωρήσει με τον ίδιο) */ public Providers(String username, String password, String role, String Gender, String companyName) { super(username, password, role, Gender); this.providersBrandName = companyName; this.activated = false; } /** * Getter της τιμής providersBrandName * * @return Επιστρέφει την επωνυμία του παρόχου */ public String getProvidersBrandName() { return providersBrandName; } /** * Μέθοδος που αποφασίζει για το αν ένας συγκεκριμένος πάροχος έχει δωμάτια ξενοδοχείων στην κατοχή του. * <p> * * @param name Το όνομα του ξενοδοχείου * @return True αν ο πάροχος έχει στην κατοχή του δωμάτια ξενοδοχείων/ false αλλιώς */ public boolean OwnsHotel(String name) { for(HotelRooms index : getAccommodations().getRooms()) { if(index.getHotelName().equals(name)) { return true; } } return false; } /** * Μέθοδος που αποφασίζει για το αν ένας συγκεκριμένος πάροχος έχει ιδιωτικά καταλύματα στην κατοχή του. * <p> * @param name Το όνομα της ιδιωτικής εταιρίας του παρόχου * @return True αν ο πάροχος έχει στην κατοχή του ιδιωτικά καταλύματα/ false αλλιώς */ public boolean OwnsPrivateAccommodation(String name) { for(PrivateAccommodation index : getAccommodations().getAirbnb()) { if(index.getCompanyName().equals(name)) { return true; } } return false; } /** * Βοηθητική μέθοδος που αποφασίζει αν ο πάροχος έχει ήδη δωμάτιο με τον ίδιο αριθμό στην ίδια διεύθυνση * * @param address Διεύθυνση του ξενοδοχείου * @param roomNumber αριθμός δωματίου * @param name Όνομα παρόχου ώστε να χρησιμοποιείται η μέθοδος μόνο για τα δωμάτια που έχει στην κατοχή του * @return true αν ο πάροχος δεν έχει στην κατοχή του δωμάτιο με τον ίδιο αριθμό δωματίου / false αλλιώς */ public boolean UniqueRoomNumber(String address, int roomNumber, String name) { for (HotelRooms index : getAccommodations().getRooms()) { if (roomNumber == index.getRoomNumber() && index.getHotelName().equals(name) && address.equals(index.getAddress())) return false; } return true; } /** * Η μέθοδος αυτή προσθέτει ξενοδοχειακό δωμάτιο για τον πάροχο. * Αν όλες οι τιμές που δώθηκαν στα textiles είναι έγκυρες και ο πάροχος δεν έχει άλλο δωμάτιο * με τον ίδιο αριθμό δωματίου στη συγκεκριμένη διεύθυνση, τότε δημιουργείται νέο δωμάτιο, * εισάγεται στη λίστα {@link Accommodations#getRooms()} και επιστρέφεται το νέο δωμάτιο * @param roomNumber αριθμός δωματίου * @param floor όροφος δωματίου * @param squareMetres τετραγωνικά δωματίου * @param price τιμή δωματίου * @param Address διεύθυνση ξενοδοχείου * @param capacity χωρητικότητα ατόμων στο δωμάτιο * @param characteristics Λίστα με τα ειδικά χαρακτηριστικά του δωματίου * @return μεταβλητή τύπου {@link HotelRooms} που είναι το νέο δωμάτιο που προσθέθηκε * αν δεν έγινε επιτυχής προσθήκη του νέου δωματίου επιστρέφεται null */ public HotelRooms AddHotelRoom(String roomNumber, String floor, String squareMetres, String price, String Address, String capacity, List<String> characteristics, String path) { boolean types = false; Scanner dump; dump = new Scanner(roomNumber); if (dump.hasNextInt()) { dump = new Scanner(floor); if (dump.hasNextInt()) { dump = new Scanner(squareMetres); if (dump.hasNextInt()) { dump = new Scanner(price); if (dump.hasNextInt()) { dump = new Scanner(capacity); if (dump.hasNextInt()) { if (!Address.equals("")) if (!path.equals("")) types = true; } } } } } if (types) { if (UniqueRoomNumber(Address, Integer.parseInt(roomNumber), this.providersBrandName)) { int x = this.getAccommodations().getImageIdentifier(); this.getAccommodations().addImageToDirectory(path, x, 0); HotelRooms newRoom = new HotelRooms(Integer.parseInt(roomNumber), Integer.parseInt(squareMetres), Integer.parseInt(price), this.providersBrandName, Address, Integer.parseInt(floor), getAccommodations().identifierManager() , Integer.parseInt(capacity), characteristics, "room" + x + ".png"); System.out.println("sss: " + newRoom.getImageName()); return newRoom; } else JOptionPane.showMessageDialog(null, "You already own a room with the number: " + roomNumber); } return null; } /** * Η μέθοδος αυτή προσθέτει ιδιωτικό κατάλυμα για τον πάροχο. * Αν όλες οι τιμές που δώθηκαν στα textiles είναι έγκυρες * τότε δημιουργείται νέο ιδιωτικό κατάλυμα, * εισάγεται στη λίστα {@link Accommodations#getAirbnb()} και επιστρέφεται το νέο ιδιωτικό κατάλυμα * * @param address Διεύθυνση ιδιωτικού καταλύματος * @param type Τύπος καταλύματος * @param squareMetres τετραγωνικά καταλύματος * @param price τιμή καταλύματος * @param capacity χωρητικότητα ατόμων για το κατάλυμα * @param characteristics Λίστα με τα ειδικά χαρακτηριστικά του ιδιωτικού καταλύματος * @return μεταβλητή τύπου {@link PrivateAccommodation} που είναι το νέο ιδιωτικό κατάλυμα που προσθέθηκε, * null αν δεν δημιουργηθεί και προσθεθεί επιτυχώς το ιδιωτικό κατάλυμα */ public PrivateAccommodation AddPrivateAccommodation(String address, String type , String squareMetres, String price, String capacity , List<String> characteristics, String imagePath) { boolean types = false; Scanner dump; dump = new Scanner(squareMetres); if (dump.hasNextInt()) { dump = new Scanner(price); if (dump.hasNextInt()) { if (!address.equals("")) { if (!type.equals("") && (type.equalsIgnoreCase("house") || type.equalsIgnoreCase("maisonette") || type.equalsIgnoreCase("airbnb"))) { dump = new Scanner(capacity); if (dump.hasNextInt()) { if (!imagePath.equals("")) types = true; } } } } } if (types) { int x = this.getAccommodations().getImageIdentifier(); this.getAccommodations().addImageToDirectory(imagePath, x, 1); return new PrivateAccommodation(Integer.parseInt(squareMetres), Integer.parseInt(price) , type, address, this.providersBrandName, this.getAccommodations().identifierManager(), Integer.parseInt(capacity), characteristics, "accommodation" + x + ".png"); } return null; } /** * Μέθοδος που υπολογίζει τον συνολικό αριθμό καταλυμάτων που έχει στην κατοχή του ο πάροχος * * @param name Όνομα παρόχου που βοηθά στην ταύτιση των καταλυμάτων με αυτά που του ανήκουν * @return Επιστρέφει μία ακέραιη τιμή που δείχνει τον αριθμό των καταλυμάτων του παρόχου */ public int numberOfAccommodations(String name) { int count = 0; for (HotelRooms index : getAccommodations().getRooms()) { if (index.getHotelName().equals(name)) count++; } for (PrivateAccommodation index : getAccommodations().getAirbnb()) { if (index.getCompanyName().equals(name)) count++; } return count; } /** * Η μέθοδος αυτή επιτρέπει την επεξεργασία δωματίου. Δημιουργείται αντίγραφο του δωματίου για το οποίο * ο πάροχος επιθυμεί να κάνει αλλαγές. Αν όλες οι τιμές που εισέρχονται ως παράμετροι είναι κενές επιστρέφεται * null αφού δεν υπάρχει καμία αλλαγή στο δωμάτιο. Διαφορετικά ελέγχεται η εγκυρότητα της τιμής του κάθε πεδίου και αν δεν είναι * κενό, οπότε και αλλάζουν οι αντίστοιχες τιμές στο δωμάτιο. Σε αυτήν την περίπτωση έχουμε επιτυχημένη επεξεργασία δωματίου * και επιστρέφεται το αντίγραφο που δημιουργήθηκε με τις αλλαγμένες τιμές * @param roomNumber αριθμός δωματίου * @param roomFloor όροφος δωματίου * @param squareMetres τετραγωνικά μέτρα * @param priceNight τιμή * @param capacity χωρητικότητα ατόμων * @param roomCharacteristics λίστα με τα χαρακτηριστικά του δωματίου * @param room Το δωμάτιο για το οποίο ο πάροχος επιθυμεί να κάνει αλλαγές * @return Το αντίγραφο του δωματίου με τις αλλαγές που εφαρμόστηκαν σε αυτό σε περίπτωση επιτυχημένης * επεξεργασίας, null αν η επεξεργασία δεν είναι επιτυχημένη */ public HotelRooms EditRoom(String roomNumber, String roomFloor, String squareMetres, String priceNight, String capacity, String roomCharacteristics, HotelRooms room) { HotelRooms copyOfRoom = new HotelRooms(room.getRoomNumber(), room.getSquareMetres(), room.getPrice(), room.getHotelName(), room.getAddress(), room.getFloor(), room.getId(), room.getCapacity(), room.getCharacteristics(), room.getImageName()); if (roomNumber.equals("") && roomFloor.equals("") && squareMetres.equals("") && priceNight.equals("") && capacity.equals("") && roomCharacteristics.equals("")) return null; Scanner dump; dump = new Scanner(roomNumber); if (dump.hasNextInt()) { if (UniqueRoomNumber(room.getAddress(), Integer.parseInt(roomNumber), this.providersBrandName)) copyOfRoom.setRoomNumber(dump.nextInt()); else return null; } dump = new Scanner(roomNumber); if (!dump.hasNextInt() && !roomNumber.equals("")) return null; dump = new Scanner(roomFloor); if (dump.hasNextInt()) { copyOfRoom.setFloor(dump.nextInt()); } dump = new Scanner(roomFloor); if (!dump.hasNextInt() && !roomFloor.equals("")) return null; dump = new Scanner(squareMetres); if (dump.hasNextInt()) { copyOfRoom.setSquareMetres(dump.nextInt()); } dump = new Scanner(squareMetres); if (!dump.hasNextInt() && !squareMetres.equals("")) return null; dump = new Scanner(priceNight); if (dump.hasNextInt()) { copyOfRoom.setPrice(dump.nextInt()); } dump = new Scanner(priceNight); if (!dump.hasNextInt() && !priceNight.equals("")) return null; dump = new Scanner(capacity); if (dump.hasNextInt()) { copyOfRoom.setCapacity(dump.nextInt()); } dump = new Scanner(capacity); if (!dump.hasNextInt() && !priceNight.equals("")) return null; if (!roomCharacteristics.equals("")) { List<String> characteristics = new ArrayList<>(); String[] temp = roomCharacteristics.split("/"); characteristics.addAll(Arrays.asList(temp)); characteristics.addAll(room.getCharacteristics()); copyOfRoom.setCharacteristics(characteristics); } return copyOfRoom; } /** * Η μέθοδος αυτή επιτρέπει την επεξεργασία ιδιωτικού καταλύματος. Δημιουργείται αντίγραφο του καταλύματος για το οποίο * ο πάροχος επιθυμεί να κάνει αλλαγές. Αν όλες οι τιμές που εισέρχονται ως παράμετροι είναι κενές επιστρέφεται * null αφού δεν υπάρχει καμία αλλαγή στο κατάλυμα. Διαφορετικά ελέγχεται η εγκυρότητα της τιμής του κάθε πεδίου και αν δεν είναι * κενό, οπότε και αλλάζουν οι αντίστοιχες τιμές στο κατάλυμα. Σε αυτήν την περίπτωση έχουμε επιτυχημένη επεξεργασία καταλύματος * και επιστρέφεται το αντίγραφο που δημιουργήθηκε με τις αλλαγμένες τιμές * * @param type Τύπος ιδιωτικού καταλύματος * @param squareMetres τετραγωνικά ιδιωτικού καταλύματος * @param price Τιμή * @param capacity Χωρητικότητα ατόμων * @param characteristics Ειδικά χαρακτηριστικά * @param accommodation Το ιδιωτικό κατάλυμα για το οποίο ο πάροχος επιθυμεί να κάνει αλλαγές * @return Το αντίγραφο του ιδιωτικού καταλύματος με τις αλλαγές που εφαρμόστηκαν σε αυτό σε περίπτωση επιτυχημένης * * επεξεργασίας, null αν η επεξεργασία δεν είναι επιτυχημένη */ public PrivateAccommodation EditAccommodation(String type, String squareMetres, String price, String capacity , String characteristics, PrivateAccommodation accommodation) { PrivateAccommodation copyOfAccommodation = new PrivateAccommodation(accommodation.getSquareMetres(), accommodation.getPrice(), accommodation.getType(), accommodation.getAddress(), accommodation.getCompanyName(), accommodation.getId(), accommodation.getCapacity(), accommodation.getCharacteristics(), accommodation.getImageName()); if (type.equals("") && squareMetres.equals("") && price.equals("") && capacity.equals("") && characteristics.equals("")) return null; if (!type.equals("")) { if (!type.equalsIgnoreCase("maisonette") && !type.equalsIgnoreCase("airbnb") && !type.equalsIgnoreCase("house")) return null; else copyOfAccommodation.setType(type); } Scanner dump = new Scanner(squareMetres); if (dump.hasNextInt()) copyOfAccommodation.setSquareMetres(dump.nextInt()); dump = new Scanner(squareMetres); if (!squareMetres.equals("") && !dump.hasNextInt()) return null; dump = new Scanner(price); if (dump.hasNextInt()) copyOfAccommodation.setPrice(dump.nextInt()); dump = new Scanner(price); if (!price.equals("") && !dump.hasNextInt()) return null; dump = new Scanner(capacity); if (dump.hasNextInt()) copyOfAccommodation.setCapacity(dump.nextInt()); dump = new Scanner(capacity); if (!capacity.equals("") && !dump.hasNextInt()) return null; if (!characteristics.equals("")) { List<String> characteristicsList = new ArrayList<>(); String[] temp = characteristics.split("/"); characteristicsList.addAll(Arrays.asList(temp)); characteristicsList.addAll(accommodation.getCharacteristics()); copyOfAccommodation.setCharacteristics(characteristicsList); } return copyOfAccommodation; } /** * Η μέθοδος αυτή επιτρέπει την διαγραφή καταλύματος. Δέχεται ως όρισμα τον ειδικό αναγνωριστικό αριθμό καταλύματος * και αν το κατάλυμα με αυτον τον αριθμό ανήκει στον πάροχο τότε διαγράφεται από την αντίστοιχη λίστα * @param ID Ο ειδικός αναγνωριστικός αριθμός του καταλύματος * @return true αν το κατάλυμα διαγράφηκε επιτυχώς */ public boolean DeleteAccommodation(String ID) { int i = 0; if (OwnsHotel(this.providersBrandName)) { Iterator<HotelRooms> itr = getAccommodations().getRooms().iterator(); while (itr.hasNext()) { HotelRooms room = itr.next(); if (room.getId() == Integer.parseInt(ID) && room.getHotelName().equals(this.providersBrandName)) { itr.remove(); i++; } } } if (i != 0) { try (ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream("hotelRooms.bin"))) { out.writeObject(getAccommodations().getRooms()); } catch (IOException e) { e.printStackTrace(); } } if (OwnsPrivateAccommodation(this.providersBrandName)) { Iterator<PrivateAccommodation> it = getAccommodations().getAirbnb().iterator(); while (it.hasNext()) { PrivateAccommodation accommodation = it.next(); if (accommodation.getId() == Integer.parseInt(ID) && accommodation.getCompanyName().equals(this.providersBrandName)) { it.remove(); i++; System.out.println(i); } } } if (i != 0) { try (ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream("privateAccommodation.bin"))) { out.writeObject(getAccommodations().getAirbnb()); } catch (IOException e) { e.printStackTrace(); } } return i > 0; } /** * Η μέθοδος αυτή βρίσκει και επιστρέφει όλες τις κρατήσεις για τα ξενοδοχειακά δωμάτια * που έχει στην κατοχή του ο πάροχος * @return HashMap με κλειδία δωμάτια και τιμές τις ημερομηνίες κράτησης τους */ public HashMap<HotelRooms, ArrayList<Date>> RoomReservations() { HashMap<HotelRooms, ArrayList<Date>> allReservations = new HashMap<>(); ArrayList<Date> allReservedDates; for (HotelRooms room : getAccommodations().getRooms()) { if (room.getHotelName().equals(this.getProvidersBrandName())) { if (room.getUserReservations().size() != 0) { allReservedDates = new ArrayList<>(); for (Date date : room.getUserReservations()) { allReservedDates.add(date); allReservations.put(room, allReservedDates); } } } } return allReservations; } /** * Η μέθοδος αυτή βρίσκει και επιστρέφει όλες τις κρατήσεις για ιδιωτικά καταλύματα * που έχει στην κατοχή του ο πάροχος * * @return HashMap με κλειδία ιδιωτικά καταλύματα και τιμές τις ημερομηνίες κράτησης τους */ public HashMap<PrivateAccommodation, ArrayList<Date>> PrivateReservations() { HashMap<PrivateAccommodation, ArrayList<Date>> allReservations = new HashMap<>(); ArrayList<Date> allReservedDates; for (PrivateAccommodation accommodation : getAccommodations().getAirbnb()) { if (accommodation.getCompanyName().equals(this.getProvidersBrandName())) { if (accommodation.getUserReservations().size() != 0) { allReservedDates = new ArrayList<>(); for (Date date : accommodation.getUserReservations()) { allReservedDates.add(date); allReservations.put(accommodation, allReservedDates); } } } } return allReservations; } /** * μέθοδος που ενεργοποιεί τον λογαριασμό του παρόχου */ public void activate() { this.activated = true; } /** * @return true/false ανάλογα με το αν ο λογαριασμός του παρόχου * είναι ενεργοποιημένος ή όχι */ public boolean accountStatus() { return activated; } }
NikosVogiatzis/UniProjects
java mybooking/mybooking-main/src/users/Providers.java
900
package org.mockserver.integration.server; import com.google.common.base.Charsets; import com.google.common.net.HttpHeaders; import com.google.common.net.MediaType; import com.google.common.util.concurrent.Uninterruptibles; import org.apache.commons.io.IOUtils; import org.junit.Before; import org.junit.Test; import org.mockserver.client.netty.NettyHttpClient; import org.mockserver.client.netty.SocketConnectionException; import org.mockserver.client.server.MockServerClient; import org.mockserver.echo.http.EchoServer; import org.mockserver.matchers.HttpRequestMatcher; import org.mockserver.matchers.MatchType; import org.mockserver.matchers.TimeToLive; import org.mockserver.matchers.Times; import org.mockserver.mock.Expectation; import org.mockserver.model.*; import org.mockserver.socket.PortFactory; import org.mockserver.verify.VerificationTimes; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.IOException; import java.util.*; import java.util.concurrent.*; import static org.hamcrest.Matchers.*; import static org.hamcrest.core.Is.is; import static org.hamcrest.core.StringStartsWith.startsWith; import static org.hamcrest.number.OrderingComparison.greaterThan; import static org.junit.Assert.*; import static org.mockserver.matchers.Times.exactly; import static org.mockserver.matchers.Times.once; import static org.mockserver.model.BinaryBody.binary; import static org.mockserver.model.Cookie.cookie; import static org.mockserver.model.Header.header; import static org.mockserver.model.HttpCallback.callback; import static org.mockserver.model.HttpForward.forward; import static org.mockserver.model.HttpRequest.request; import static org.mockserver.model.HttpResponse.notFoundResponse; import static org.mockserver.model.HttpResponse.response; import static org.mockserver.model.JsonBody.json; import static org.mockserver.model.JsonSchemaBody.jsonSchema; import static org.mockserver.model.NottableString.not; import static org.mockserver.model.NottableString.string; import static org.mockserver.model.OutboundHttpRequest.outboundRequest; import static org.mockserver.model.Parameter.param; import static org.mockserver.model.ParameterBody.params; import static org.mockserver.model.StringBody.exact; import static org.mockserver.model.XPathBody.xpath; /** * @author jamesdbloom */ public abstract class AbstractClientServerIntegrationTest { public static final String TEXT_PLAIN = MediaType.create("text", "plain").toString(); protected static MockServerClient mockServerClient; protected static String servletContext = ""; private final Logger logger = LoggerFactory.getLogger(this.getClass()); protected List<String> headersToIgnore = Arrays.asList( "server", "expires", "date", "host", "connection", "user-agent", "content-length", "accept-encoding", "transfer-encoding" ); private NettyHttpClient httpClient = new NettyHttpClient(); public static Expectation expectation(HttpRequest httpRequest) { return new Expectation(httpRequest, Times.unlimited(), TimeToLive.unlimited()); } public abstract int getMockServerPort(); public abstract int getMockServerSecurePort(); public abstract int getTestServerPort(); protected String calculatePath(String path) { return "/" + path; } @Before public void resetServer() { mockServerClient.reset(); } @Test public void shouldForwardRequestInHTTP() { // when mockServerClient .when( request() .withPath(calculatePath("echo")) ) .forward( forward() .withHost("127.0.0.1") .withPort(getTestServerPort()) ); // then // - in http assertEquals( response() .withStatusCode(HttpStatusCode.OK_200.code()) .withHeaders( header("x-test", "test_headers_and_body"), header(HttpHeaders.CONTENT_TYPE, TEXT_PLAIN) ) .withBody("an_example_body_http"), makeRequest( request() .withPath(calculatePath("echo")) .withMethod("POST") .withHeaders( header("x-test", "test_headers_and_body") ) .withBody("an_example_body_http"), headersToIgnore) ); // - in https assertEquals( response() .withStatusCode(HttpStatusCode.OK_200.code()) .withHeaders( header("x-test", "test_headers_and_body"), header(HttpHeaders.CONTENT_TYPE, TEXT_PLAIN) ) .withBody("an_example_body_https"), makeRequest( request() .withSecure(true) .withPath(calculatePath("echo")) .withMethod("POST") .withHeaders( header("x-test", "test_headers_and_body") ) .withBody("an_example_body_https"), headersToIgnore) ); } @Test public void shouldForwardRequestInHTTPS() { int testServerHttpsPort = PortFactory.findFreePort(); EchoServer secureEchoServer = new EchoServer(testServerHttpsPort, true); try { // when mockServerClient .when( request() .withPath(calculatePath("echo")) ) .forward( forward() .withHost("127.0.0.1") .withPort(testServerHttpsPort) .withScheme(HttpForward.Scheme.HTTPS) ); // then // - in http assertEquals( response() .withStatusCode(HttpStatusCode.OK_200.code()) .withHeaders( header("x-test", "test_headers_and_body"), header(HttpHeaders.CONTENT_TYPE, TEXT_PLAIN) ) .withBody("an_example_body_http"), makeRequest( request() .withPath(calculatePath("echo")) .withMethod("POST") .withHeaders( header("x-test", "test_headers_and_body") ) .withBody("an_example_body_http"), headersToIgnore) ); // - in https assertEquals( response() .withStatusCode(HttpStatusCode.OK_200.code()) .withHeaders( header("x-test", "test_headers_and_body"), header(HttpHeaders.CONTENT_TYPE, TEXT_PLAIN) ) .withBody("an_example_body_https"), makeRequest( request() .withSecure(true) .withPath(calculatePath("echo")) .withMethod("POST") .withHeaders( header("x-test", "test_headers_and_body") ) .withBody("an_example_body_https"), headersToIgnore) ); } finally { secureEchoServer.stop(); } } @Test public void shouldAllowSimultaneousForwardAndResponseExpectations() { // when mockServerClient .when( request() .withPath(calculatePath("echo")), once() ) .forward( forward() .withHost("127.0.0.1") .withPort(getTestServerPort()) ); mockServerClient .when( request() .withPath(calculatePath("test_headers_and_body")), once() ) .respond( response() .withBody("some_body") ); // then // - forward assertEquals( response() .withStatusCode(HttpStatusCode.OK_200.code()) .withHeaders( header("x-test", "test_headers_and_body"), header(HttpHeaders.CONTENT_TYPE, TEXT_PLAIN) ) .withBody("an_example_body"), makeRequest( request() .withPath(calculatePath("echo")) .withMethod("POST") .withHeaders( header("x-test", "test_headers_and_body") ) .withBody("an_example_body"), headersToIgnore) ); // - respond assertEquals( response() .withHeader(HttpHeaders.CONTENT_TYPE, TEXT_PLAIN) .withStatusCode(HttpStatusCode.OK_200.code()) .withBody("some_body"), makeRequest( request() .withPath(calculatePath("test_headers_and_body")), headersToIgnore) ); // - no response or forward assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()), makeRequest( request() .withPath(calculatePath("test_headers_and_body")), headersToIgnore) ); } @Test public void shouldCallbackToSpecifiedClassWithPrecannedResponse() { // when mockServerClient .when( request() .withPath(calculatePath("callback")) ) .callback( callback() .withCallbackClass("org.mockserver.integration.callback.PrecannedTestExpectationCallback") ); // then // - in http assertEquals( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withHeaders( header("x-callback", "test_callback_header"), header(HttpHeaders.CONTENT_TYPE, TEXT_PLAIN) ) .withBody("a_callback_response"), makeRequest( request() .withPath(calculatePath("callback")) .withMethod("POST") .withHeaders( header("x-test", "test_headers_and_body") ) .withBody("an_example_body_http"), headersToIgnore ) ); // - in https assertEquals( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withHeaders( header("x-callback", "test_callback_header"), header(HttpHeaders.CONTENT_TYPE, TEXT_PLAIN) ) .withBody("a_callback_response"), makeRequest( request() .withSecure(true) .withPath(calculatePath("callback")) .withMethod("POST") .withHeaders( header("x-test", "test_headers_and_body") ) .withBody("an_example_body_https"), headersToIgnore ) ); } @Test public void shouldReturnResponseWithOnlyBody() { // when mockServerClient.when(request()).respond(response().withBody("some_body")); // then // - in http assertEquals( response() .withHeader(HttpHeaders.CONTENT_TYPE, TEXT_PLAIN) .withStatusCode(HttpStatusCode.OK_200.code()) .withBody("some_body"), makeRequest( request() .withPath(calculatePath("")), headersToIgnore) ); // - in https assertEquals( response() .withHeader(HttpHeaders.CONTENT_TYPE, TEXT_PLAIN) .withStatusCode(HttpStatusCode.OK_200.code()) .withBody("some_body"), makeRequest( request() .withSecure(true) .withPath(calculatePath("")), headersToIgnore) ); } @Test public void shouldReturnResponseForRequestInSsl() { // when mockServerClient.when(request().withSecure(true)).respond(response().withBody("some_body")); // then // - in http assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()), makeRequest( request() .withPath(calculatePath("")), headersToIgnore) ); // - in https assertEquals( response() .withHeader(HttpHeaders.CONTENT_TYPE, TEXT_PLAIN) .withStatusCode(HttpStatusCode.OK_200.code()) .withBody("some_body"), makeRequest( request() .withSecure(true) .withPath(calculatePath("")), headersToIgnore) ); } @Test public void shouldReturnResponseForRequestNotInSsl() { // when mockServerClient.when(request().withSecure(false)).respond(response().withBody("some_body")); // then // - in http assertEquals( response() .withHeader(HttpHeaders.CONTENT_TYPE, TEXT_PLAIN) .withStatusCode(HttpStatusCode.OK_200.code()) .withBody("some_body"), makeRequest( request() .withPath(calculatePath("")), headersToIgnore) ); // - in https assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()), makeRequest( request() .withSecure(true) .withPath(calculatePath("")), headersToIgnore) ); } @Test public void shouldReturnMatchRequestWithBodyInUTF16() { // when String body = "我说中国话"; mockServerClient.when(request().withBody(body, Charsets.UTF_16)).respond(response().withBody(body, Charsets.UTF_8)); // then // - in http assertEquals( response() .withHeader(HttpHeaders.CONTENT_TYPE, MediaType.create("text", "plain").withCharset(Charsets.UTF_8).toString()) .withStatusCode(HttpStatusCode.OK_200.code()) .withBody(body), makeRequest( request() .withPath(calculatePath("")) .withBody(body, Charsets.UTF_16), headersToIgnore) ); // - in https assertEquals( response() .withHeader(HttpHeaders.CONTENT_TYPE, MediaType.create("text", "plain").withCharset(Charsets.UTF_8).toString()) .withStatusCode(HttpStatusCode.OK_200.code()) .withBody(body), makeRequest( request() .withSecure(true) .withPath(calculatePath("")) .withBody(body, Charsets.UTF_16), headersToIgnore) ); } @Test public void shouldReturnMatchRequestWithBodyInUTF16WithContentTypeHeader() { // when String body = "我说中国话"; mockServerClient .when( request() .withHeader(HttpHeaders.CONTENT_TYPE, MediaType.create("text", "plain").withCharset(Charsets.UTF_8).toString()) .withBody(body) ) .respond( response() .withBody(body, Charsets.UTF_8) ); // then // - in http assertEquals( response() .withHeader(HttpHeaders.CONTENT_TYPE, MediaType.create("text", "plain").withCharset(Charsets.UTF_8).toString()) .withStatusCode(HttpStatusCode.OK_200.code()) .withBody(body), makeRequest( request() .withHeader(HttpHeaders.CONTENT_TYPE, MediaType.create("text", "plain").withCharset(Charsets.UTF_8).toString()) .withPath(calculatePath("")) .withBody(body), headersToIgnore) ); // - in https assertEquals( response() .withHeader(HttpHeaders.CONTENT_TYPE, MediaType.create("text", "plain").withCharset(Charsets.UTF_8).toString()) .withStatusCode(HttpStatusCode.OK_200.code()) .withBody(body), makeRequest( request() .withHeader(HttpHeaders.CONTENT_TYPE, MediaType.create("text", "plain").withCharset(Charsets.UTF_8).toString()) .withSecure(true) .withPath(calculatePath("")) .withBody(body), headersToIgnore) ); } @Test public void shouldReturnResponseWithBodyInUTF8() { // when String body = "我说中国话"; mockServerClient.when(request()).respond(response().withBody(body, Charsets.UTF_16)); // then // - in http assertEquals( response() .withHeader(HttpHeaders.CONTENT_TYPE, MediaType.create("text", "plain").withCharset(Charsets.UTF_16).toString()) .withStatusCode(HttpStatusCode.OK_200.code()) .withBody(body), makeRequest( request() .withPath(calculatePath("")), headersToIgnore) ); // - in https assertEquals( response() .withHeader(HttpHeaders.CONTENT_TYPE, MediaType.create("text", "plain").withCharset(Charsets.UTF_16).toString()) .withStatusCode(HttpStatusCode.OK_200.code()) .withBody(body), makeRequest( request() .withSecure(true) .withPath(calculatePath("")), headersToIgnore) ); } @Test public void shouldReturnResponseWithBodyInUTF16WithContentTypeHeader() { // when String body = "我说中国话"; mockServerClient .when( request() ) .respond( response() .withHeader(HttpHeaders.CONTENT_TYPE, MediaType.create("text", "plain").withCharset(Charsets.UTF_8).toString()) .withBody(body) ); // then // - in http assertEquals( response() .withHeader(HttpHeaders.CONTENT_TYPE, MediaType.create("text", "plain").withCharset(Charsets.UTF_8).toString()) .withStatusCode(HttpStatusCode.OK_200.code()) .withBody(body), makeRequest( request() .withPath(calculatePath("")), headersToIgnore) ); // - in https assertEquals( response() .withHeader(HttpHeaders.CONTENT_TYPE, MediaType.create("text", "plain").withCharset(Charsets.UTF_8).toString()) .withStatusCode(HttpStatusCode.OK_200.code()) .withBody(body), makeRequest( request() .withSecure(true) .withPath(calculatePath("")), headersToIgnore) ); } @Test public void shouldReturnResponseWithOnlyStatusCode() { // when mockServerClient .when( request() .withMethod("POST") .withPath(calculatePath("some_path")) ) .respond( response() .withStatusCode(200) ); // then // - in http assertEquals( response() .withStatusCode(HttpStatusCode.OK_200.code()), makeRequest( request() .withPath(calculatePath("some_path")) .withMethod("POST"), headersToIgnore) ); // - in https assertEquals( response() .withStatusCode(HttpStatusCode.OK_200.code()), makeRequest( request() .withSecure(true) .withPath(calculatePath("some_path")) .withMethod("POST"), headersToIgnore) ); } @Test public void shouldReturnResponseByMatchingPath() { // when mockServerClient .when( request() .withPath(calculatePath("some_path1")) ) .respond( response() .withBody("some_body1") ); mockServerClient .when( request() .withPath(calculatePath("some_path2")) ) .respond( response() .withBody("some_body2") ); // then // - in http assertEquals( response() .withHeader(HttpHeaders.CONTENT_TYPE, TEXT_PLAIN) .withStatusCode(HttpStatusCode.OK_200.code()) .withBody("some_body2"), makeRequest( request() .withPath(calculatePath("some_path2")), headersToIgnore) ); assertEquals( response() .withHeader(HttpHeaders.CONTENT_TYPE, TEXT_PLAIN) .withStatusCode(HttpStatusCode.OK_200.code()) .withBody("some_body1"), makeRequest( request() .withPath(calculatePath("some_path1")), headersToIgnore) ); // - in https assertEquals( response() .withHeader(HttpHeaders.CONTENT_TYPE, TEXT_PLAIN) .withStatusCode(HttpStatusCode.OK_200.code()) .withBody("some_body2"), makeRequest( request() .withSecure(true) .withPath(calculatePath("some_path2")), headersToIgnore) ); assertEquals( response() .withHeader(HttpHeaders.CONTENT_TYPE, TEXT_PLAIN) .withStatusCode(HttpStatusCode.OK_200.code()) .withBody("some_body1"), makeRequest( request() .withSecure(true) .withPath(calculatePath("some_path1")), headersToIgnore) ); } @Test public void shouldReturnResponseByMatchingPathExactTimes() { // when mockServerClient .when( request() .withPath(calculatePath("some_path")), exactly(2) ) .respond( response() .withBody("some_body") ); // then // - in http assertEquals( response() .withHeader(HttpHeaders.CONTENT_TYPE, TEXT_PLAIN) .withStatusCode(HttpStatusCode.OK_200.code()) .withBody("some_body"), makeRequest( request() .withPath(calculatePath("some_path")), headersToIgnore) ); // - in https assertEquals( response() .withHeader(HttpHeaders.CONTENT_TYPE, TEXT_PLAIN) .withStatusCode(HttpStatusCode.OK_200.code()) .withBody("some_body"), makeRequest( request() .withSecure(true) .withPath(calculatePath("some_path")), headersToIgnore) ); // - in http assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()), makeRequest( request() .withPath(calculatePath("some_path")), headersToIgnore) ); // - in https assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()), makeRequest( request() .withSecure(true) .withPath(calculatePath("some_path")), headersToIgnore) ); } @Test public void shouldReturnResponseWhenTimeToLiveHasNotExpired() { // when mockServerClient .when( request().withPath(calculatePath("some_path")), exactly(2), TimeToLive.exactly(TimeUnit.HOURS, 1L) ) .respond( response().withBody("some_body") ); // then // - in http assertEquals( response() .withHeader(HttpHeaders.CONTENT_TYPE, TEXT_PLAIN) .withStatusCode(HttpStatusCode.OK_200.code()) .withBody("some_body"), makeRequest( request() .withPath(calculatePath("some_path")), headersToIgnore) ); // - in https assertEquals( response() .withHeader(HttpHeaders.CONTENT_TYPE, TEXT_PLAIN) .withStatusCode(HttpStatusCode.OK_200.code()) .withBody("some_body"), makeRequest( request() .withSecure(true) .withPath(calculatePath("some_path")), headersToIgnore) ); // - in http assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()), makeRequest( request() .withPath(calculatePath("some_path")), headersToIgnore) ); // - in https assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()), makeRequest( request() .withSecure(true) .withPath(calculatePath("some_path")), headersToIgnore) ); } @Test public void shouldReturnResponseByMatchingBodyWithXPath() { // when mockServerClient.when(request().withBody(xpath("/bookstore/book[price>30]/price")), exactly(2)).respond(response().withBody("some_body")); // then // - in http assertEquals( response() .withHeader(HttpHeaders.CONTENT_TYPE, TEXT_PLAIN) .withStatusCode(HttpStatusCode.OK_200.code()) .withBody("some_body"), makeRequest( request() .withPath(calculatePath("some_path")) .withMethod("POST") .withBody(new StringBody("" + "<?xml version=\"1.0\" encoding=\"ISO-8859-1\"?>" + System.getProperty("line.separator") + "<bookstore>" + System.getProperty("line.separator") + " <book category=\"COOKING\">" + System.getProperty("line.separator") + " <title lang=\"en\">Everyday Italian</title>" + System.getProperty("line.separator") + " <author>Giada De Laurentiis</author>" + System.getProperty("line.separator") + " <year>2005</year>" + System.getProperty("line.separator") + " <price>30.00</price>" + System.getProperty("line.separator") + " </book>" + System.getProperty("line.separator") + " <book category=\"CHILDREN\">" + System.getProperty("line.separator") + " <title lang=\"en\">Harry Potter</title>" + System.getProperty("line.separator") + " <author>J K. Rowling</author>" + System.getProperty("line.separator") + " <year>2005</year>" + System.getProperty("line.separator") + " <price>29.99</price>" + System.getProperty("line.separator") + " </book>" + System.getProperty("line.separator") + " <book category=\"WEB\">" + System.getProperty("line.separator") + " <title lang=\"en\">Learning XML</title>" + System.getProperty("line.separator") + " <author>Erik T. Ray</author>" + System.getProperty("line.separator") + " <year>2003</year>" + System.getProperty("line.separator") + " <price>31.95</price>" + System.getProperty("line.separator") + " </book>" + System.getProperty("line.separator") + "</bookstore>")), headersToIgnore) ); // - in https assertEquals( response() .withHeader(HttpHeaders.CONTENT_TYPE, TEXT_PLAIN) .withStatusCode(HttpStatusCode.OK_200.code()) .withBody("some_body"), makeRequest( request() .withSecure(true) .withPath(calculatePath("some_path")) .withMethod("POST") .withBody(new StringBody("" + "<?xml version=\"1.0\" encoding=\"ISO-8859-1\"?>" + System.getProperty("line.separator") + "<bookstore>" + System.getProperty("line.separator") + " <book category=\"COOKING\">" + System.getProperty("line.separator") + " <title lang=\"en\">Everyday Italian</title>" + System.getProperty("line.separator") + " <author>Giada De Laurentiis</author>" + System.getProperty("line.separator") + " <year>2005</year>" + System.getProperty("line.separator") + " <price>30.00</price>" + System.getProperty("line.separator") + " </book>" + System.getProperty("line.separator") + " <book category=\"CHILDREN\">" + System.getProperty("line.separator") + " <title lang=\"en\">Harry Potter</title>" + System.getProperty("line.separator") + " <author>J K. Rowling</author>" + System.getProperty("line.separator") + " <year>2005</year>" + System.getProperty("line.separator") + " <price>29.99</price>" + System.getProperty("line.separator") + " </book>" + System.getProperty("line.separator") + " <book category=\"WEB\">" + System.getProperty("line.separator") + " <title lang=\"en\">Learning XML</title>" + System.getProperty("line.separator") + " <author>Erik T. Ray</author>" + System.getProperty("line.separator") + " <year>2003</year>" + System.getProperty("line.separator") + " <price>31.95</price>" + System.getProperty("line.separator") + " </book>" + System.getProperty("line.separator") + "</bookstore>")), headersToIgnore) ); } @Test public void shouldReturnResponseByMatchingBodyWithJson() { // when mockServerClient .when( request() .withBody(json("{" + System.getProperty("line.separator") + " \"id\": 1," + System.getProperty("line.separator") + " \"name\": \"A green door\"," + System.getProperty("line.separator") + " \"price\": 12.50," + System.getProperty("line.separator") + " \"tags\": [\"home\", \"green\"]" + System.getProperty("line.separator") + "}")), exactly(2) ) .respond( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body") ); // then // - in http assertEquals( response() .withHeader(HttpHeaders.CONTENT_TYPE, TEXT_PLAIN) .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body"), makeRequest( request() .withPath(calculatePath("some_path")) .withMethod("POST") .withBody("{" + System.getProperty("line.separator") + " \"id\": 1," + System.getProperty("line.separator") + " \"extra ignored field\": \"some value\"," + System.getProperty("line.separator") + " \"name\": \"A green door\"," + System.getProperty("line.separator") + " \"price\": 12.50," + System.getProperty("line.separator") + " \"tags\": [\"home\", \"green\"]" + System.getProperty("line.separator") + "}"), headersToIgnore) ); // - in https assertEquals( response() .withHeader(HttpHeaders.CONTENT_TYPE, TEXT_PLAIN) .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body"), makeRequest( request() .withSecure(true) .withPath(calculatePath("some_path")) .withMethod("POST") .withBody("{" + System.getProperty("line.separator") + " \"id\": 1," + System.getProperty("line.separator") + " \"extra ignored array\": [\"one\", \"two\"]," + System.getProperty("line.separator") + " \"name\": \"A green door\"," + System.getProperty("line.separator") + " \"price\": 12.50," + System.getProperty("line.separator") + " \"tags\": [\"home\", \"green\"]" + System.getProperty("line.separator") + "}"), headersToIgnore) ); } @Test public void shouldReturnResponseByMatchingBodyWithJsonWithCharsetUTF8() { // when mockServerClient .when( request() .withBody(json("{" + System.getProperty("line.separator") + " \"ταυτότητα\": 1," + System.getProperty("line.separator") + " \"όνομα\": \"μια πράσινη πόρτα\"," + System.getProperty("line.separator") + " \"τιμή\": 12.50," + System.getProperty("line.separator") + " \"ετικέτες\": [\"σπίτι\", \"πράσινος\"]" + System.getProperty("line.separator") + "}", Charsets.UTF_16, MatchType.ONLY_MATCHING_FIELDS)), exactly(2) ) .respond( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body") ); // then // - in http assertEquals( response() .withHeader(HttpHeaders.CONTENT_TYPE, TEXT_PLAIN) .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body"), makeRequest( request() .withPath(calculatePath("some_path")) .withMethod("POST") .withBody(json("{" + System.getProperty("line.separator") + " \"ταυτότητα\": 1," + System.getProperty("line.separator") + " \"επιπλέον αγνοούνται τομέα\": \"κάποια αξία\"," + System.getProperty("line.separator") + " \"όνομα\": \"μια πράσινη πόρτα\"," + System.getProperty("line.separator") + " \"τιμή\": 12.50," + System.getProperty("line.separator") + " \"ετικέτες\": [\"σπίτι\", \"πράσινος\"]" + System.getProperty("line.separator") + "}", Charsets.UTF_16, MatchType.ONLY_MATCHING_FIELDS)), headersToIgnore) ); // - in https assertEquals( response() .withHeader(HttpHeaders.CONTENT_TYPE, TEXT_PLAIN) .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body"), makeRequest( request() .withSecure(true) .withPath(calculatePath("some_path")) .withMethod("POST") .withBody(json("{" + System.getProperty("line.separator") + " \"ταυτότητα\": 1," + System.getProperty("line.separator") + " \"επιπλέον αγνοούνται σειρά\": [\"ένας\", \"δυο\"]," + System.getProperty("line.separator") + " \"όνομα\": \"μια πράσινη πόρτα\"," + System.getProperty("line.separator") + " \"τιμή\": 12.50," + System.getProperty("line.separator") + " \"ετικέτες\": [\"σπίτι\", \"πράσινος\"]" + System.getProperty("line.separator") + "}", Charsets.UTF_16, MatchType.ONLY_MATCHING_FIELDS)), headersToIgnore) ); } @Test public void shouldReturnResponseByMatchingBodyWithJsonWithContentTypeHeader() { // when mockServerClient .when( request() .withBody(json("{" + System.getProperty("line.separator") + " \"ταυτότητα\": 1," + System.getProperty("line.separator") + " \"όνομα\": \"μια πράσινη πόρτα\"," + System.getProperty("line.separator") + " \"τιμή\": 12.50," + System.getProperty("line.separator") + " \"ετικέτες\": [\"σπίτι\", \"πράσινος\"]" + System.getProperty("line.separator") + "}", Charsets.UTF_16, MatchType.ONLY_MATCHING_FIELDS)), exactly(2) ) .respond( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body") ); // then // - in http assertEquals( response() .withHeader(HttpHeaders.CONTENT_TYPE, TEXT_PLAIN) .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body"), makeRequest( request() .withHeader(HttpHeaders.CONTENT_TYPE, MediaType.create("text", "plain").withCharset(Charsets.UTF_16).toString()) .withPath(calculatePath("some_path")) .withMethod("POST") .withBody(json("{" + System.getProperty("line.separator") + " \"ταυτότητα\": 1," + System.getProperty("line.separator") + " \"επιπλέον αγνοούνται τομέα\": \"κάποια αξία\"," + System.getProperty("line.separator") + " \"όνομα\": \"μια πράσινη πόρτα\"," + System.getProperty("line.separator") + " \"τιμή\": 12.50," + System.getProperty("line.separator") + " \"ετικέτες\": [\"σπίτι\", \"πράσινος\"]" + System.getProperty("line.separator") + "}")), headersToIgnore) ); // - in https assertEquals( response() .withHeader(HttpHeaders.CONTENT_TYPE, TEXT_PLAIN) .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body"), makeRequest( request() .withSecure(true) .withHeader(HttpHeaders.CONTENT_TYPE, MediaType.create("text", "plain").withCharset(Charsets.UTF_16).toString()) .withPath(calculatePath("some_path")) .withMethod("POST") .withBody(json("{" + System.getProperty("line.separator") + " \"ταυτότητα\": 1," + System.getProperty("line.separator") + " \"επιπλέον αγνοούνται σειρά\": [\"ένας\", \"δυο\"]," + System.getProperty("line.separator") + " \"όνομα\": \"μια πράσινη πόρτα\"," + System.getProperty("line.separator") + " \"τιμή\": 12.50," + System.getProperty("line.separator") + " \"ετικέτες\": [\"σπίτι\", \"πράσινος\"]" + System.getProperty("line.separator") + "}")), headersToIgnore) ); } @Test public void shouldReturnResponseByMatchingBodyWithJsonWithMatchType() { // when mockServerClient .when( request() .withBody(json("{" + System.getProperty("line.separator") + " \"id\": 1," + System.getProperty("line.separator") + " \"name\": \"A green door\"," + System.getProperty("line.separator") + " \"price\": 12.50," + System.getProperty("line.separator") + " \"tags\": [\"home\", \"green\"]" + System.getProperty("line.separator") + "}", MatchType.ONLY_MATCHING_FIELDS)), exactly(2) ) .respond( response() .withBody("some_body") ); // then // - in http assertEquals( response("some_body").withHeader(HttpHeaders.CONTENT_TYPE, TEXT_PLAIN), makeRequest( request() .withPath(calculatePath("some_path")) .withMethod("POST") .withBody("{" + System.getProperty("line.separator") + " \"id\": 1," + System.getProperty("line.separator") + " \"extra field\": \"some value\"," + System.getProperty("line.separator") + " \"name\": \"A green door\"," + System.getProperty("line.separator") + " \"price\": 12.50," + System.getProperty("line.separator") + " \"tags\": [\"home\", \"green\"]" + System.getProperty("line.separator") + "}"), headersToIgnore) ); // - in https assertEquals( response("some_body").withHeader(HttpHeaders.CONTENT_TYPE, TEXT_PLAIN), makeRequest( request() .withSecure(true) .withPath(calculatePath("some_path")) .withMethod("POST") .withBody("{" + System.getProperty("line.separator") + " \"id\": 1," + System.getProperty("line.separator") + " \"extra field\": \"some value\"," + System.getProperty("line.separator") + " \"name\": \"A green door\"," + System.getProperty("line.separator") + " \"price\": 12.50," + System.getProperty("line.separator") + " \"tags\": [\"home\", \"green\"]" + System.getProperty("line.separator") + "}"), headersToIgnore) ); } @Test public void shouldReturnResponseByMatchingBodyWithJsonSchema() { // when mockServerClient.when(request().withBody(jsonSchema("{" + System.getProperty("line.separator") + " \"$schema\": \"http://json-schema.org/draft-04/schema#\"," + System.getProperty("line.separator") + " \"title\": \"Product\"," + System.getProperty("line.separator") + " \"description\": \"A product from Acme's catalog\"," + System.getProperty("line.separator") + " \"type\": \"object\"," + System.getProperty("line.separator") + " \"properties\": {" + System.getProperty("line.separator") + " \"id\": {" + System.getProperty("line.separator") + " \"description\": \"The unique identifier for a product\"," + System.getProperty("line.separator") + " \"type\": \"integer\"" + System.getProperty("line.separator") + " }," + System.getProperty("line.separator") + " \"name\": {" + System.getProperty("line.separator") + " \"description\": \"Name of the product\"," + System.getProperty("line.separator") + " \"type\": \"string\"" + System.getProperty("line.separator") + " }," + System.getProperty("line.separator") + " \"price\": {" + System.getProperty("line.separator") + " \"type\": \"number\"," + System.getProperty("line.separator") + " \"minimum\": 0," + System.getProperty("line.separator") + " \"exclusiveMinimum\": true" + System.getProperty("line.separator") + " }," + System.getProperty("line.separator") + " \"tags\": {" + System.getProperty("line.separator") + " \"type\": \"array\"," + System.getProperty("line.separator") + " \"items\": {" + System.getProperty("line.separator") + " \"type\": \"string\"" + System.getProperty("line.separator") + " }," + System.getProperty("line.separator") + " \"minItems\": 1," + System.getProperty("line.separator") + " \"uniqueItems\": true" + System.getProperty("line.separator") + " }" + System.getProperty("line.separator") + " }," + System.getProperty("line.separator") + " \"required\": [\"id\", \"name\", \"price\"]" + System.getProperty("line.separator") + "}")), exactly(2)).respond(response().withBody("some_body")); // then // - in http assertEquals( response() .withHeader(HttpHeaders.CONTENT_TYPE, TEXT_PLAIN) .withStatusCode(HttpStatusCode.OK_200.code()) .withBody("some_body"), makeRequest( request() .withPath(calculatePath("some_path")) .withMethod("POST") .withBody("{" + System.getProperty("line.separator") + " \"id\": 1," + System.getProperty("line.separator") + " \"name\": \"A green door\"," + System.getProperty("line.separator") + " \"price\": 12.50," + System.getProperty("line.separator") + " \"tags\": [\"home\", \"green\"]" + System.getProperty("line.separator") + "}"), headersToIgnore) ); // - in https assertEquals( response() .withHeader(HttpHeaders.CONTENT_TYPE, TEXT_PLAIN) .withStatusCode(HttpStatusCode.OK_200.code()) .withBody("some_body"), makeRequest( request() .withSecure(true) .withPath(calculatePath("some_path")) .withMethod("POST") .withBody("{" + System.getProperty("line.separator") + " \"id\": 1," + System.getProperty("line.separator") + " \"name\": \"A green door\"," + System.getProperty("line.separator") + " \"price\": 12.50," + System.getProperty("line.separator") + " \"tags\": [\"home\", \"green\"]" + System.getProperty("line.separator") + "}"), headersToIgnore) ); } @Test public void shouldReturnPDFResponseByMatchingPath() throws IOException { // when byte[] pdfBytes = IOUtils.toByteArray(getClass().getClassLoader().getResourceAsStream("test.pdf")); mockServerClient .when( request() .withPath(calculatePath("ws/rest/user/[0-9]+/document/[0-9]+\\.pdf")) ) .respond( response() .withStatusCode(HttpStatusCode.OK_200.code()) .withHeaders( header(HttpHeaders.CONTENT_TYPE, MediaType.PDF.toString()), header(HttpHeaders.CONTENT_DISPOSITION, "form-data; name=\"test.pdf\"; filename=\"test.pdf\""), header(HttpHeaders.CACHE_CONTROL, "must-revalidate, post-check=0, pre-check=0") ) .withBody(binary(pdfBytes)) ); // then // - in http assertEquals( response() .withStatusCode(HttpStatusCode.OK_200.code()) .withHeaders( header(HttpHeaders.CONTENT_DISPOSITION, "form-data; name=\"test.pdf\"; filename=\"test.pdf\""), header(HttpHeaders.CACHE_CONTROL, "must-revalidate, post-check=0, pre-check=0"), header(HttpHeaders.CONTENT_TYPE, MediaType.PDF.toString()) ) .withBody(binary(pdfBytes)), makeRequest( request() .withPath(calculatePath("ws/rest/user/1/document/2.pdf")) .withMethod("GET"), headersToIgnore) ); // - in https assertEquals( response() .withStatusCode(HttpStatusCode.OK_200.code()) .withHeaders( header(HttpHeaders.CONTENT_DISPOSITION, "form-data; name=\"test.pdf\"; filename=\"test.pdf\""), header(HttpHeaders.CACHE_CONTROL, "must-revalidate, post-check=0, pre-check=0"), header(HttpHeaders.CONTENT_TYPE, MediaType.PDF.toString()) ) .withBody(binary(pdfBytes)), makeRequest( request() .withSecure(true) .withPath(calculatePath("ws/rest/user/1/document/2.pdf")) .withMethod("GET"), headersToIgnore) ); } @Test public void shouldReturnPNGResponseByMatchingPath() throws IOException { // when byte[] pngBytes = IOUtils.toByteArray(getClass().getClassLoader().getResourceAsStream("test.png")); mockServerClient .when( request() .withPath(calculatePath("ws/rest/user/[0-9]+/icon/[0-9]+\\.png")) ) .respond( response() .withStatusCode(HttpStatusCode.OK_200.code()) .withHeaders( header(HttpHeaders.CONTENT_TYPE, MediaType.PNG.toString()), header(HttpHeaders.CONTENT_DISPOSITION, "form-data; name=\"test.png\"; filename=\"test.png\"") ) .withBody(binary(pngBytes)) ); // then // - in http assertEquals( response() .withStatusCode(HttpStatusCode.OK_200.code()) .withHeaders( header(HttpHeaders.CONTENT_DISPOSITION, "form-data; name=\"test.png\"; filename=\"test.png\""), header(HttpHeaders.CONTENT_TYPE, MediaType.PNG.toString()) ) .withBody(binary(pngBytes)), makeRequest( request() .withPath(calculatePath("ws/rest/user/1/icon/1.png")) .withMethod("GET"), headersToIgnore) ); // - in https assertEquals( response() .withStatusCode(HttpStatusCode.OK_200.code()) .withHeaders( header(HttpHeaders.CONTENT_DISPOSITION, "form-data; name=\"test.png\"; filename=\"test.png\""), header(HttpHeaders.CONTENT_TYPE, MediaType.PNG.toString()) ) .withBody(binary(pngBytes)), makeRequest( request() .withSecure(true) .withPath(calculatePath("ws/rest/user/1/icon/1.png")) .withMethod("GET"), headersToIgnore) ); } @Test public void shouldReturnPDFResponseByMatchingBinaryPDFBody() throws IOException { // when byte[] pdfBytes = IOUtils.toByteArray(getClass().getClassLoader().getResourceAsStream("test.pdf")); mockServerClient .when( request().withBody(binary(pdfBytes)) ) .respond( response() .withStatusCode(HttpStatusCode.OK_200.code()) .withHeaders( header(HttpHeaders.CONTENT_TYPE, MediaType.PDF.toString()), header(HttpHeaders.CONTENT_DISPOSITION, "form-data; name=\"test.pdf\"; filename=\"test.pdf\""), header(HttpHeaders.CACHE_CONTROL, "must-revalidate, post-check=0, pre-check=0") ) .withBody(binary(pdfBytes)) ); // then // - in http assertEquals( response() .withStatusCode(HttpStatusCode.OK_200.code()) .withHeaders( header(HttpHeaders.CONTENT_DISPOSITION, "form-data; name=\"test.pdf\"; filename=\"test.pdf\""), header(HttpHeaders.CACHE_CONTROL, "must-revalidate, post-check=0, pre-check=0"), header(HttpHeaders.CONTENT_TYPE, MediaType.PDF.toString()) ) .withBody(binary(pdfBytes)), makeRequest( request() .withPath(calculatePath("ws/rest/user/1/document/2.pdf")) .withBody(binary(pdfBytes)) .withMethod("POST"), headersToIgnore) ); // - in https assertEquals( response() .withStatusCode(HttpStatusCode.OK_200.code()) .withHeaders( header(HttpHeaders.CONTENT_DISPOSITION, "form-data; name=\"test.pdf\"; filename=\"test.pdf\""), header(HttpHeaders.CACHE_CONTROL, "must-revalidate, post-check=0, pre-check=0"), header(HttpHeaders.CONTENT_TYPE, MediaType.PDF.toString()) ) .withBody(binary(pdfBytes)), makeRequest( request() .withSecure(true) .withPath(calculatePath("ws/rest/user/1/document/2.pdf")) .withBody(binary(pdfBytes)) .withMethod("POST"), headersToIgnore) ); } @Test public void shouldReturnPNGResponseByMatchingBinaryPNGBody() throws IOException { // when byte[] pngBytes = IOUtils.toByteArray(getClass().getClassLoader().getResourceAsStream("test.png")); mockServerClient .when( request().withBody(binary(pngBytes)) ) .respond( response() .withStatusCode(HttpStatusCode.OK_200.code()) .withHeaders( header(HttpHeaders.CONTENT_TYPE, MediaType.PNG.toString()), header(HttpHeaders.CONTENT_DISPOSITION, "form-data; name=\"test.png\"; filename=\"test.png\"") ) .withBody(binary(pngBytes)) ); // then // - in http assertEquals( response() .withStatusCode(HttpStatusCode.OK_200.code()) .withHeaders( header(HttpHeaders.CONTENT_DISPOSITION, "form-data; name=\"test.png\"; filename=\"test.png\""), header(HttpHeaders.CONTENT_TYPE, MediaType.PNG.toString()) ) .withBody(binary(pngBytes)), makeRequest( request() .withPath(calculatePath("ws/rest/user/1/icon/1.png")) .withBody(binary(pngBytes)) .withMethod("POST"), headersToIgnore) ); // - in https assertEquals( response() .withStatusCode(HttpStatusCode.OK_200.code()) .withHeaders( header(HttpHeaders.CONTENT_DISPOSITION, "form-data; name=\"test.png\"; filename=\"test.png\""), header(HttpHeaders.CONTENT_TYPE, MediaType.PNG.toString()) ) .withBody(binary(pngBytes)), makeRequest( request() .withSecure(true) .withPath(calculatePath("ws/rest/user/1/icon/1.png")) .withBody(binary(pngBytes)) .withMethod("POST"), headersToIgnore) ); } @Test public void shouldReturnResponseForExpectationWithDelay() { // when mockServerClient .when( request() .withPath(calculatePath("some_path1")) ) .respond( response() .withBody("some_body1") .withDelay(new Delay(TimeUnit.MILLISECONDS, 10)) ); mockServerClient .when( request() .withPath(calculatePath("some_path2")) ) .respond( response() .withBody("some_body2") .withDelay(new Delay(TimeUnit.MILLISECONDS, 20)) ); // then // - in http assertEquals( response() .withHeader(HttpHeaders.CONTENT_TYPE, TEXT_PLAIN) .withStatusCode(HttpStatusCode.OK_200.code()) .withBody("some_body2"), makeRequest( request() .withPath(calculatePath("some_path2")), headersToIgnore) ); assertEquals( response() .withHeader(HttpHeaders.CONTENT_TYPE, TEXT_PLAIN) .withStatusCode(HttpStatusCode.OK_200.code()) .withBody("some_body1"), makeRequest( request() .withPath(calculatePath("some_path1")), headersToIgnore) ); // - in https assertEquals( response() .withHeader(HttpHeaders.CONTENT_TYPE, TEXT_PLAIN) .withStatusCode(HttpStatusCode.OK_200.code()) .withBody("some_body2"), makeRequest( request() .withSecure(true) .withPath(calculatePath("some_path2")), headersToIgnore) ); assertEquals( response() .withHeader(HttpHeaders.CONTENT_TYPE, TEXT_PLAIN) .withStatusCode(HttpStatusCode.OK_200.code()) .withBody("some_body1"), makeRequest( request() .withSecure(true) .withPath(calculatePath("some_path1")), headersToIgnore) ); } @Test public void shouldReturnResponseByMatchingPathAndMethod() { // when mockServerClient .when( request() .withMethod("GET") .withPath(calculatePath("some_pathRequest")) ) .respond( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body_response") ); // then // - in http assertEquals( response() .withHeader(HttpHeaders.CONTENT_TYPE, TEXT_PLAIN) .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body_response"), makeRequest( request() .withMethod("GET") .withPath(calculatePath("some_pathRequest")) .withQueryStringParameters( param("queryStringParameterOneName", "queryStringParameterOneValue"), param("queryStringParameterTwoName", "queryStringParameterTwoValue") ) .withHeaders(header("headerNameRequest", "headerValueRequest")) .withCookies(cookie("cookieNameRequest", "cookieValueRequest")), headersToIgnore) ); // - in https assertEquals( response() .withHeader(HttpHeaders.CONTENT_TYPE, TEXT_PLAIN) .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body_response"), makeRequest( request() .withMethod("GET") .withSecure(true) .withPath(calculatePath("some_pathRequest")) .withQueryStringParameters( param("queryStringParameterOneName", "queryStringParameterOneValue"), param("queryStringParameterTwoName", "queryStringParameterTwoValue") ) .withHeaders(header("headerNameRequest", "headerValueRequest")) .withCookies(cookie("cookieNameRequest", "cookieValueRequest")), headersToIgnore) ); } @Test public void shouldReturnResponseByNotMatchingPathWithNotOperator() { // when mockServerClient .when( request() .withPath(not(calculatePath("some_path"))) ) .respond( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body_response") ); // then // - in http assertEquals( response() .withHeader(HttpHeaders.CONTENT_TYPE, TEXT_PLAIN) .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body_response"), makeRequest( request() .withPath(calculatePath("some_other_path")), headersToIgnore) ); // - in https assertEquals( response() .withHeader(HttpHeaders.CONTENT_TYPE, TEXT_PLAIN) .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body_response"), makeRequest( request() .withPath(calculatePath("some_other_path")), headersToIgnore) ); } @Test public void shouldReturnResponseByNotMatchingMethodWithNotOperator() { // when mockServerClient .when( request() .withMethod(not("GET")) ) .respond( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body_response") ); // then // - in http assertEquals( response() .withHeader(HttpHeaders.CONTENT_TYPE, TEXT_PLAIN) .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body_response"), makeRequest( request() .withMethod("POST"), headersToIgnore) ); // - in https assertEquals( response() .withHeader(HttpHeaders.CONTENT_TYPE, TEXT_PLAIN) .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body_response"), makeRequest( request() .withMethod("POST"), headersToIgnore) ); } @Test public void shouldReturnResponseByMatchingPathAndMethodAndBody() { // when mockServerClient .when( request() .withMethod("POST") .withPath(calculatePath("some_pathRequest")) .withBody("some_bodyRequest") ) .respond( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body_response") .withHeaders(header("headerNameResponse", "headerValueResponse")) ); // then // - in http assertEquals( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body_response") .withHeaders( header("headerNameResponse", "headerValueResponse"), header(HttpHeaders.CONTENT_TYPE, TEXT_PLAIN) ), makeRequest( request() .withMethod("POST") .withPath(calculatePath("some_pathRequest")) .withQueryStringParameters( param("queryStringParameterOneName", "queryStringParameterOneValue"), param("queryStringParameterTwoName", "queryStringParameterTwoValue") ) .withBody("some_bodyRequest") .withHeaders(header("headerNameRequest", "headerValueRequest")) .withCookies(cookie("cookieNameRequest", "cookieValueRequest")), headersToIgnore) ); // - in https assertEquals( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body_response") .withHeaders( header("headerNameResponse", "headerValueResponse"), header(HttpHeaders.CONTENT_TYPE, TEXT_PLAIN) ), makeRequest( request() .withMethod("POST") .withSecure(true) .withPath(calculatePath("some_pathRequest")) .withQueryStringParameters( param("queryStringParameterOneName", "queryStringParameterOneValue"), param("queryStringParameterTwoName", "queryStringParameterTwoValue") ) .withBody("some_bodyRequest") .withHeaders(header("headerNameRequest", "headerValueRequest")) .withCookies(cookie("cookieNameRequest", "cookieValueRequest")), headersToIgnore) ); } @Test public void shouldReturnResponseByMatchingPathAndMethodAndQueryStringParameters() { // when mockServerClient .when( request() .withMethod("GET") .withPath(calculatePath("some_pathRequest")) .withQueryStringParameters( param("queryStringParameterOneName", "queryStringParameterOneValue"), param("queryStringParameterTwoName", "queryStringParameterTwoValue") ) ) .respond( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body_response") .withCookies(cookie("cookieNameResponse", "cookieValueResponse")) ); // then // - in http assertEquals( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body_response") .withCookies(cookie("cookieNameResponse", "cookieValueResponse")) .withHeaders( header("Set-Cookie", "cookieNameResponse=cookieValueResponse"), header(HttpHeaders.CONTENT_TYPE, TEXT_PLAIN) ), makeRequest( request() .withMethod("GET") .withPath(calculatePath("some_pathRequest")) .withQueryStringParameters( param("queryStringParameterOneName", "queryStringParameterOneValue"), param("queryStringParameterTwoName", "queryStringParameterTwoValue") ) .withHeaders(header("headerNameRequest", "headerValueRequest")) .withCookies(cookie("cookieNameRequest", "cookieValueRequest")), headersToIgnore) ); // - in https assertEquals( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body_response") .withCookies(cookie("cookieNameResponse", "cookieValueResponse")) .withHeaders( header("Set-Cookie", "cookieNameResponse=cookieValueResponse"), header(HttpHeaders.CONTENT_TYPE, TEXT_PLAIN) ), makeRequest( request() .withMethod("GET") .withSecure(true) .withPath(calculatePath("some_pathRequest")) .withQueryStringParameters( param("queryStringParameterOneName", "queryStringParameterOneValue"), param("queryStringParameterTwoName", "queryStringParameterTwoValue") ) .withHeaders(header("headerNameRequest", "headerValueRequest")) .withCookies(cookie("cookieNameRequest", "cookieValueRequest")), headersToIgnore) ); } @Test public void shouldReturnResponseByMatchingPathAndMethodAndHeaders() { // when mockServerClient .when( request() .withMethod("GET") .withPath(calculatePath("some_pathRequest")) .withHeaders( header("requestHeaderNameOne", "requestHeaderValueOne_One", "requestHeaderValueOne_Two"), header("requestHeaderNameTwo", "requestHeaderValueTwo") ) ) .respond( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body_response") .withCookies(cookie("cookieNameResponse", "cookieValueResponse")) ); // then // - in http assertEquals( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body_response") .withCookies(cookie("cookieNameResponse", "cookieValueResponse")) .withHeaders( header("Set-Cookie", "cookieNameResponse=cookieValueResponse"), header(HttpHeaders.CONTENT_TYPE, TEXT_PLAIN) ), makeRequest( request() .withMethod("GET") .withPath(calculatePath("some_pathRequest")) .withHeaders( header("requestHeaderNameOne", "requestHeaderValueOne_One", "requestHeaderValueOne_Two"), header("requestHeaderNameTwo", "requestHeaderValueTwo") ) .withCookies(cookie("cookieNameRequest", "cookieValueRequest")), headersToIgnore) ); // - in https assertEquals( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body_response") .withCookies(cookie("cookieNameResponse", "cookieValueResponse")) .withHeaders( header("Set-Cookie", "cookieNameResponse=cookieValueResponse"), header(HttpHeaders.CONTENT_TYPE, TEXT_PLAIN) ), makeRequest( request() .withMethod("GET") .withSecure(true) .withPath(calculatePath("some_pathRequest")) .withHeaders( header("requestHeaderNameOne", "requestHeaderValueOne_One", "requestHeaderValueOne_Two"), header("requestHeaderNameTwo", "requestHeaderValueTwo") ) .withCookies(cookie("cookieNameRequest", "cookieValueRequest")), headersToIgnore) ); } @Test public void shouldReturnResponseByMatchingPathAndMethodAndCookies() { // when mockServerClient .when( request() .withMethod("GET") .withPath(calculatePath("some_pathRequest")) .withCookies( cookie("requestCookieNameOne", "requestCookieValueOne"), cookie("requestCookieNameTwo", "requestCookieValueTwo") ) ) .respond( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body_response") .withCookies( cookie("responseCookieNameOne", "responseCookieValueOne"), cookie("responseCookieNameTwo", "responseCookieValueTwo") ) ); // then // - in http - cookie objects assertEquals( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body_response") .withCookies( cookie("responseCookieNameOne", "responseCookieValueOne"), cookie("responseCookieNameTwo", "responseCookieValueTwo") ) .withHeaders( header("Set-Cookie", "responseCookieNameOne=responseCookieValueOne", "responseCookieNameTwo=responseCookieValueTwo"), header(HttpHeaders.CONTENT_TYPE, TEXT_PLAIN) ), makeRequest( request() .withMethod("GET") .withPath(calculatePath("some_pathRequest")) .withHeaders( header("headerNameRequest", "headerValueRequest"), header(HttpHeaders.CONTENT_TYPE, TEXT_PLAIN) ) .withCookies( cookie("requestCookieNameOne", "requestCookieValueOne"), cookie("requestCookieNameTwo", "requestCookieValueTwo") ), headersToIgnore) ); // - in http - cookie header assertEquals( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body_response") .withCookies( cookie("responseCookieNameOne", "responseCookieValueOne"), cookie("responseCookieNameTwo", "responseCookieValueTwo") ) .withHeaders( header("Set-Cookie", "responseCookieNameOne=responseCookieValueOne", "responseCookieNameTwo=responseCookieValueTwo"), header(HttpHeaders.CONTENT_TYPE, TEXT_PLAIN) ), makeRequest( request() .withMethod("GET") .withPath(calculatePath("some_pathRequest")) .withHeaders( header("headerNameRequest", "headerValueRequest"), header("Cookie", "requestCookieNameOne=requestCookieValueOne; requestCookieNameTwo=requestCookieValueTwo") ), headersToIgnore) ); // - in https - cookie objects assertEquals( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body_response") .withCookies( cookie("responseCookieNameOne", "responseCookieValueOne"), cookie("responseCookieNameTwo", "responseCookieValueTwo") ) .withHeaders( header("Set-Cookie", "responseCookieNameOne=responseCookieValueOne", "responseCookieNameTwo=responseCookieValueTwo"), header(HttpHeaders.CONTENT_TYPE, TEXT_PLAIN) ), makeRequest( request() .withMethod("GET") .withSecure(true) .withPath(calculatePath("some_pathRequest")) .withHeaders( header("headerNameRequest", "headerValueRequest") ) .withCookies( cookie("requestCookieNameOne", "requestCookieValueOne"), cookie("requestCookieNameTwo", "requestCookieValueTwo") ), headersToIgnore) ); // - in https - cookie header assertEquals( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body_response") .withCookies( cookie("responseCookieNameOne", "responseCookieValueOne"), cookie("responseCookieNameTwo", "responseCookieValueTwo") ) .withHeaders( header("Set-Cookie", "responseCookieNameOne=responseCookieValueOne", "responseCookieNameTwo=responseCookieValueTwo"), header(HttpHeaders.CONTENT_TYPE, TEXT_PLAIN) ), makeRequest( request() .withMethod("GET") .withSecure(true) .withPath(calculatePath("some_pathRequest")) .withHeaders( header("headerNameRequest", "headerValueRequest"), header("Cookie", "requestCookieNameOne=requestCookieValueOne; requestCookieNameTwo=requestCookieValueTwo") ), headersToIgnore) ); } @Test public void shouldReturnResponseByMatchingPathAndMethodAndQueryStringParametersAndBodyParameters() { // when mockServerClient .when( request() .withMethod("POST") .withPath(calculatePath("some_pathRequest")) .withQueryStringParameters( param("queryStringParameterOneName", "queryStringParameterOneValueOne", "queryStringParameterOneValueTwo"), param("queryStringParameterTwoName", "queryStringParameterTwoValue") ) .withBody(params(param("bodyParameterName", "bodyParameterValue"))) ) .respond( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body") ); // then // - in http - url query string assertEquals( response() .withHeader(HttpHeaders.CONTENT_TYPE, TEXT_PLAIN) .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body"), makeRequest( request() .withMethod("POST") .withPath(calculatePath("some_pathRequest")) .withQueryStringParameters( param("queryStringParameterOneName", "queryStringParameterOneValueOne", "queryStringParameterOneValueTwo"), param("queryStringParameterTwoName", "queryStringParameterTwoValue") ) .withBody(params(param("bodyParameterName", "bodyParameterValue"))), headersToIgnore) ); // - in https - query string parameter objects assertEquals( response() .withHeader(HttpHeaders.CONTENT_TYPE, TEXT_PLAIN) .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body"), makeRequest( request() .withSecure(true) .withMethod("POST") .withPath(calculatePath("some_pathRequest")) .withQueryStringParameters( param("queryStringParameterOneName", "queryStringParameterOneValueOne", "queryStringParameterOneValueTwo"), param("queryStringParameterTwoName", "queryStringParameterTwoValue") ) .withBody(params(param("bodyParameterName", "bodyParameterValue"))), headersToIgnore) ); } @Test public void shouldReturnResponseByMatchingPathAndMethodAndQueryStringParametersAndBody() { // when mockServerClient .when( request() .withMethod("POST") .withPath(calculatePath("some_pathRequest")) .withQueryStringParameters( param("queryStringParameterOneName", "queryStringParameterOneValueOne", "queryStringParameterOneValueTwo"), param("queryStringParameterTwoName", "queryStringParameterTwoValue") ) .withBody("some_bodyRequest") ) .respond( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body_response") .withHeaders(header("headerNameResponse", "headerValueResponse")) .withCookies(cookie("cookieNameResponse", "cookieValueResponse")) ); // then // - in http - url query string assertEquals( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body_response") .withCookies(cookie("cookieNameResponse", "cookieValueResponse")) .withHeaders( header("headerNameResponse", "headerValueResponse"), header("Set-Cookie", "cookieNameResponse=cookieValueResponse"), header(HttpHeaders.CONTENT_TYPE, TEXT_PLAIN) ), makeRequest( request() .withMethod("POST") .withPath(calculatePath("some_pathRequest")) .withQueryStringParameters( param("queryStringParameterOneName", "queryStringParameterOneValueOne", "queryStringParameterOneValueTwo"), param("queryStringParameterTwoName", "queryStringParameterTwoValue") ) .withBody("some_bodyRequest") .withHeaders(header("headerNameRequest", "headerValueRequest")) .withCookies(cookie("cookieNameRequest", "cookieValueRequest")), headersToIgnore) ); // - in http - query string parameter objects assertEquals( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body_response") .withCookies(cookie("cookieNameResponse", "cookieValueResponse")) .withHeaders( header("headerNameResponse", "headerValueResponse"), header("Set-Cookie", "cookieNameResponse=cookieValueResponse"), header(HttpHeaders.CONTENT_TYPE, TEXT_PLAIN) ), makeRequest( request() .withMethod("POST") .withPath(calculatePath("some_pathRequest")) .withQueryStringParameters( param("queryStringParameterOneName", "queryStringParameterOneValueOne", "queryStringParameterOneValueTwo"), param("queryStringParameterTwoName", "queryStringParameterTwoValue") ) .withBody("some_bodyRequest") .withHeaders(header("headerNameRequest", "headerValueRequest")) .withCookies(cookie("cookieNameRequest", "cookieValueRequest")), headersToIgnore) ); // - in https - url string and query string parameter objects assertEquals( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body_response") .withCookies(cookie("cookieNameResponse", "cookieValueResponse")) .withHeaders( header("headerNameResponse", "headerValueResponse"), header("Set-Cookie", "cookieNameResponse=cookieValueResponse"), header(HttpHeaders.CONTENT_TYPE, TEXT_PLAIN) ), makeRequest( request() .withMethod("POST") .withPath(calculatePath("some_pathRequest")) .withQueryStringParameters( param("queryStringParameterOneName", "queryStringParameterOneValueOne", "queryStringParameterOneValueTwo"), param("queryStringParameterTwoName", "queryStringParameterTwoValue") ) .withBody("some_bodyRequest") .withHeaders(header("headerNameRequest", "headerValueRequest")) .withCookies(cookie("cookieNameRequest", "cookieValueRequest")), headersToIgnore) ); } @Test public void shouldReturnResponseByMatchingPathAndMethodAndBodyParameters() { // when mockServerClient .when( request() .withMethod("POST") .withPath(calculatePath("some_pathRequest")) .withBody(params( param("bodyParameterOneName", "Parameter One Value One", "Parameter One Value Two"), param("bodyParameterTwoName", "Parameter Two") )) ) .respond( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body_response") .withHeaders(header("headerNameResponse", "headerValueResponse")) .withCookies(cookie("cookieNameResponse", "cookieValueResponse")) ); // then // - in http - body string assertEquals( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body_response") .withCookies(cookie("cookieNameResponse", "cookieValueResponse")) .withHeaders( header("headerNameResponse", "headerValueResponse"), header("Set-Cookie", "cookieNameResponse=cookieValueResponse"), header(HttpHeaders.CONTENT_TYPE, TEXT_PLAIN) ), makeRequest( request() .withMethod("POST") .withPath(calculatePath("some_pathRequest")) .withBody(new StringBody("bodyParameterOneName=Parameter+One+Value+One" + "&bodyParameterOneName=Parameter+One+Value+Two" + "&bodyParameterTwoName=Parameter+Two")) .withHeaders(header("headerNameRequest", "headerValueRequest")) .withCookies(cookie("cookieNameRequest", "cookieValueRequest")), headersToIgnore) ); // - in http - body parameter objects assertEquals( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body_response") .withCookies(cookie("cookieNameResponse", "cookieValueResponse")) .withHeaders( header("headerNameResponse", "headerValueResponse"), header("Set-Cookie", "cookieNameResponse=cookieValueResponse"), header(HttpHeaders.CONTENT_TYPE, TEXT_PLAIN) ), makeRequest( request() .withMethod("POST") .withPath(calculatePath("some_pathRequest")) .withBody(params( param("bodyParameterOneName", "Parameter One Value One", "Parameter One Value Two"), param("bodyParameterTwoName", "Parameter Two") )) .withHeaders(header("headerNameRequest", "headerValueRequest")) .withCookies(cookie("cookieNameRequest", "cookieValueRequest")), headersToIgnore) ); // - in https - url string and query string parameter objects assertEquals( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body_response") .withCookies(cookie("cookieNameResponse", "cookieValueResponse")) .withHeaders( header("headerNameResponse", "headerValueResponse"), header("Set-Cookie", "cookieNameResponse=cookieValueResponse"), header(HttpHeaders.CONTENT_TYPE, TEXT_PLAIN) ), makeRequest( request() .withMethod("POST") .withPath(calculatePath("some_pathRequest")) .withBody(params( param("bodyParameterOneName", "Parameter One Value One", "Parameter One Value Two"), param("bodyParameterTwoName", "Parameter Two") )) .withHeaders(header("headerNameRequest", "headerValueRequest")) .withCookies(cookie("cookieNameRequest", "cookieValueRequest")), headersToIgnore) ); } @Test public void shouldReturnResponseByMatchingPathAndMethodAndParametersAndHeadersAndCookies() { // when mockServerClient .when( request() .withMethod("PUT") .withPath(calculatePath("some_pathRequest")) .withBody(new StringBody("bodyParameterOneName=Parameter+One+Value+One" + "&bodyParameterOneName=Parameter+One+Value+Two" + "&bodyParameterTwoName=Parameter+Two")) .withHeaders(header("headerNameRequest", "headerValueRequest")) .withCookies(cookie("cookieNameRequest", "cookieValueRequest")) ) .respond( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body_response") .withHeaders(header("headerNameResponse", "headerValueResponse")) .withCookies(cookie("cookieNameResponse", "cookieValueResponse")) ); // then // - in http - body string assertEquals( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body_response") .withCookies(cookie("cookieNameResponse", "cookieValueResponse")) .withHeaders( header("headerNameResponse", "headerValueResponse"), header("Set-Cookie", "cookieNameResponse=cookieValueResponse"), header(HttpHeaders.CONTENT_TYPE, TEXT_PLAIN) ), makeRequest( request() .withMethod("PUT") .withPath(calculatePath("some_pathRequest")) .withBody(new StringBody("bodyParameterOneName=Parameter+One+Value+One" + "&bodyParameterOneName=Parameter+One+Value+Two" + "&bodyParameterTwoName=Parameter+Two")) .withHeaders( header("headerNameRequest", "headerValueRequest"), header("Cookie", "cookieNameRequest=cookieValueRequest") ), headersToIgnore) ); // - in http - body parameter objects assertEquals( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body_response") .withCookies(cookie("cookieNameResponse", "cookieValueResponse")) .withHeaders( header("headerNameResponse", "headerValueResponse"), header("Set-Cookie", "cookieNameResponse=cookieValueResponse"), header(HttpHeaders.CONTENT_TYPE, TEXT_PLAIN) ), makeRequest( request() .withMethod("PUT") .withPath(calculatePath("some_pathRequest")) .withBody(params( param("bodyParameterOneName", "Parameter One Value One", "Parameter One Value Two"), param("bodyParameterTwoName", "Parameter Two") )) .withHeaders(header("headerNameRequest", "headerValueRequest")) .withCookies(cookie("cookieNameRequest", "cookieValueRequest")), headersToIgnore) ); } @Test public void shouldReturnResponseByNotMatchingBodyParameterWithNotOperatorForNameAndValue() { // when mockServerClient .when( request() .withMethod("POST") .withPath(calculatePath("some_pathRequest")) .withBody(params( param(not("bodyParameterOneName"), not("Parameter One Value One"), not("Parameter One Value Two")), param("bodyParameterTwoName", "Parameter Two") )) ) .respond( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body_response") ); // then // wrong query string parameter name assertEquals( response() .withHeader(HttpHeaders.CONTENT_TYPE, TEXT_PLAIN) .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body_response"), makeRequest( request() .withMethod("POST") .withPath(calculatePath("some_pathRequest")) .withBody(params( param("OTHERBodyParameterOneName", "Parameter One Value One", "Parameter One Value Two"), param("bodyParameterTwoName", "Parameter Two") )) .withHeaders(header("headerNameRequest", "headerValueRequest")) .withCookies(cookie("cookieNameRequest", "cookieValueRequest")), headersToIgnore) ); // wrong query string parameter name assertEquals( response() .withHeader(HttpHeaders.CONTENT_TYPE, TEXT_PLAIN) .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body_response"), makeRequest( request() .withMethod("POST") .withPath(calculatePath("some_pathRequest")) .withBody(new StringBody("OTHERBodyParameterOneName=Parameter+One+Value+One" + "&OTHERBodyParameterOneName=Parameter+One+Value+Two" + "&bodyParameterTwoName=Parameter+Two")) .withHeaders(header("headerNameRequest", "headerValueRequest")) .withCookies(cookie("cookieNameRequest", "cookieValueRequest")), headersToIgnore) ); // wrong query string parameter value assertEquals( response() .withHeader(HttpHeaders.CONTENT_TYPE, TEXT_PLAIN) .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body_response"), makeRequest( request() .withMethod("POST") .withPath(calculatePath("some_pathRequest")) .withBody(params( param("bodyParameterOneName", "OTHER Parameter One Value One", "OTHER Parameter One Value Two"), param("bodyParameterTwoName", "Parameter Two") )) .withHeaders(header("headerNameRequest", "headerValueRequest")) .withCookies(cookie("cookieNameRequest", "cookieValueRequest")), headersToIgnore) ); // wrong query string parameter value assertEquals( response() .withHeader(HttpHeaders.CONTENT_TYPE, TEXT_PLAIN) .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body_response"), makeRequest( request() .withMethod("POST") .withPath(calculatePath("some_pathRequest")) .withBody(new StringBody("bodyParameterOneName=OTHER Parameter+One+Value+One" + "&bodyParameterOneName=OTHER Parameter+One+Value+Two" + "&bodyParameterTwoName=Parameter+Two")) .withHeaders(header("headerNameRequest", "headerValueRequest")) .withCookies(cookie("cookieNameRequest", "cookieValueRequest")), headersToIgnore) ); } @Test public void shouldReturnResponseByNotMatchingBodyParameterWithNotOperatorForName() { // when mockServerClient .when( request() .withMethod("POST") .withPath(calculatePath("some_pathRequest")) .withBody(params( param(not("bodyParameterOneName"), string("Parameter One Value One"), string("Parameter One Value Two")), param("bodyParameterTwoName", "Parameter Two") )) ) .respond( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body_response") ); // then // wrong query string parameter name assertEquals( response() .withHeader(HttpHeaders.CONTENT_TYPE, TEXT_PLAIN) .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body_response"), makeRequest( request() .withMethod("POST") .withPath(calculatePath("some_pathRequest")) .withBody(params( param("OTHERBodyParameterOneName", "Parameter One Value One", "Parameter One Value Two"), param("bodyParameterTwoName", "Parameter Two") )) .withHeaders(header("headerNameRequest", "headerValueRequest")) .withCookies(cookie("cookieNameRequest", "cookieValueRequest")), headersToIgnore) ); // wrong query string parameter name assertEquals( response() .withHeader(HttpHeaders.CONTENT_TYPE, TEXT_PLAIN) .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body_response"), makeRequest( request() .withMethod("POST") .withPath(calculatePath("some_pathRequest")) .withBody(new StringBody("OTHERBodyParameterOneName=Parameter+One+Value+One" + "&OTHERBodyParameterOneName=Parameter+One+Value+Two" + "&bodyParameterTwoName=Parameter+Two")) .withHeaders(header("headerNameRequest", "headerValueRequest")) .withCookies(cookie("cookieNameRequest", "cookieValueRequest")), headersToIgnore) ); } @Test public void shouldReturnResponseByNotMatchingBodyParameterWithNotOperatorForValue() { // when mockServerClient .when( request() .withMethod("POST") .withPath(calculatePath("some_pathRequest")) .withBody(params( param(string("bodyParameterOneName"), not("Parameter One Value One"), not("Parameter One Value Two")), param("bodyParameterTwoName", "Parameter Two") )) ) .respond( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body_response") ); // then // wrong query string parameter value assertEquals( response() .withHeader(HttpHeaders.CONTENT_TYPE, TEXT_PLAIN) .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body_response"), makeRequest( request() .withMethod("POST") .withPath(calculatePath("some_pathRequest")) .withBody(params( param("bodyParameterOneName", "OTHER Parameter One Value One", "OTHER Parameter One Value Two"), param("bodyParameterTwoName", "Parameter Two") )) .withHeaders(header("headerNameRequest", "headerValueRequest")) .withCookies(cookie("cookieNameRequest", "cookieValueRequest")), headersToIgnore) ); // wrong query string parameter value assertEquals( response() .withHeader(HttpHeaders.CONTENT_TYPE, TEXT_PLAIN) .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body_response"), makeRequest( request() .withMethod("POST") .withPath(calculatePath("some_pathRequest")) .withBody(new StringBody("bodyParameterOneName=OTHER Parameter+One+Value+One" + "&bodyParameterOneName=OTHER Parameter+One+Value+Two" + "&bodyParameterTwoName=Parameter+Two")) .withHeaders(header("headerNameRequest", "headerValueRequest")) .withCookies(cookie("cookieNameRequest", "cookieValueRequest")), headersToIgnore) ); } @Test public void shouldReturnResponseByNotMatchingQueryStringParameterWithNotOperatorForNameAndValue() { // when mockServerClient .when( request() .withMethod("POST") .withPath(calculatePath("some_pathRequest")) .withQueryStringParameters( param(not("queryStringParameterOneName"), not("Parameter One Value One"), not("Parameter One Value Two")), param("queryStringParameterTwoName", "Parameter Two") ) ) .respond( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body_response") ); // then // wrong query string parameter name assertEquals( response() .withHeader(HttpHeaders.CONTENT_TYPE, TEXT_PLAIN) .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body_response"), makeRequest( request() .withMethod("POST") .withPath(calculatePath("some_pathRequest")) .withQueryStringParameters( param("OTHERQueryStringParameterOneName", "Parameter One Value One", "Parameter One Value Two"), param("queryStringParameterTwoName", "Parameter Two") ), headersToIgnore) ); // wrong query string parameter value assertEquals( response() .withHeader(HttpHeaders.CONTENT_TYPE, TEXT_PLAIN) .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body_response"), makeRequest( request() .withMethod("POST") .withPath(calculatePath("some_pathRequest")) .withQueryStringParameters( param("queryStringParameterOneName", "OTHER Parameter One Value One", "OTHER Parameter One Value Two"), param("queryStringParameterTwoName", "Parameter Two") ), headersToIgnore) ); } @Test public void shouldReturnResponseByNotMatchingQueryStringParameterWithNotOperatorForName() { // when mockServerClient .when( request() .withMethod("POST") .withPath(calculatePath("some_pathRequest")) .withQueryStringParameters( param(not("queryStringParameterOneName"), string("Parameter One Value One"), string("Parameter One Value Two")), param("queryStringParameterTwoName", "Parameter Two") ) ) .respond( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body_response") ); // then // wrong query string parameter name assertEquals( response() .withHeader(HttpHeaders.CONTENT_TYPE, TEXT_PLAIN) .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body_response"), makeRequest( request() .withMethod("POST") .withPath(calculatePath("some_pathRequest")) .withQueryStringParameters( param("OTHERQueryStringParameterOneName", "Parameter One Value One", "Parameter One Value Two"), param("queryStringParameterTwoName", "Parameter Two") ), headersToIgnore) ); } @Test public void shouldReturnResponseByNotMatchingQueryStringParameterWithNotOperatorForValue() { // when mockServerClient .when( request() .withMethod("POST") .withPath(calculatePath("some_pathRequest")) .withQueryStringParameters( param(string("queryStringParameterOneName"), not("Parameter One Value One"), not("Parameter One Value Two")), param("queryStringParameterTwoName", "Parameter Two") ) ) .respond( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body_response") ); // then // wrong query string parameter value assertEquals( response() .withHeader(HttpHeaders.CONTENT_TYPE, TEXT_PLAIN) .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body_response"), makeRequest( request() .withMethod("POST") .withPath(calculatePath("some_pathRequest")) .withQueryStringParameters( param("queryStringParameterOneName", "OTHER Parameter One Value One", "OTHER Parameter One Value Two"), param("queryStringParameterTwoName", "Parameter Two") ), headersToIgnore) ); } @Test public void shouldReturnResponseByNotMatchingCookieWithNotOperatorForNameAndValue() { // when mockServerClient .when( request() .withMethod("GET") .withPath(calculatePath("some_pathRequest")) .withCookies( cookie(not("requestCookieNameOne"), not("requestCookieValueOne")), cookie("requestCookieNameTwo", "requestCookieValueTwo") ) ) .respond( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body_response") ); // then // wrong query string cookie name assertEquals( response() .withHeader(HttpHeaders.CONTENT_TYPE, TEXT_PLAIN) .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body_response"), makeRequest( request() .withMethod("GET") .withPath(calculatePath("some_pathRequest")) .withCookies( cookie("OTHERrequestCookieNameOne", "requestCookieValueOne"), cookie("requestCookieNameTwo", "requestCookieValueTwo") ), headersToIgnore) ); // wrong query string cookie value assertEquals( response() .withHeader(HttpHeaders.CONTENT_TYPE, TEXT_PLAIN) .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body_response"), makeRequest( request() .withMethod("GET") .withPath(calculatePath("some_pathRequest")) .withCookies( cookie("requestCookieNameOne", "OTHERrequestCookieValueOne"), cookie("requestCookieNameTwo", "requestCookieValueTwo") ), headersToIgnore) ); } @Test public void shouldReturnResponseByNotMatchingCookieWithNotOperatorForName() { // when mockServerClient .when( request() .withMethod("GET") .withPath(calculatePath("some_pathRequest")) .withCookies( cookie(not("requestCookieNameOne"), string("requestCookieValueOne")), cookie("requestCookieNameTwo", "requestCookieValueTwo") ) ) .respond( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body_response") ); // then // wrong query string cookie name assertEquals( response() .withHeader(HttpHeaders.CONTENT_TYPE, TEXT_PLAIN) .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body_response"), makeRequest( request() .withMethod("GET") .withPath(calculatePath("some_pathRequest")) .withCookies( cookie("OTHERrequestCookieNameOne", "requestCookieValueOne"), cookie("requestCookieNameTwo", "requestCookieValueTwo") ), headersToIgnore) ); } @Test public void shouldReturnResponseByNotMatchingCookieWithNotOperatorForValue() { // when mockServerClient .when( request() .withMethod("GET") .withPath(calculatePath("some_pathRequest")) .withCookies( cookie(string("requestCookieNameOne"), not("requestCookieValueOne")), cookie("requestCookieNameTwo", "requestCookieValueTwo") ) ) .respond( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body_response") ); // then // wrong query string cookie value assertEquals( response() .withHeader(HttpHeaders.CONTENT_TYPE, TEXT_PLAIN) .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body_response"), makeRequest( request() .withMethod("GET") .withPath(calculatePath("some_pathRequest")) .withCookies( cookie("requestCookieNameOne", "OTHERrequestCookieValueOne"), cookie("requestCookieNameTwo", "requestCookieValueTwo") ), headersToIgnore) ); } @Test public void shouldReturnResponseByNotMatchingHeaderWithNotOperatorForNameAndValue() { // when mockServerClient .when( request() .withMethod("GET") .withPath(calculatePath("some_pathRequest")) .withHeaders( header(not("requestHeaderNameOne"), not("requestHeaderValueOne")), header("requestHeaderNameTwo", "requestHeaderValueTwo") ) ) .respond( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body_response") ); // then // wrong query string header name assertEquals( response() .withHeader(HttpHeaders.CONTENT_TYPE, TEXT_PLAIN) .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body_response"), makeRequest( request() .withMethod("GET") .withPath(calculatePath("some_pathRequest")) .withHeaders( header("OTHERrequestHeaderNameOne", "requestHeaderValueOne"), header("requestHeaderNameTwo", "requestHeaderValueTwo") ), headersToIgnore) ); // wrong query string header value assertEquals( response() .withHeader(HttpHeaders.CONTENT_TYPE, TEXT_PLAIN) .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body_response"), makeRequest( request() .withMethod("GET") .withPath(calculatePath("some_pathRequest")) .withHeaders( header("requestHeaderNameOne", "OTHERrequestHeaderValueOne"), header("requestHeaderNameTwo", "requestHeaderValueTwo") ), headersToIgnore) ); } @Test public void shouldReturnResponseByNotMatchingHeaderWithNotOperatorForName() { // when mockServerClient .when( request() .withMethod("GET") .withPath(calculatePath("some_pathRequest")) .withHeaders( header(not("requestHeaderNameOne"), string("requestHeaderValueOne")), header("requestHeaderNameTwo", "requestHeaderValueTwo") ) ) .respond( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body_response") ); // then // wrong query string header name assertEquals( response() .withHeader(HttpHeaders.CONTENT_TYPE, TEXT_PLAIN) .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body_response"), makeRequest( request() .withMethod("GET") .withPath(calculatePath("some_pathRequest")) .withHeaders( header("OTHERrequestHeaderNameOne", "requestHeaderValueOne"), header("requestHeaderNameTwo", "requestHeaderValueTwo") ), headersToIgnore) ); } @Test public void shouldReturnResponseByNotMatchingHeaderWithNotOperatorForValue() { // when mockServerClient .when( request() .withMethod("GET") .withPath(calculatePath("some_pathRequest")) .withHeaders( header(string("requestHeaderNameOne"), not("requestHeaderValueOne")), header("requestHeaderNameTwo", "requestHeaderValueTwo") ) ) .respond( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body_response") ); // then // wrong query string header value assertEquals( response() .withHeader(HttpHeaders.CONTENT_TYPE, TEXT_PLAIN) .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body_response"), makeRequest( request() .withMethod("GET") .withPath(calculatePath("some_pathRequest")) .withHeaders( header("requestHeaderNameOne", "OTHERrequestHeaderValueOne"), header("requestHeaderNameTwo", "requestHeaderValueTwo") ), headersToIgnore) ); } @Test public void shouldNotReturnResponseForWhenTimeToLiveExpired() { // when mockServerClient .when( request().withPath(calculatePath("some_path")), exactly(2), TimeToLive.exactly(TimeUnit.SECONDS, 5L) ) .respond( response().withBody("some_body").withDelay(TimeUnit.SECONDS, 5L) ); // then assertEquals( response() .withHeader(HttpHeaders.CONTENT_TYPE, TEXT_PLAIN) .withStatusCode(HttpStatusCode.OK_200.code()) .withBody("some_body"), makeRequest( request() .withPath(calculatePath("some_path")), headersToIgnore) ); // - in http assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()), makeRequest( request() .withPath(calculatePath("some_path")), headersToIgnore) ); // - in https assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()), makeRequest( request() .withSecure(true) .withPath(calculatePath("some_path")), headersToIgnore) ); } @Test public void shouldNotReturnResponseForNonMatchingBody() { // when mockServerClient .when( request() .withMethod("GET") .withPath(calculatePath("some_path")) .withQueryStringParameters( param("queryStringParameterOneName", "queryStringParameterOneValue"), param("queryStringParameterTwoName", "queryStringParameterTwoValue") ) .withBody(exact("some_body")) .withHeaders(header("headerName", "headerValue")) .withCookies(cookie("cookieName", "cookieValue")) ) .respond( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body") .withHeaders(header("headerName", "headerValue")) .withCookies(cookie("cookieName", "cookieValue")) ); // then // - in http assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()), makeRequest( request() .withMethod("GET") .withPath(calculatePath("some_path")) .withQueryStringParameters( param("queryStringParameterOneName", "queryStringParameterOneValue"), param("queryStringParameterTwoName", "queryStringParameterTwoValue") ) .withBody(exact("some_other_body")) .withHeaders(header("headerName", "headerValue")) .withCookies(cookie("cookieName", "cookieValue")), headersToIgnore) ); // - in https assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()), makeRequest( request() .withMethod("GET") .withSecure(true) .withPath(calculatePath("some_path")) .withQueryStringParameters( param("queryStringParameterOneName", "queryStringParameterOneValue"), param("queryStringParameterTwoName", "queryStringParameterTwoValue") ) .withBody(exact("some_other_body")) .withHeaders(header("headerName", "headerValue")) .withCookies(cookie("cookieName", "cookieValue")), headersToIgnore) ); } @Test public void shouldNotReturnResponseForMatchingBodyWithNotOperator() { // when mockServerClient .when( request() .withBody(Not.not(json("{" + System.getProperty("line.separator") + " \"id\": 1," + System.getProperty("line.separator") + " \"name\": \"A green door\"," + System.getProperty("line.separator") + " \"price\": 12.50," + System.getProperty("line.separator") + " \"tags\": [\"home\", \"green\"]" + System.getProperty("line.separator") + "}"))), exactly(2) ) .respond( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body") ); // then // - in http assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()), makeRequest( request() .withPath(calculatePath("some_path")) .withMethod("POST") .withBody("{" + System.getProperty("line.separator") + " \"id\": 1," + System.getProperty("line.separator") + " \"extra_ignored_field\": \"some value\"," + System.getProperty("line.separator") + " \"name\": \"A green door\"," + System.getProperty("line.separator") + " \"price\": 12.50," + System.getProperty("line.separator") + " \"tags\": [\"home\", \"green\"]" + System.getProperty("line.separator") + "}"), headersToIgnore) ); // - in https assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()), makeRequest( request() .withSecure(true) .withPath(calculatePath("some_path")) .withMethod("POST") .withBody("{" + System.getProperty("line.separator") + " \"id\": 1," + System.getProperty("line.separator") + " \"extra_ignored_array\": [\"one\", \"two\"]," + System.getProperty("line.separator") + " \"name\": \"A green door\"," + System.getProperty("line.separator") + " \"price\": 12.50," + System.getProperty("line.separator") + " \"tags\": [\"home\", \"green\"]" + System.getProperty("line.separator") + "}"), headersToIgnore) ); } @Test public void shouldNotReturnResponseForNonMatchingXPathBody() { // when mockServerClient.when(request().withBody(new XPathBody("/bookstore/book[price>35]/price")), exactly(2)).respond(response().withBody("some_body")); // then // - in http assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()), makeRequest( request() .withSecure(true) .withPath(calculatePath("some_path")) .withMethod("POST") .withBody(new StringBody("" + "<?xml version=\"1.0\" encoding=\"ISO-8859-1\"?>" + System.getProperty("line.separator") + "<bookstore>" + System.getProperty("line.separator") + " <book category=\"COOKING\">" + System.getProperty("line.separator") + " <title lang=\"en\">Everyday Italian</title>" + System.getProperty("line.separator") + " <author>Giada De Laurentiis</author>" + System.getProperty("line.separator") + " <year>2005</year>" + System.getProperty("line.separator") + " <price>30.00</price>" + System.getProperty("line.separator") + " </book>" + System.getProperty("line.separator") + " <book category=\"CHILDREN\">" + System.getProperty("line.separator") + " <title lang=\"en\">Harry Potter</title>" + System.getProperty("line.separator") + " <author>J K. Rowling</author>" + System.getProperty("line.separator") + " <year>2005</year>" + System.getProperty("line.separator") + " <price>29.99</price>" + System.getProperty("line.separator") + " </book>" + System.getProperty("line.separator") + " <book category=\"WEB\">" + System.getProperty("line.separator") + " <title lang=\"en\">Learning XML</title>" + System.getProperty("line.separator") + " <author>Erik T. Ray</author>" + System.getProperty("line.separator") + " <year>2003</year>" + System.getProperty("line.separator") + " <price>31.95</price>" + System.getProperty("line.separator") + " </book>" + System.getProperty("line.separator") + "</bookstore>")), headersToIgnore) ); // - in https assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()), makeRequest( request() .withSecure(true) .withPath(calculatePath("some_path")) .withMethod("POST") .withBody(new StringBody("" + "<?xml version=\"1.0\" encoding=\"ISO-8859-1\"?>" + System.getProperty("line.separator") + "<bookstore>" + System.getProperty("line.separator") + " <book category=\"COOKING\">" + System.getProperty("line.separator") + " <title lang=\"en\">Everyday Italian</title>" + System.getProperty("line.separator") + " <author>Giada De Laurentiis</author>" + System.getProperty("line.separator") + " <year>2005</year>" + System.getProperty("line.separator") + " <price>30.00</price>" + System.getProperty("line.separator") + " </book>" + System.getProperty("line.separator") + " <book category=\"CHILDREN\">" + System.getProperty("line.separator") + " <title lang=\"en\">Harry Potter</title>" + System.getProperty("line.separator") + " <author>J K. Rowling</author>" + System.getProperty("line.separator") + " <year>2005</year>" + System.getProperty("line.separator") + " <price>29.99</price>" + System.getProperty("line.separator") + " </book>" + System.getProperty("line.separator") + " <book category=\"WEB\">" + System.getProperty("line.separator") + " <title lang=\"en\">Learning XML</title>" + System.getProperty("line.separator") + " <author>Erik T. Ray</author>" + System.getProperty("line.separator") + " <year>2003</year>" + System.getProperty("line.separator") + " <price>31.95</price>" + System.getProperty("line.separator") + " </book>" + System.getProperty("line.separator") + "</bookstore>")), headersToIgnore) ); } @Test public void shouldNotReturnResponseForNonMatchingJsonBody() { // when mockServerClient.when(request().withBody(json("{" + System.getProperty("line.separator") + " \"id\": 1," + System.getProperty("line.separator") + " \"name\": \"A green door\"," + System.getProperty("line.separator") + " \"price\": 12.50," + System.getProperty("line.separator") + " \"tags\": [\"home\", \"green\"]" + System.getProperty("line.separator") + "}")), exactly(2)).respond(response().withBody("some_body")); // then // - in http assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()), makeRequest( request() .withPath(calculatePath("some_path")) .withMethod("POST") .withBody("{" + System.getProperty("line.separator") + " \"id\": 1," + System.getProperty("line.separator") + " \"name\": \"---- XXXX WRONG VALUE XXXX ----\"," + System.getProperty("line.separator") + " \"price\": 12.50," + System.getProperty("line.separator") + " \"tags\": [\"home\", \"green\"]" + System.getProperty("line.separator") + "}"), headersToIgnore) ); // - in https assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()), makeRequest( request() .withSecure(true) .withPath(calculatePath("some_path")) .withMethod("POST") .withBody("{" + System.getProperty("line.separator") + " \"id\": 1," + System.getProperty("line.separator") + " \"name\": \"---- XXXX WRONG VALUE XXXX ----\"," + System.getProperty("line.separator") + " \"price\": 12.50," + System.getProperty("line.separator") + " \"tags\": [\"home\", \"green\"]" + System.getProperty("line.separator") + "}"), headersToIgnore) ); } @Test public void shouldNotReturnResponseForNonMatchingJsonBodyWithMatchType() { // when mockServerClient .when( request() .withBody(json("{" + System.getProperty("line.separator") + " \"id\": 1," + System.getProperty("line.separator") + " \"name\": \"A green door\"," + System.getProperty("line.separator") + " \"price\": 12.50," + System.getProperty("line.separator") + " \"tags\": [\"home\", \"green\"]" + System.getProperty("line.separator") + "}", MatchType.STRICT)), exactly(2)) .respond( response() .withBody("some_body") ); // then // - in http assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()), makeRequest( request() .withPath(calculatePath("some_path")) .withMethod("POST") .withBody("{" + System.getProperty("line.separator") + " \"id\": 1," + System.getProperty("line.separator") + " \"extra field\": \"some value\"," + System.getProperty("line.separator") + " \"name\": \"A green door\"," + System.getProperty("line.separator") + " \"price\": 12.50," + System.getProperty("line.separator") + " \"tags\": [\"home\", \"green\"]" + System.getProperty("line.separator") + "}"), headersToIgnore) ); // - in https assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()), makeRequest( request() .withSecure(true) .withPath(calculatePath("some_path")) .withMethod("POST") .withBody("{" + System.getProperty("line.separator") + " \"id\": 1," + System.getProperty("line.separator") + " \"extra field\": \"some value\"," + System.getProperty("line.separator") + " \"name\": \"A green door\"," + System.getProperty("line.separator") + " \"price\": 12.50," + System.getProperty("line.separator") + " \"tags\": [\"home\", \"green\"]" + System.getProperty("line.separator") + "}"), headersToIgnore) ); } @Test public void shouldNotReturnResponseForNonMatchingJsonSchema() { // when mockServerClient.when(request().withBody(jsonSchema("{" + System.getProperty("line.separator") + " \"$schema\": \"http://json-schema.org/draft-04/schema#\"," + System.getProperty("line.separator") + " \"title\": \"Product\"," + System.getProperty("line.separator") + " \"description\": \"A product from Acme's catalog\"," + System.getProperty("line.separator") + " \"type\": \"object\"," + System.getProperty("line.separator") + " \"properties\": {" + System.getProperty("line.separator") + " \"id\": {" + System.getProperty("line.separator") + " \"description\": \"The unique identifier for a product\"," + System.getProperty("line.separator") + " \"type\": \"integer\"" + System.getProperty("line.separator") + " }," + System.getProperty("line.separator") + " \"name\": {" + System.getProperty("line.separator") + " \"description\": \"Name of the product\"," + System.getProperty("line.separator") + " \"type\": \"string\"" + System.getProperty("line.separator") + " }," + System.getProperty("line.separator") + " \"price\": {" + System.getProperty("line.separator") + " \"type\": \"number\"," + System.getProperty("line.separator") + " \"minimum\": 0," + System.getProperty("line.separator") + " \"exclusiveMinimum\": true" + System.getProperty("line.separator") + " }," + System.getProperty("line.separator") + " \"tags\": {" + System.getProperty("line.separator") + " \"type\": \"array\"," + System.getProperty("line.separator") + " \"items\": {" + System.getProperty("line.separator") + " \"type\": \"string\"" + System.getProperty("line.separator") + " }," + System.getProperty("line.separator") + " \"minItems\": 1," + System.getProperty("line.separator") + " \"uniqueItems\": true" + System.getProperty("line.separator") + " }" + System.getProperty("line.separator") + " }," + System.getProperty("line.separator") + " \"required\": [\"id\", \"name\", \"price\"]" + System.getProperty("line.separator") + "}")), exactly(2)).respond(response().withBody("some_body")); // then // - in http assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()), makeRequest( request() .withPath(calculatePath("some_path")) .withMethod("POST") .withBody("{" + System.getProperty("line.separator") + " \"id\": 1," + System.getProperty("line.separator") + " \"wrong field name\": \"A green door\"," + System.getProperty("line.separator") + " \"price\": 12.50," + System.getProperty("line.separator") + " \"tags\": [\"home\", \"green\"]" + System.getProperty("line.separator") + "}"), headersToIgnore) ); // - in https assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()), makeRequest( request() .withSecure(true) .withPath(calculatePath("some_path")) .withMethod("POST") .withBody("{" + System.getProperty("line.separator") + " \"id\": 1," + System.getProperty("line.separator") + " \"name\": \"A green door\"," + System.getProperty("line.separator") + " \"wrong field name\": 12.50," + System.getProperty("line.separator") + " \"tags\": [\"home\", \"green\"]" + System.getProperty("line.separator") + "}"), headersToIgnore) ); } @Test public void shouldNotReturnResponseForNonMatchingPath() { // when mockServerClient .when( request() .withMethod("GET") .withPath(calculatePath("some_path")) .withQueryStringParameters( param("queryStringParameterOneName", "queryStringParameterOneValue"), param("queryStringParameterTwoName", "queryStringParameterTwoValue") ) .withBody(exact("some_body")) .withHeaders(header("headerName", "headerValue")) .withCookies(cookie("cookieName", "cookieValue")) ) .respond( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body") .withHeaders(header("headerName", "headerValue")) .withCookies(cookie("cookieName", "cookieValue")) ); // then // - in http assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()), makeRequest( request() .withMethod("GET") .withPath(calculatePath("some_other_path")) .withQueryStringParameters( param("queryStringParameterOneName", "queryStringParameterOneValue"), param("queryStringParameterTwoName", "queryStringParameterTwoValue") ) .withBody(exact("some_body")) .withHeaders(header("headerName", "headerValue")) .withCookies(cookie("cookieName", "cookieValue")), headersToIgnore) ); // - in https assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()), makeRequest( request() .withMethod("GET") .withSecure(true) .withPath(calculatePath("some_other_path")) .withQueryStringParameters( param("queryStringParameterOneName", "queryStringParameterOneValue"), param("queryStringParameterTwoName", "queryStringParameterTwoValue") ) .withBody(exact("some_body")) .withHeaders(header("headerName", "headerValue")) .withCookies(cookie("cookieName", "cookieValue")), headersToIgnore) ); } @Test public void shouldNotReturnResponseForMatchingPathWithNotOperator() { // when mockServerClient .when( request() .withPath(not(calculatePath("some_path"))) ) .respond( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body_response") ); // then // - in http assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()), makeRequest( request() .withPath(calculatePath("some_path")), headersToIgnore) ); // - in https assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()), makeRequest( request() .withPath(calculatePath("some_path")), headersToIgnore) ); } @Test public void shouldNotReturnResponseForMatchingMethodWithNotOperator() { // when mockServerClient .when( request() .withMethod(not("GET")) ) .respond( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body_response") ); // then // - in http assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()), makeRequest( request() .withMethod("GET"), headersToIgnore) ); // - in https assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()), makeRequest( request() .withMethod("GET"), headersToIgnore) ); } @Test public void shouldNotReturnResponseForNonMatchingBodyParameterName() { // when mockServerClient .when( request() .withMethod("POST") .withPath(calculatePath("some_pathRequest")) .withBody(params( param("bodyParameterOneName", "Parameter One Value One", "Parameter One Value Two"), param("bodyParameterTwoName", "Parameter Two") )) ) .respond( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body_response") .withHeaders(header("headerNameResponse", "headerValueResponse")) .withCookies(cookie("cookieNameResponse", "cookieValueResponse")) ); // then // wrong query string parameter name assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()), makeRequest( request() .withMethod("POST") .withPath(calculatePath("some_pathRequest")) .withBody(params( param("OTHERBodyParameterOneName", "Parameter One Value One", "Parameter One Value Two"), param("bodyParameterTwoName", "Parameter Two") )) .withHeaders(header("headerNameRequest", "headerValueRequest")) .withCookies(cookie("cookieNameRequest", "cookieValueRequest")), headersToIgnore) ); // wrong query string parameter name assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()), makeRequest( request() .withMethod("POST") .withPath(calculatePath("some_pathRequest")) .withBody(new StringBody("OTHERBodyParameterOneName=Parameter+One+Value+One" + "&bodyParameterOneName=Parameter+One+Value+Two" + "&bodyParameterTwoName=Parameter+Two")) .withHeaders(header("headerNameRequest", "headerValueRequest")) .withCookies(cookie("cookieNameRequest", "cookieValueRequest")), headersToIgnore) ); } @Test public void shouldNotReturnResponseForMatchingBodyParameterWithNotOperator() { // when mockServerClient .when( request() .withMethod("POST") .withPath(calculatePath("some_pathRequest")) .withBody(params( param(not("bodyParameterOneName"), not("Parameter One Value One"), not("Parameter One Value Two")), param("bodyParameterTwoName", "Parameter Two") )) ) .respond( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body_response") ); // then // wrong query string parameter name assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()), makeRequest( request() .withMethod("POST") .withPath(calculatePath("some_pathRequest")) .withBody(params( param("bodyParameterOneName", "Parameter One Value One", "Parameter One Value Two"), param("bodyParameterTwoName", "Parameter Two") )) .withHeaders(header("headerNameRequest", "headerValueRequest")) .withCookies(cookie("cookieNameRequest", "cookieValueRequest")), headersToIgnore) ); // wrong query string parameter name assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()), makeRequest( request() .withMethod("POST") .withPath(calculatePath("some_pathRequest")) .withBody(new StringBody("bodyParameterOneName=Other Parameter+One+Value+One" + "&bodyParameterOneName=Parameter+One+Value+Two" + "&bodyParameterTwoName=Parameter+Two")) .withHeaders(header("headerNameRequest", "headerValueRequest")) .withCookies(cookie("cookieNameRequest", "cookieValueRequest")), headersToIgnore) ); } @Test public void shouldNotReturnResponseForNonMatchingBodyParameterValue() { // when mockServerClient .when( request() .withMethod("POST") .withPath(calculatePath("some_pathRequest")) .withBody(params( param("bodyParameterOneName", "Parameter One Value One", "Parameter One Value Two"), param("bodyParameterTwoName", "Parameter Two") )) ) .respond( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body_response") .withHeaders(header("headerNameResponse", "headerValueResponse")) .withCookies(cookie("cookieNameResponse", "cookieValueResponse")) ); // then // wrong body parameter value assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()), makeRequest( request() .withMethod("POST") .withPath(calculatePath("some_pathRequest")) .withBody(params( param("bodyParameterOneName", "Other Parameter One Value One", "Parameter One Value Two"), param("bodyParameterTwoName", "Parameter Two") )) .withHeaders(header("headerNameRequest", "headerValueRequest")) .withCookies(cookie("cookieNameRequest", "cookieValueRequest")), headersToIgnore) ); // wrong body parameter value assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()), makeRequest( request() .withMethod("POST") .withPath(calculatePath("some_pathRequest")) .withBody(new StringBody("bodyParameterOneName=Other Parameter+One+Value+One" + "&bodyParameterOneName=Parameter+One+Value+Two" + "&bodyParameterTwoName=Parameter+Two")) .withHeaders(header("headerNameRequest", "headerValueRequest")) .withCookies(cookie("cookieNameRequest", "cookieValueRequest")), headersToIgnore) ); } @Test public void shouldNotReturnResponseForNonMatchingQueryStringParameterName() { // when mockServerClient .when( request() .withMethod("POST") .withPath(calculatePath("some_pathRequest")) .withQueryStringParameters( param("queryStringParameterOneName", "queryStringParameterOneValueOne", "queryStringParameterOneValueTwo"), param("queryStringParameterTwoName", "queryStringParameterTwoValue") ) .withBody("some_bodyRequest") ) .respond( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body_response") .withHeaders(header("headerNameResponse", "headerValueResponse")) .withCookies(cookie("cookieNameResponse", "cookieValueResponse")) ); // then // wrong query string parameter name assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()), makeRequest( request() .withMethod("POST") .withPath(calculatePath("some_pathRequest")) .withQueryStringParameters( param("OTHERQueryStringParameterOneName", "queryStringParameterOneValueOne", "queryStringParameterOneValueTwo"), param("queryStringParameterTwoName", "queryStringParameterTwoValue") ) .withBody("some_bodyRequest") .withHeaders( header("headerNameRequest", "headerValueRequest") ) .withCookies(cookie("cookieNameRequest", "cookieValueRequest")), headersToIgnore) ); } @Test public void shouldNotReturnResponseForNonMatchingQueryStringParameterValue() { // when mockServerClient .when( request() .withMethod("POST") .withPath(calculatePath("some_pathRequest")) .withQueryStringParameters( param("queryStringParameterOneName", "queryStringParameterOneValueOne", "queryStringParameterOneValueTwo"), param("queryStringParameterTwoName", "queryStringParameterTwoValue") ) .withBody("some_bodyRequest") ) .respond( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body_response") .withHeaders(header("headerNameResponse", "headerValueResponse")) .withCookies(cookie("cookieNameResponse", "cookieValueResponse")) ); // then // wrong query string parameter value assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()), makeRequest( request() .withMethod("POST") .withPath(calculatePath("some_pathRequest")) .withQueryStringParameters( param("queryStringParameterOneName", "OTHERqueryStringParameterOneValueOne", "queryStringParameterOneValueTwo"), param("queryStringParameterTwoName", "queryStringParameterTwoValue") ) .withBody("some_bodyRequest") .withHeaders(header("headerNameRequest", "headerValueRequest")) .withCookies(cookie("cookieNameRequest", "cookieValueRequest")), headersToIgnore) ); } @Test public void shouldNotReturnResponseForMatchingQueryStringParameterWithNotOperator() { // when mockServerClient .when( request() .withMethod("POST") .withPath(calculatePath("some_pathRequest")) .withQueryStringParameters( param(not("queryStringParameterOneName"), not("Parameter One Value One"), not("Parameter One Value Two")), param("queryStringParameterTwoName", "Parameter Two") ) ) .respond( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body_response") ); // then // wrong query string parameter name assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()), makeRequest( request() .withMethod("POST") .withPath(calculatePath("some_pathRequest")) .withQueryStringParameters( param("queryStringParameterOneName", "Parameter One Value One", "Parameter One Value Two"), param("queryStringParameterTwoName", "Parameter Two") ), headersToIgnore) ); // wrong query string parameter name assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()), makeRequest( request() .withMethod("POST") .withPath(calculatePath("some_pathRequest")) .withQueryStringParameters( param("queryStringParameterOneName", "Parameter One Value One", "Parameter One Value Two"), param("queryStringParameterTwoName", "Parameter Two") ), headersToIgnore) ); } @Test public void shouldNotReturnResponseForNonMatchingCookieName() { // when mockServerClient .when( request() .withMethod("GET") .withPath(calculatePath("some_path")) .withQueryStringParameters( param("queryStringParameterOneName", "queryStringParameterOneValue"), param("queryStringParameterTwoName", "queryStringParameterTwoValue") ) .withBody(exact("some_body")) .withHeaders(header("headerName", "headerValue")) .withCookies(cookie("cookieName", "cookieValue")) ) .respond( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body") .withHeaders(header("headerName", "headerValue")) .withCookies(cookie("cookieName", "cookieValue")) ); // then // - in http assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()), makeRequest( request() .withMethod("GET") .withPath(calculatePath("some_path")) .withQueryStringParameters( param("queryStringParameterOneName", "queryStringParameterOneValue"), param("queryStringParameterTwoName", "queryStringParameterTwoValue") ) .withBody(exact("some_body")) .withHeaders(header("headerName", "headerValue")) .withCookies(cookie("cookieOtherName", "cookieValue")), headersToIgnore) ); // - in https assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()), makeRequest( request() .withMethod("GET") .withSecure(true) .withPath(calculatePath("some_path")) .withQueryStringParameters( param("queryStringParameterOneName", "queryStringParameterOneValue"), param("queryStringParameterTwoName", "queryStringParameterTwoValue") ) .withBody(exact("some_body")) .withHeaders(header("headerName", "headerValue")) .withCookies(cookie("cookieOtherName", "cookieValue")), headersToIgnore) ); } @Test public void shouldNotReturnResponseForNonMatchingCookieValue() { // when mockServerClient .when( request() .withMethod("GET") .withPath(calculatePath("some_path")) .withQueryStringParameters( param("queryStringParameterOneName", "queryStringParameterOneValue"), param("queryStringParameterTwoName", "queryStringParameterTwoValue") ) .withBody(exact("some_body")) .withHeaders(header("headerName", "headerValue")) .withCookies(cookie("cookieName", "cookieValue")) ) .respond( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body") .withHeaders(header("headerName", "headerValue")) .withCookies(cookie("cookieName", "cookieValue")) ); // then // - in http assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()), makeRequest( request() .withMethod("GET") .withPath(calculatePath("some_path")) .withQueryStringParameters( param("queryStringParameterOneName", "queryStringParameterOneValue"), param("queryStringParameterTwoName", "queryStringParameterTwoValue") ) .withBody(exact("some_body")) .withHeaders(header("headerName", "headerValue")) .withCookies(cookie("cookieName", "cookieOtherValue")), headersToIgnore) ); // - in https assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()), makeRequest( request() .withMethod("GET") .withSecure(true) .withPath(calculatePath("some_path")) .withQueryStringParameters( param("queryStringParameterOneName", "queryStringParameterOneValue"), param("queryStringParameterTwoName", "queryStringParameterTwoValue") ) .withBody(exact("some_body")) .withHeaders(header("headerName", "headerValue")) .withCookies(cookie("cookieName", "cookieOtherValue")), headersToIgnore) ); } @Test public void shouldNotReturnResponseForMatchingCookieWithNotOperator() { // when mockServerClient .when( request() .withMethod("GET") .withPath(calculatePath("some_pathRequest")) .withCookies( cookie(not("requestCookieNameOne"), not("requestCookieValueOne")), cookie("requestCookieNameTwo", "requestCookieValueTwo") ) ) .respond( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body_response") ); // then // wrong query string parameter name assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()), makeRequest( request() .withMethod("GET") .withPath(calculatePath("some_pathRequest")) .withCookies( cookie("requestCookieNameOne", "requestCookieValueOne"), cookie("requestCookieNameTwo", "requestCookieValueTwo") ), headersToIgnore) ); // wrong query string parameter name assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()), makeRequest( request() .withMethod("GET") .withPath(calculatePath("some_pathRequest")) .withCookies( cookie("requestCookieNameOne", "requestCookieValueOne"), cookie("requestCookieNameTwo", "requestCookieValueTwo") ), headersToIgnore) ); } @Test public void shouldNotReturnResponseForNonMatchingHeaderName() { // when mockServerClient .when( request() .withMethod("GET") .withPath(calculatePath("some_path")) .withQueryStringParameters( param("queryStringParameterOneName", "queryStringParameterOneValue"), param("queryStringParameterTwoName", "queryStringParameterTwoValue") ) .withBody(exact("some_body")) .withHeaders(header("headerName", "headerValue")) .withCookies(cookie("cookieName", "cookieValue")) ) .respond( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body") .withHeaders(header("headerName", "headerValue")) .withCookies(cookie("cookieName", "cookieValue")) ); // then // - in http assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()), makeRequest( request() .withMethod("GET") .withPath(calculatePath("some_path")) .withQueryStringParameters( param("queryStringParameterOneName", "queryStringParameterOneValue"), param("queryStringParameterTwoName", "queryStringParameterTwoValue") ) .withBody(exact("some_body")) .withHeaders(header("headerOtherName", "headerValue")) .withCookies(cookie("cookieName", "cookieValue")), headersToIgnore) ); // - in https assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()), makeRequest( request() .withMethod("GET") .withSecure(true) .withPath(calculatePath("some_path")) .withQueryStringParameters( param("queryStringParameterOneName", "queryStringParameterOneValue"), param("queryStringParameterTwoName", "queryStringParameterTwoValue") ) .withBody(exact("some_body")) .withHeaders(header("headerOtherName", "headerValue")) .withCookies(cookie("cookieName", "cookieValue")), headersToIgnore) ); } @Test public void shouldNotReturnResponseForNonMatchingHeaderValue() { // when mockServerClient .when( request() .withMethod("GET") .withPath(calculatePath("some_path")) .withQueryStringParameters( param("queryStringParameterOneName", "queryStringParameterOneValue"), param("queryStringParameterTwoName", "queryStringParameterTwoValue") ) .withBody(exact("some_body")) .withHeaders(header("headerName", "headerValue")) .withCookies(cookie("cookieName", "cookieValue")) ) .respond( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body") .withHeaders(header("headerName", "headerValue")) .withCookies(cookie("cookieName", "cookieValue")) ); // then // - in http assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()), makeRequest( request() .withMethod("GET") .withPath(calculatePath("some_path")) .withQueryStringParameters( param("queryStringParameterOneName", "queryStringParameterOneValue"), param("queryStringParameterTwoName", "queryStringParameterTwoValue") ) .withBody(exact("some_body")) .withHeaders(header("headerName", "headerOtherValue")) .withCookies(cookie("cookieName", "cookieValue")), headersToIgnore) ); // - in https assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()), makeRequest( request() .withMethod("GET") .withSecure(true) .withPath(calculatePath("some_path")) .withQueryStringParameters( param("queryStringParameterOneName", "queryStringParameterOneValue"), param("queryStringParameterTwoName", "queryStringParameterTwoValue") ) .withBody(exact("some_body")) .withHeaders(header("headerName", "headerOtherValue")) .withCookies(cookie("cookieName", "cookieValue")), headersToIgnore) ); } @Test public void shouldNotReturnResponseForMatchingHeaderWithNotOperator() { // when mockServerClient .when( request() .withMethod("GET") .withPath(calculatePath("some_pathRequest")) .withHeaders( header(not("requestHeaderNameOne"), not("requestHeaderValueOne")), header("requestHeaderNameTwo", "requestHeaderValueTwo") ) ) .respond( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body_response") ); // then // wrong query string parameter name assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()), makeRequest( request() .withMethod("GET") .withPath(calculatePath("some_pathRequest")) .withHeaders( header("requestHeaderNameOne", "requestHeaderValueOne"), header("requestHeaderNameTwo", "requestHeaderValueTwo") ), headersToIgnore) ); // wrong query string parameter name assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()), makeRequest( request() .withMethod("GET") .withPath(calculatePath("some_pathRequest")) .withHeaders( header("requestHeaderNameOne", "requestHeaderValueOne"), header("requestHeaderNameTwo", "requestHeaderValueTwo") ), headersToIgnore) ); } @Test public void shouldVerifyReceivedRequests() { // when mockServerClient .when( request() .withPath(calculatePath("some_path")), exactly(2) ) .respond( response() .withBody("some_body") ); // then // - in http assertEquals( response() .withHeader(HttpHeaders.CONTENT_TYPE, TEXT_PLAIN) .withStatusCode(HttpStatusCode.OK_200.code()) .withBody("some_body"), makeRequest( request() .withPath(calculatePath("some_path")), headersToIgnore) ); mockServerClient.verify(request() .withPath(calculatePath("some_path"))); mockServerClient.verify(request() .withPath(calculatePath("some_path")), VerificationTimes.exactly(1)); // - in https assertEquals( response() .withHeader(HttpHeaders.CONTENT_TYPE, TEXT_PLAIN) .withStatusCode(HttpStatusCode.OK_200.code()) .withBody("some_body"), makeRequest( request() .withSecure(true) .withPath(calculatePath("some_path")), headersToIgnore) ); mockServerClient.verify(request().withPath(calculatePath("some_path")), VerificationTimes.atLeast(1)); mockServerClient.verify(request().withPath(calculatePath("some_path")), VerificationTimes.exactly(2)); } @Test public void shouldVerifyReceivedRequestInSsl() { // when mockServerClient .when( request() .withPath(calculatePath("some.*path")), exactly(2) ) .respond( response() .withBody("some_body") ); // then // - in http assertEquals( response() .withHeader(HttpHeaders.CONTENT_TYPE, TEXT_PLAIN) .withStatusCode(HttpStatusCode.OK_200.code()) .withBody("some_body"), makeRequest( request() .withPath(calculatePath("some_path")), headersToIgnore) ); mockServerClient.verify(request() .withPath(calculatePath("some_path")) .withSecure(false)); mockServerClient.verify(request() .withPath(calculatePath("some_path")) .withSecure(false), VerificationTimes.exactly(1)); // - in https assertEquals( response() .withHeader(HttpHeaders.CONTENT_TYPE, TEXT_PLAIN) .withStatusCode(HttpStatusCode.OK_200.code()) .withBody("some_body"), makeRequest( request() .withPath(calculatePath("some_secure_path")) .withSecure(true), headersToIgnore) ); mockServerClient.verify(request() .withPath(calculatePath("some_secure_path")) .withSecure(true)); mockServerClient.verify(request() .withPath(calculatePath("some_secure_path")) .withSecure(true), VerificationTimes.exactly(1)); } @Test public void shouldVerifyReceivedRequestsWithNoBody() { // when mockServerClient.when(request().withPath(calculatePath("some_path")), exactly(2)).respond(response()); // then // - in http assertEquals( response() .withStatusCode(HttpStatusCode.OK_200.code()), makeRequest( request() .withPath(calculatePath("some_path")), headersToIgnore) ); mockServerClient.verify(request() .withPath(calculatePath("some_path"))); mockServerClient.verify(request() .withPath(calculatePath("some_path")), VerificationTimes.exactly(1)); } @Test public void shouldVerifyNotEnoughRequestsReceived() { // when mockServerClient.when(request().withPath(calculatePath("some_path")), exactly(2)).respond(response().withBody("some_body")); // then assertEquals( response() .withHeader(HttpHeaders.CONTENT_TYPE, TEXT_PLAIN) .withStatusCode(HttpStatusCode.OK_200.code()) .withBody("some_body"), makeRequest( request() .withPath(calculatePath("some_path")), headersToIgnore) ); try { mockServerClient.verify(request() .withPath(calculatePath("some_path")), VerificationTimes.atLeast(2)); fail(); } catch (AssertionError ae) { assertThat(ae.getMessage(), startsWith("Request not found at least 2 times, expected:<{" + System.getProperty("line.separator") + " \"path\" : \"" + calculatePath("some_path") + "\"" + System.getProperty("line.separator") + "}> but was:<{" + System.getProperty("line.separator") + " \"method\" : \"GET\"," + System.getProperty("line.separator") + " \"path\" : \"" + calculatePath("some_path") + "\"," + System.getProperty("line.separator"))); } } @Test public void shouldVerifyTooManyRequestsReceived() { // when mockServerClient.when(request().withPath(calculatePath("some_path")), exactly(2)).respond(response().withBody("some_body")); // then assertEquals( response() .withHeader(HttpHeaders.CONTENT_TYPE, TEXT_PLAIN) .withStatusCode(HttpStatusCode.OK_200.code()) .withBody("some_body"), makeRequest( request() .withPath(calculatePath("some_path")), headersToIgnore) ); try { mockServerClient.verify(request() .withPath(calculatePath("some_path")), VerificationTimes.exactly(0)); fail(); } catch (AssertionError ae) { assertThat(ae.getMessage(), startsWith("Request not found exactly 0 times, expected:<{" + System.getProperty("line.separator") + " \"path\" : \"" + calculatePath("some_path") + "\"" + System.getProperty("line.separator") + "}> but was:<{" + System.getProperty("line.separator") + " \"method\" : \"GET\"," + System.getProperty("line.separator") + " \"path\" : \"" + calculatePath("some_path") + "\"," + System.getProperty("line.separator"))); } } @Test public void shouldVerifyNoMatchingRequestsReceived() { // when mockServerClient.when(request().withPath(calculatePath("some_path")), exactly(2)).respond(response().withBody("some_body")); // then assertEquals( response() .withHeader(HttpHeaders.CONTENT_TYPE, TEXT_PLAIN) .withStatusCode(HttpStatusCode.OK_200.code()) .withBody("some_body"), makeRequest( request() .withPath(calculatePath("some_path")), headersToIgnore) ); try { mockServerClient.verify(request() .withPath(calculatePath("some_other_path")), VerificationTimes.exactly(2)); fail(); } catch (AssertionError ae) { assertThat(ae.getMessage(), startsWith("Request not found exactly 2 times, expected:<{" + System.getProperty("line.separator") + " \"path\" : \"" + calculatePath("some_other_path") + "\"" + System.getProperty("line.separator") + "}> but was:<{" + System.getProperty("line.separator") + " \"method\" : \"GET\"," + System.getProperty("line.separator") + " \"path\" : \"" + calculatePath("some_path") + "\"," + System.getProperty("line.separator"))); } } @Test public void shouldVerifyNoRequestsReceived() { // when mockServerClient.reset(); // then mockServerClient.verifyZeroInteractions(); } @Test public void shouldNotVerifyNoRequestsReceived() { // when mockServerClient.when(request().withPath(calculatePath("some_path")), exactly(2)).respond(response().withBody("some_body")); // then assertEquals( response() .withHeader(HttpHeaders.CONTENT_TYPE, TEXT_PLAIN) .withStatusCode(HttpStatusCode.OK_200.code()) .withBody("some_body"), makeRequest( request() .withPath(calculatePath("some_path")), headersToIgnore) ); try { mockServerClient.verifyZeroInteractions(); fail(); } catch (AssertionError ae) { assertThat(ae.getMessage(), startsWith("Request not found exactly 0 times, expected:<{ }> but was:<{" + System.getProperty("line.separator") + " \"method\" : \"GET\"," + System.getProperty("line.separator") + " \"path\" : \"" + calculatePath("some_path") + "\"," + System.getProperty("line.separator"))); } } @Test public void shouldVerifyNoMatchingRequestsReceivedInSsl() { // when mockServerClient.when(request().withPath(calculatePath("some.*path")), exactly(2)).respond(response().withBody("some_body")); // then // - in http assertEquals( response() .withHeader(HttpHeaders.CONTENT_TYPE, TEXT_PLAIN) .withStatusCode(HttpStatusCode.OK_200.code()) .withBody("some_body"), makeRequest( request() .withPath(calculatePath("some_path")), headersToIgnore) ); try { mockServerClient.verify( request() .withPath(calculatePath("some_path")) .withSecure(true), VerificationTimes.atLeast(1) ); fail(); } catch (AssertionError ae) { assertThat(ae.getMessage(), startsWith("Request not found at least once, expected:<{" + System.getProperty("line.separator") + " \"path\" : \"" + calculatePath("some_path") + "\"," + System.getProperty("line.separator") + " \"secure\" : true" + System.getProperty("line.separator") + "}> but was:<{" + System.getProperty("line.separator") + " \"method\" : \"GET\"," + System.getProperty("line.separator") + " \"path\" : \"" + calculatePath("some_path") + "\"," + System.getProperty("line.separator"))); } // - in https assertEquals( response() .withHeader(HttpHeaders.CONTENT_TYPE, TEXT_PLAIN) .withStatusCode(HttpStatusCode.OK_200.code()) .withBody("some_body"), makeRequest( request() .withPath(calculatePath("some_secure_path")) .withSecure(true), headersToIgnore) ); try { mockServerClient.verify( request() .withPath(calculatePath("some_secure_path")) .withSecure(false), VerificationTimes.atLeast(1) ); fail(); } catch (AssertionError ae) { assertThat(ae.getMessage(), startsWith("Request not found at least once, expected:<{" + System.getProperty("line.separator") + " \"path\" : \"" + calculatePath("some_secure_path") + "\"," + System.getProperty("line.separator") + " \"secure\" : false" + System.getProperty("line.separator") + "}> but was:<[ {" + System.getProperty("line.separator") + " \"method\" : \"GET\"," + System.getProperty("line.separator") + " \"path\" : \"" + calculatePath("some_path") + "\"," + System.getProperty("line.separator"))); } } @Test public void shouldVerifySequenceOfRequestsReceived() { // when mockServerClient.when(request().withPath(calculatePath("some_path.*")), exactly(6)).respond(response().withBody("some_body")); // then assertEquals( response("some_body").withHeader(HttpHeaders.CONTENT_TYPE, TEXT_PLAIN), makeRequest( request().withPath(calculatePath("some_path_one")), headersToIgnore) ); assertEquals( response("some_body").withHeader(HttpHeaders.CONTENT_TYPE, TEXT_PLAIN), makeRequest( request().withPath(calculatePath("some_path_two")), headersToIgnore) ); assertEquals( response("some_body").withHeader(HttpHeaders.CONTENT_TYPE, TEXT_PLAIN), makeRequest( request().withPath(calculatePath("some_path_three")), headersToIgnore) ); mockServerClient.verify(request(calculatePath("some_path_one")), request(calculatePath("some_path_three"))); mockServerClient.verify(request(calculatePath("some_path_one")), request(calculatePath("some_path_two"))); mockServerClient.verify(request(calculatePath("some_path_one")), request(calculatePath("some_path_two")), request(calculatePath("some_path_three"))); } @Test public void shouldVerifySequenceOfRequestsReceivedIncludingThoseNotMatchingAnException() { // when mockServerClient.when(request().withPath(calculatePath("some_path.*")), exactly(4)).respond(response().withBody("some_body")); // then assertEquals( response("some_body").withHeader(HttpHeaders.CONTENT_TYPE, TEXT_PLAIN), makeRequest( request().withPath(calculatePath("some_path_one")), headersToIgnore) ); assertEquals( notFoundResponse(), makeRequest( request().withPath(calculatePath("not_found")), headersToIgnore) ); assertEquals( response("some_body").withHeader(HttpHeaders.CONTENT_TYPE, TEXT_PLAIN), makeRequest( request().withPath(calculatePath("some_path_three")), headersToIgnore) ); mockServerClient.verify(request(calculatePath("some_path_one")), request(calculatePath("some_path_three"))); mockServerClient.verify(request(calculatePath("some_path_one")), request(calculatePath("not_found"))); mockServerClient.verify(request(calculatePath("some_path_one")), request(calculatePath("not_found")), request(calculatePath("some_path_three"))); mockServerClient.verify(request(calculatePath("some_path_one")), request(calculatePath("not_found")), request(calculatePath("some_path_three"))); } @Test public void shouldRetrieveSequenceOfRequestsReceivedIncludingThoseNotMatchingAnException() { // when mockServerClient.when(request().withPath(calculatePath("some_path.*")), exactly(4)).respond(response().withBody("some_body")); assertEquals( response("some_body").withHeader(HttpHeaders.CONTENT_TYPE, TEXT_PLAIN), makeRequest( request().withPath(calculatePath("some_path_one")), headersToIgnore) ); assertEquals( notFoundResponse(), makeRequest( request().withPath(calculatePath("not_found")), headersToIgnore) ); assertEquals( response("some_body").withHeader(HttpHeaders.CONTENT_TYPE, TEXT_PLAIN), makeRequest( request().withPath(calculatePath("some_path_three")), headersToIgnore) ); // then verifyRequestMatches( mockServerClient.retrieveRecordedRequests(request().withPath(calculatePath("some_path.*"))), request(calculatePath("some_path_one")), request(calculatePath("some_path_three")) ); verifyRequestMatches( mockServerClient.retrieveRecordedRequests(request()), request(calculatePath("some_path_one")), request(calculatePath("not_found")), request(calculatePath("some_path_three")) ); verifyRequestMatches( mockServerClient.retrieveRecordedRequests(null), request(calculatePath("some_path_one")), request(calculatePath("not_found")), request(calculatePath("some_path_three")) ); } @Test public void shouldRetrieveSequenceOfExpectationsSetup() { // when mockServerClient.when(request().withPath(calculatePath("some_path.*")), exactly(4)) .respond(response().withBody("some_body")); mockServerClient.when(request().withPath(calculatePath("some_path.*"))) .respond(response().withBody("some_body")); mockServerClient.when(request().withPath(calculatePath("some_other_path"))) .respond(response().withBody("some_other_body")); mockServerClient.when(request().withPath(calculatePath("some_forward_path"))) .forward(forward()); // then assertThat( mockServerClient.retrieveExistingExpectations(request().withPath(calculatePath("some_path.*"))), arrayContaining( new Expectation(request().withPath(calculatePath("some_path.*")), exactly(4), TimeToLive.unlimited()) .thenRespond(response().withBody("some_body")), expectation(request().withPath(calculatePath("some_path.*"))) .thenRespond(response().withBody("some_body")) ) ); assertThat( mockServerClient.retrieveExistingExpectations(null), arrayContaining( new Expectation(request().withPath(calculatePath("some_path.*")), exactly(4), TimeToLive.unlimited()) .thenRespond(response().withBody("some_body")), expectation(request().withPath(calculatePath("some_path.*"))) .thenRespond(response().withBody("some_body")), expectation(request().withPath(calculatePath("some_other_path"))) .thenRespond(response().withBody("some_other_body")), expectation(request().withPath(calculatePath("some_forward_path"))) .thenForward(forward()) ) ); assertThat( mockServerClient.retrieveExistingExpectations(request()), arrayContaining( new Expectation(request().withPath(calculatePath("some_path.*")), exactly(4), TimeToLive.unlimited()) .thenRespond(response().withBody("some_body")), expectation(request().withPath(calculatePath("some_path.*"))) .thenRespond(response().withBody("some_body")), expectation(request().withPath(calculatePath("some_other_path"))) .thenRespond(response().withBody("some_other_body")), expectation(request().withPath(calculatePath("some_forward_path"))) .thenForward(forward()) ) ); } @Test public void shouldVerifySequenceOfRequestsNotReceived() { // when mockServerClient.when(request().withPath(calculatePath("some_path.*")), exactly(6)).respond(response().withBody("some_body")); // then assertEquals( response("some_body").withHeader(HttpHeaders.CONTENT_TYPE, TEXT_PLAIN), makeRequest( request().withPath(calculatePath("some_path_one")), headersToIgnore) ); assertEquals( response("some_body").withHeader(HttpHeaders.CONTENT_TYPE, TEXT_PLAIN), makeRequest( request().withPath(calculatePath("some_path_two")), headersToIgnore) ); assertEquals( response("some_body").withHeader(HttpHeaders.CONTENT_TYPE, TEXT_PLAIN), makeRequest( request().withPath(calculatePath("some_path_three")), headersToIgnore) ); try { mockServerClient.verify(request(calculatePath("some_path_two")), request(calculatePath("some_path_one"))); fail(); } catch (AssertionError ae) { assertThat(ae.getMessage(), startsWith("Request sequence not found, expected:<[ {" + System.getProperty("line.separator") + " \"path\" : \"" + calculatePath("some_path_two") + "\"" + System.getProperty("line.separator") + "}, {" + System.getProperty("line.separator") + " \"path\" : \"" + calculatePath("some_path_one") + "\"" + System.getProperty("line.separator") + "} ]> but was:<[ {" + System.getProperty("line.separator") + " \"method\" : \"GET\"," + System.getProperty("line.separator") + " \"path\" : \"" + calculatePath("some_path_one") + "\"," + System.getProperty("line.separator"))); } try { mockServerClient.verify(request(calculatePath("some_path_three")), request(calculatePath("some_path_two"))); fail(); } catch (AssertionError ae) { assertThat(ae.getMessage(), startsWith("Request sequence not found, expected:<[ {" + System.getProperty("line.separator") + " \"path\" : \"" + calculatePath("some_path_three") + "\"" + System.getProperty("line.separator") + "}, {" + System.getProperty("line.separator") + " \"path\" : \"" + calculatePath("some_path_two") + "\"" + System.getProperty("line.separator") + "} ]> but was:<[ {" + System.getProperty("line.separator") + " \"method\" : \"GET\"," + System.getProperty("line.separator") + " \"path\" : \"" + calculatePath("some_path_one") + "\"," + System.getProperty("line.separator"))); } try { mockServerClient.verify(request(calculatePath("some_path_four"))); fail(); } catch (AssertionError ae) { assertThat(ae.getMessage(), startsWith("Request sequence not found, expected:<[ {" + System.getProperty("line.separator") + " \"path\" : \"" + calculatePath("some_path_four") + "\"" + System.getProperty("line.separator") + "} ]> but was:<[ {" + System.getProperty("line.separator") + " \"method\" : \"GET\"," + System.getProperty("line.separator") + " \"path\" : \"" + calculatePath("some_path_one") + "\"," + System.getProperty("line.separator"))); } } @Test public void shouldClearExpectations() { // given - some expectations mockServerClient .when( request() .withPath(calculatePath("some_path1")) ) .respond( response() .withBody("some_body1") ); mockServerClient .when( request() .withPath(calculatePath("some_path2")) ) .respond( response() .withBody("some_body2") ); // and - some matching requests assertEquals( response() .withHeader(HttpHeaders.CONTENT_TYPE, TEXT_PLAIN) .withStatusCode(HttpStatusCode.OK_200.code()) .withBody("some_body1"), makeRequest( request() .withPath(calculatePath("some_path1")), headersToIgnore) ); assertEquals( response() .withHeader(HttpHeaders.CONTENT_TYPE, TEXT_PLAIN) .withStatusCode(HttpStatusCode.OK_200.code()) .withBody("some_body2"), makeRequest( request() .withPath(calculatePath("some_path2")), headersToIgnore) ); // when mockServerClient .clear( request() .withPath(calculatePath("some_path1")) ); // then - expectations cleared assertThat( mockServerClient.retrieveExistingExpectations(null), arrayContaining( expectation( request() .withPath(calculatePath("some_path2")) ) .thenRespond( response() .withBody("some_body2") ) ) ); // and then - request log cleared verifyRequestMatches( mockServerClient.retrieveRecordedRequests(null), request(calculatePath("some_path2")) ); // and then - remaining expectations not cleared assertEquals( response() .withHeader(HttpHeaders.CONTENT_TYPE, TEXT_PLAIN) .withStatusCode(HttpStatusCode.OK_200.code()) .withBody("some_body2"), makeRequest( request() .withPath(calculatePath("some_path2")), headersToIgnore) ); assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()), makeRequest( request() .withPath(calculatePath("some_path1")), headersToIgnore) ); } @Test public void shouldClearAllExpectationsWithNull() { // given mockServerClient .when( request() .withPath(calculatePath("some_path1")) ) .respond( response() .withBody("some_body1") ); mockServerClient .when( request() .withPath(calculatePath("some_path2")) ) .respond( response() .withBody("some_body2") ); assertEquals( response() .withHeader(HttpHeaders.CONTENT_TYPE, TEXT_PLAIN) .withStatusCode(HttpStatusCode.OK_200.code()) .withBody("some_body2"), makeRequest( request() .withPath(calculatePath("some_path2")), headersToIgnore) ); // when mockServerClient.clear(null); // then assertThat(mockServerClient.retrieveExistingExpectations(null), emptyArray()); assertThat(mockServerClient.retrieveRecordedRequests(null), emptyArray()); } @Test public void shouldClearAllExpectationsWithEmptyRequest() { // given mockServerClient .when( request() .withPath(calculatePath("some_path1")) ) .respond( response() .withBody("some_body1") ); mockServerClient .when( request() .withPath(calculatePath("some_path2")) ) .respond( response() .withBody("some_body2") ); assertEquals( response() .withHeader(HttpHeaders.CONTENT_TYPE, TEXT_PLAIN) .withStatusCode(HttpStatusCode.OK_200.code()) .withBody("some_body2"), makeRequest( request() .withPath(calculatePath("some_path2")), headersToIgnore) ); // when mockServerClient.clear(request()); // then assertThat(mockServerClient.retrieveExistingExpectations(null), emptyArray()); assertThat(mockServerClient.retrieveRecordedRequests(null), emptyArray()); } @Test public void shouldClearExpectationsWithXPathBody() { // given mockServerClient .when( request() .withBody(xpath("/bookstore/book[year=2005]/price")) ) .respond( response() .withBody("some_body1") ); mockServerClient .when( request() .withBody(xpath("/bookstore/book[year=2006]/price")) ) .respond( response() .withBody("some_body2") ); // and StringBody xmlBody = new StringBody("" + "<?xml version=\"1.0\" encoding=\"ISO-8859-1\"?>" + System.getProperty("line.separator") + "<bookstore>" + System.getProperty("line.separator") + " <book category=\"COOKING\">" + System.getProperty("line.separator") + " <title lang=\"en\">Everyday Italian</title>" + System.getProperty("line.separator") + " <author>Giada De Laurentiis</author>" + System.getProperty("line.separator") + " <year>2005</year>" + System.getProperty("line.separator") + " <price>30.00</price>" + System.getProperty("line.separator") + " </book>" + System.getProperty("line.separator") + " <book category=\"CHILDREN\">" + System.getProperty("line.separator") + " <title lang=\"en\">Harry Potter</title>" + System.getProperty("line.separator") + " <author>J K. Rowling</author>" + System.getProperty("line.separator") + " <year>2006</year>" + System.getProperty("line.separator") + " <price>29.99</price>" + System.getProperty("line.separator") + " </book>" + System.getProperty("line.separator") + " <book category=\"WEB\">" + System.getProperty("line.separator") + " <title lang=\"en\">Learning XML</title>" + System.getProperty("line.separator") + " <author>Erik T. Ray</author>" + System.getProperty("line.separator") + " <year>2003</year>" + System.getProperty("line.separator") + " <price>31.95</price>" + System.getProperty("line.separator") + " </book>" + System.getProperty("line.separator") + "</bookstore>"); // then assertEquals( response() .withHeader(HttpHeaders.CONTENT_TYPE, TEXT_PLAIN) .withStatusCode(HttpStatusCode.OK_200.code()) .withBody("some_body1"), makeRequest( request() .withBody(xmlBody), headersToIgnore) ); // when mockServerClient .clear( request() .withBody(xpath("/bookstore/book[year=2005]/price")) ); // then assertThat( mockServerClient.retrieveExistingExpectations(null), arrayContaining( expectation( request() .withBody(xpath("/bookstore/book[year=2006]/price")) ) .thenRespond( response() .withBody("some_body2") ) ) ); // - in http assertEquals( response() .withHeader(HttpHeaders.CONTENT_TYPE, TEXT_PLAIN) .withStatusCode(HttpStatusCode.OK_200.code()) .withBody("some_body2"), makeRequest( request() .withBody(xmlBody), headersToIgnore) ); // - in https assertEquals( response() .withHeader(HttpHeaders.CONTENT_TYPE, TEXT_PLAIN) .withStatusCode(HttpStatusCode.OK_200.code()) .withBody("some_body2"), makeRequest( request() .withSecure(true) .withBody(xmlBody), headersToIgnore) ); } @Test public void shouldClearExpectationsWithJsonSchemaBody() { // given JsonSchemaBody jsonSchemaBodyOne = jsonSchema("{" + System.getProperty("line.separator") + " \"$schema\": \"http://json-schema.org/draft-04/schema#\"," + System.getProperty("line.separator") + " \"title\": \"Product\"," + System.getProperty("line.separator") + " \"description\": \"A product from Acme's catalog\"," + System.getProperty("line.separator") + " \"type\": \"object\"," + System.getProperty("line.separator") + " \"properties\": {" + System.getProperty("line.separator") + " \"id\": {" + System.getProperty("line.separator") + " \"description\": \"The unique identifier for a product\"," + System.getProperty("line.separator") + " \"type\": \"integer\"" + System.getProperty("line.separator") + " }," + System.getProperty("line.separator") + " \"name\": {" + System.getProperty("line.separator") + " \"description\": \"Name of the product\"," + System.getProperty("line.separator") + " \"type\": \"string\"" + System.getProperty("line.separator") + " }," + System.getProperty("line.separator") + " \"price\": {" + System.getProperty("line.separator") + " \"type\": \"number\"," + System.getProperty("line.separator") + " \"minimum\": 0," + System.getProperty("line.separator") + " \"exclusiveMinimum\": true" + System.getProperty("line.separator") + " }," + System.getProperty("line.separator") + " \"tags\": {" + System.getProperty("line.separator") + " \"type\": \"array\"," + System.getProperty("line.separator") + " \"items\": {" + System.getProperty("line.separator") + " \"type\": \"string\"" + System.getProperty("line.separator") + " }," + System.getProperty("line.separator") + " \"minItems\": 1," + System.getProperty("line.separator") + " \"uniqueItems\": true" + System.getProperty("line.separator") + " }" + System.getProperty("line.separator") + " }," + System.getProperty("line.separator") + " \"required\": [\"id\", \"name\", \"price\"]" + System.getProperty("line.separator") + "}"); JsonSchemaBody jsonSchemaBodyTwo = jsonSchema("{" + System.getProperty("line.separator") + " \"$schema\": \"http://json-schema.org/draft-04/schema#\"," + System.getProperty("line.separator") + " \"title\": \"Product\"," + System.getProperty("line.separator") + " \"description\": \"A product from Acme's catalog\"," + System.getProperty("line.separator") + " \"type\": \"object\"," + System.getProperty("line.separator") + " \"properties\": {" + System.getProperty("line.separator") + " \"id\": {" + System.getProperty("line.separator") + " \"description\": \"The unique identifier for a product\"," + System.getProperty("line.separator") + " \"type\": \"integer\"" + System.getProperty("line.separator") + " }," + System.getProperty("line.separator") + " \"name\": {" + System.getProperty("line.separator") + " \"description\": \"Name of the product\"," + System.getProperty("line.separator") + " \"type\": \"string\"" + System.getProperty("line.separator") + " }," + System.getProperty("line.separator") + " \"price\": {" + System.getProperty("line.separator") + " \"type\": \"number\"," + System.getProperty("line.separator") + " \"minimum\": 10," + System.getProperty("line.separator") + " \"exclusiveMinimum\": true" + System.getProperty("line.separator") + " }," + System.getProperty("line.separator") + " \"tags\": {" + System.getProperty("line.separator") + " \"type\": \"array\"," + System.getProperty("line.separator") + " \"items\": {" + System.getProperty("line.separator") + " \"type\": \"string\"" + System.getProperty("line.separator") + " }," + System.getProperty("line.separator") + " \"minItems\": 1," + System.getProperty("line.separator") + " \"uniqueItems\": true" + System.getProperty("line.separator") + " }" + System.getProperty("line.separator") + " }," + System.getProperty("line.separator") + " \"required\": [\"id\", \"name\", \"price\"]" + System.getProperty("line.separator") + "}"); mockServerClient .when( request() .withBody(jsonSchemaBodyOne) ) .respond( response() .withBody("some_body1") ); mockServerClient .when( request() .withBody(jsonSchemaBodyTwo) ) .respond( response() .withBody("some_body2") ); // then assertEquals( response() .withHeader(HttpHeaders.CONTENT_TYPE, TEXT_PLAIN) .withStatusCode(HttpStatusCode.OK_200.code()) .withBody("some_body1"), makeRequest( request() .withBody("{" + System.getProperty("line.separator") + " \"id\": 1," + System.getProperty("line.separator") + " \"name\": \"A green door\"," + System.getProperty("line.separator") + " \"price\": 12.50," + System.getProperty("line.separator") + " \"tags\": [\"home\", \"green\"]" + System.getProperty("line.separator") + "}"), headersToIgnore) ); // when mockServerClient .clear( request() .withBody(jsonSchemaBodyOne) ); // then assertThat( mockServerClient.retrieveExistingExpectations(null), arrayContaining( expectation( request() .withBody(jsonSchemaBodyTwo) ) .thenRespond( response() .withBody("some_body2") ) ) ); // - in http assertEquals( response() .withHeader(HttpHeaders.CONTENT_TYPE, TEXT_PLAIN) .withStatusCode(HttpStatusCode.OK_200.code()) .withBody("some_body2"), makeRequest( request() .withBody("{" + System.getProperty("line.separator") + " \"id\": 1," + System.getProperty("line.separator") + " \"name\": \"A green door\"," + System.getProperty("line.separator") + " \"price\": 12.50," + System.getProperty("line.separator") + " \"tags\": [\"home\", \"green\"]" + System.getProperty("line.separator") + "}"), headersToIgnore) ); // - in https assertEquals( response() .withHeader(HttpHeaders.CONTENT_TYPE, TEXT_PLAIN) .withStatusCode(HttpStatusCode.OK_200.code()) .withBody("some_body2"), makeRequest( request() .withSecure(true) .withBody("{" + System.getProperty("line.separator") + " \"id\": 1," + System.getProperty("line.separator") + " \"name\": \"A green door\"," + System.getProperty("line.separator") + " \"price\": 12.50," + System.getProperty("line.separator") + " \"tags\": [\"home\", \"green\"]" + System.getProperty("line.separator") + "}"), headersToIgnore) ); } @Test public void shouldClearExpectationsWithParameterBody() { // given mockServerClient .when( request() .withBody(params(param("bodyParameterNameOne", "bodyParameterValueOne"))) ) .respond( response() .withBody("some_body1") ); mockServerClient .when( request() .withBody(params(param("bodyParameterNameTwo", "bodyParameterValueTwo"))) ) .respond( response() .withBody("some_body2") ); // then assertEquals( response() .withHeader(HttpHeaders.CONTENT_TYPE, TEXT_PLAIN) .withStatusCode(HttpStatusCode.OK_200.code()) .withBody("some_body1"), makeRequest( request() .withBody(params(param("bodyParameterName.*", "bodyParameterValue.*"))), headersToIgnore) ); // when mockServerClient .clear( request() .withBody(params(param("bodyParameterNameOne", "bodyParameterValueOne"))) ); // then assertThat( mockServerClient.retrieveExistingExpectations(null), arrayContaining( expectation( request() .withBody(params(param("bodyParameterNameTwo", "bodyParameterValueTwo"))) ) .thenRespond( response() .withBody("some_body2") ) ) ); // - in http assertEquals( response() .withHeader(HttpHeaders.CONTENT_TYPE, TEXT_PLAIN) .withStatusCode(HttpStatusCode.OK_200.code()) .withBody("some_body2"), makeRequest( request() .withBody(params(param("bodyParameterName.*", "bodyParameterValue.*"))), headersToIgnore) ); // - in https assertEquals( response() .withHeader(HttpHeaders.CONTENT_TYPE, TEXT_PLAIN) .withStatusCode(HttpStatusCode.OK_200.code()) .withBody("some_body2"), makeRequest( request() .withSecure(true) .withBody(params(param("bodyParameterName.*", "bodyParameterValue.*"))), headersToIgnore) ); } @Test public void shouldReset() { // given mockServerClient .when( request() .withPath(calculatePath("some_path1")) ) .respond( response() .withBody("some_body1") ); mockServerClient .when( request() .withPath(calculatePath("some_path2")) ) .respond( response() .withBody("some_body2") ); // when mockServerClient.reset(); // then // - in http assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()), makeRequest( request() .withPath(calculatePath("some_path1")), headersToIgnore) ); assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()), makeRequest( request() .withPath(calculatePath("some_path2")), headersToIgnore) ); // - in https assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()), makeRequest( request() .withSecure(true) .withPath(calculatePath("some_path1")), headersToIgnore) ); assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()), makeRequest( request() .withSecure(true) .withPath(calculatePath("some_path2")), headersToIgnore) ); } @Test public void shouldEnsureThatRequestDelaysDoNotAffectOtherRequests() throws Exception { mockServerClient .when( request("/slow") ) .respond( response("super slow") .withDelay(new Delay(TimeUnit.SECONDS, 8)) ); mockServerClient .when( request("/fast") ) .respond( response("quite fast") ); ExecutorService executorService = Executors.newFixedThreadPool(2); Future<Long> slowFuture = executorService.submit(new Callable<Long>() { @Override public Long call() throws Exception { long start = System.currentTimeMillis(); makeRequest(request("/slow")); return System.currentTimeMillis() - start; } }); // Let fast request come to the server slightly after slow request Uninterruptibles.sleepUninterruptibly(1, TimeUnit.SECONDS); Future<Long> fastFuture = executorService.submit(new Callable<Long>() { @Override public Long call() throws Exception { long start = System.currentTimeMillis(); makeRequest(request("/fast")); return System.currentTimeMillis() - start; } }); Long slowRequestElapsedMillis = slowFuture.get(); Long fastRequestElapsedMillis = fastFuture.get(); assertThat("Slow request takes less than expected", slowRequestElapsedMillis, is(greaterThan(7 * 1000L))); assertThat("Fast request takes longer than expected", fastRequestElapsedMillis, is(lessThan(3 * 1000L))); } protected void verifyRequestMatches(HttpRequest[] httpRequests, HttpRequest... httpRequestMatchers) { if (httpRequests.length != httpRequestMatchers.length) { throw new AssertionError("Number of request matchers does not match number of requests, expected:<" + httpRequestMatchers.length + "> but was:<" + httpRequests.length + ">"); } else { for (int i = 0; i < httpRequestMatchers.length; i++) { if (!new HttpRequestMatcher(httpRequestMatchers[i]).matches(httpRequests[i])) { throw new AssertionError("Request does not match request matcher, expected:<" + httpRequestMatchers[i] + "> but was:<" + httpRequests[i] + ">"); } } } } protected HttpResponse makeRequest(HttpRequest httpRequest) { return makeRequest(httpRequest, Collections.<String>emptySet()); } protected HttpResponse makeRequest(HttpRequest httpRequest, Collection<String> headersToIgnore) { int attemptsRemaining = 10; while (attemptsRemaining > 0) { try { boolean isSsl = httpRequest.isSecure() != null && httpRequest.isSecure(); int port = (isSsl ? getMockServerSecurePort() : getMockServerPort()); HttpResponse httpResponse = httpClient.sendRequest(outboundRequest("localhost", port, servletContext, httpRequest)); List<Header> headers = new ArrayList<Header>(); for (Header header : httpResponse.getHeaders()) { if (!headersToIgnore.contains(header.getName().getValue().toLowerCase())) { if (header.getName().getValue().equalsIgnoreCase(HttpHeaders.CONTENT_TYPE)) { // this fixes Tomcat which removes the space between // media type and charset in the Content-Type header for (NottableString value : new ArrayList<NottableString>(header.getValues())) { header.getValues().clear(); header.addValues(value.getValue().replace(";charset", "; charset")); } } headers.add(header); } } httpResponse.withHeaders(headers); return httpResponse; } catch (SocketConnectionException caught) { attemptsRemaining--; logger.info("Retrying connection to mock server, attempts remaining: " + attemptsRemaining); try { TimeUnit.MILLISECONDS.sleep(500); } catch (InterruptedException e) { // do nothing } } } throw new RuntimeException("Failed to send request:" + System.getProperty("line.separator") + httpRequest); } }
soujava/mockserver
mockserver-integration-testing/src/main/java/org/mockserver/integration/server/AbstractClientServerIntegrationTest.java
901
import java.io.File; import java.io.FileNotFoundException; import java.util.Scanner; import java.util.PriorityQueue; import java.util.Comparator; public class RandomizedBST implements TaxEvasionInterface { // Κατασκευαστής χωρίς παραμέτρους public RandomizedBST() { root = null; } private class TreeNode { private LargeDepositor item; // Το στοιχείο του κόμβου private TreeNode left; // Δείκτης στο αριστερό υποδέντρο private TreeNode right; // Δείκτης στο δεξιό υποδέντρο private int N; // Αριθμός κόμβων στο υποδέντρο που ριζώνει σε αυτόν τον κόμβο // Κατασκευαστής με τέσσερις παραμέτρους public TreeNode(LargeDepositor item, TreeNode left, TreeNode right, int N) { if (N < 0) { throw new IllegalArgumentException("Ο αριθμός των κόμβων δεν μπορεί να είναι αρνητικός"); } this.item = item; this.left = left; this.right = right; this.N = N; } // Getters και setters με έλεγχο για έγκυρες τιμές public LargeDepositor getItem() { return item; } public void setItem(LargeDepositor item) { this.item = item; } public TreeNode getLeft() { return left; } public void setLeft(TreeNode left) { this.left = left; } public TreeNode getRight() { return right; } public void setRight(TreeNode right) { this.right = right; } public int getN() { return N; } public void setN(int N) { if (N < 0) { throw new IllegalArgumentException("Ο αριθμός των κόμβων δεν μπορεί να είναι αρνητικός"); } this.N = N; } // Μέθοδος για την εκτύπωση των δεδομένων του κόμβου @Override public String toString() { return "TreeNode [item=" + item + ", left=" + (left != null ? "TreeNode" : "null") + ", right=" + (right != null ? "TreeNode" : "null") + ", N=" + N + "]"; } } private TreeNode root; // pointer to root of the tree // Υλοποίηση των μεθόδων του interface public void insert(LargeDepositor item) { if (searchByAFM(item.getAFM()) != null) { System.out.println("Ένας μεγαλοκαταθέτης με ΑΦΜ " + item.getAFM() + " υπάρχει ήδη στο δέντρο."); return; } root = insertAtRoot(item, root); } private TreeNode insertAtRoot(LargeDepositor item, TreeNode node) { if (node == null) { return new TreeNode(item, null, null, 1); } int leftSize = size(node.left); if (Math.random() * (leftSize + 1) < 1) { // Πιθανότητα εισαγωγής στη ρίζα return insertRoot(item, node); } if (item.key() < node.item.key()) { node.left = insertAtRoot(item, node.left); } else { node.right = insertAtRoot(item, node.right); } node.N = size(node.left) + size(node.right) + 1; return node; } private TreeNode insertRoot(LargeDepositor item, TreeNode node) { if (node == null) { return new TreeNode(item, null, null, 1); } if (item.key() < node.item.key()) { node.left = insertRoot(item, node.left); node = rotateRight(node); } else { node.right = insertRoot(item, node.right); node = rotateLeft(node); } node.N = size(node.left) + size(node.right) + 1; return node; } private int size(TreeNode node) { if (node == null) { return 0; } return node.N; } private TreeNode rotateRight(TreeNode node) { if (node == null || node.left == null) { return node; } TreeNode temp = node.left; node.left = temp.right; temp.right = node; temp.N = node.N; node.N = size(node.left) + size(node.right) + 1; return temp; } private TreeNode rotateLeft(TreeNode node) { if (node == null || node.right == null) { return node; } TreeNode temp = node.right; node.right = temp.left; temp.left = node; temp.N = node.N; node.N = size(node.left) + size(node.right) + 1; return temp; } public void load(String filename) { try { File file = new File(filename); Scanner scanner = new Scanner(file); while (scanner.hasNextLine()) { String line = scanner.nextLine(); String[] parts = line.split(" "); int afm = Integer.parseInt(parts[0]); String firstName = parts[1]; String lastName = parts[2]; double savings = Double.parseDouble(parts[3]); double taxedIncome = Double.parseDouble(parts[4]); LargeDepositor depositor = new LargeDepositor(afm, firstName, lastName, savings, taxedIncome); insert(depositor); } scanner.close(); } catch (FileNotFoundException e) { System.err.println("Το αρχείο δεν βρέθηκε: " + filename); } catch (NumberFormatException | ArrayIndexOutOfBoundsException e) { System.err.println("Σφάλμα κατά την ανάγνωση του αρχείου: " + e.getMessage()); } } public void updateSavings(int AFM, double savings) { LargeDepositor depositor = searchByAFM(AFM); if (depositor != null) { depositor.setSavings(savings); System.out.println("Οι αποταμιεύσεις του υπόπτου με ΑΦΜ " + AFM + " ενημερώθηκαν."); } else { System.out.println("Δεν βρέθηκε ύποπτος με ΑΦΜ " + AFM); } } private LargeDepositor searchByAFM(TreeNode node, int AFM) { if (node == null) { return null; } if (AFM < node.item.getAFM()) { return searchByAFM(node.left, AFM); } else if (AFM > node.item.getAFM()) { return searchByAFM(node.right, AFM); } else { return node.item; } } public LargeDepositor searchByAFM(int AFM) { return searchByAFM(root, AFM); } private void searchByLastName(TreeNode node, String lastName, SingleNode head, SingleNode tail) { if (node == null) { return; } if (lastName.equals(node.item.getLastName())) { SingleNode newNode = new SingleNode(node.item); if (head.next == null) { head.next = newNode; } else { tail.next = newNode; } tail.next = newNode; } searchByLastName(node.left, lastName, head, tail); searchByLastName(node.right, lastName, head, tail); } public void searchByLastName(String lastName) { SingleNode dummyHead = new SingleNode(null); SingleNode tail = dummyHead; searchByLastName(root, lastName, dummyHead, tail); SingleNode current = dummyHead.next; int count = 0; while (current != null && count < 5) { System.out.println(current.item); current = current.next; count++; } if (count == 0) { System.out.println("Δεν βρέθηκε κανένας με επίθετο: " + lastName); } } private TreeNode remove(TreeNode node, int AFM) { if (node == null) { return null; } if (AFM < node.item.getAFM()) { node.left = remove(node.left, AFM); } else if (AFM > node.item.getAFM()) { node.right = remove(node.right, AFM); } else { if (node.left == null) { return node.right; } else if (node.right == null) { return node.left; } else { TreeNode t = node; node = min(t.right); // Βρίσκουμε τον ελάχιστο κόμβο του δεξιού υποδέντρου node.right = deleteMin(t.right); node.left = t.left; } } node.N = size(node.left) + size(node.right) + 1; return node; } public void remove(int AFM) { root = remove(root, AFM); } private TreeNode min(TreeNode node) { if (node.left == null) return node; return min(node.left); } private TreeNode deleteMin(TreeNode node) { if (node.left == null) return node.right; node.left = deleteMin(node.left); node.N = size(node.left) + size(node.right) + 1; return node; } public double getMeanSavings() { double[] sumAndCount = getSumAndCount(root); return sumAndCount[1] > 0 ? sumAndCount[0] / sumAndCount[1] : 0.0; } private double[] getSumAndCount(TreeNode node) { if (node == null) { return new double[]{0.0, 0}; // Αρχικοποίηση του αθροίσματος και του μετρητή σε 0 } double[] left = getSumAndCount(node.left); double[] right = getSumAndCount(node.right); double sum = left[0] + right[0] + node.item.getSavings(); // Άθροισμα των αποταμιεύσεων double count = left[1] + right[1] + 1; // Συνολικός αριθμός των καταθετών return new double[]{sum, count}; } public void printTopLargeDepositors(int k) { PriorityQueue<LargeDepositor> pq = new PriorityQueue<>(k, new Comparator<LargeDepositor>() { @Override public int compare(LargeDepositor d1, LargeDepositor d2) { double score1 = d1.getTaxedIncome() < 8000 ? Double.MAX_VALUE : d1.getSavings() - d1.getTaxedIncome(); double score2 = d2.getTaxedIncome() < 8000 ? Double.MAX_VALUE : d2.getSavings() - d2.getTaxedIncome(); return Double.compare(score2, score1); } }); addDepositorsToPriorityQueue(root, pq, k); for (int i = 0; i < k && !pq.isEmpty(); i++) { LargeDepositor depositor = pq.poll(); System.out.println(depositor); } } private void addDepositorsToPriorityQueue(TreeNode node, PriorityQueue<LargeDepositor> pq, int k) { if (node == null) { return; } pq.offer(node.item); if (pq.size() > k) { pq.poll(); } addDepositorsToPriorityQueue(node.left, pq, k); addDepositorsToPriorityQueue(node.right, pq, k); } private void printInOrder(TreeNode node) { if (node == null) { return; } printInOrder(node.left); // Επισκεφτείτε πρώτα το αριστερό υποδέντρο System.out.println(node.item); // Εκτυπώστε τον κόμβο printInOrder(node.right); // Στη συνέχεια επισκεφτείτε το δεξί υποδέντρο } public void printByAFM() { printInOrder(root); } public static void main(String[] args) { RandomizedBST bst = new RandomizedBST(); if (args.length > 0) { String filename = args[0]; bst.load(filename); } else { System.out.println("Παρακαλώ δώστε το όνομα του αρχείου ως όρισμα."); } Scanner scanner = new Scanner(System.in); while (true) { System.out.println("\nΜενού Διαχείρισης:"); System.out.println("1. Εισαγωγή Υπόπτου"); System.out.println("2. Διαγραφή Υπόπτου"); System.out.println("3. Αναζήτηση με ΑΦΜ"); System.out.println("4. Αναζήτηση με Επίθετο"); System.out.println("5. Εμφάνιση Μέσου Ποσού Αποταμιεύσεων"); System.out.println("6. Εμφάνιση Πρώτων Υπόπτων για Φοροδιαφυγή"); System.out.println("7. Εμφάνιση Όλων των Υπόπτων Ανά ΑΦΜ"); System.out.println("8. Έξοδος"); System.out.print("Επιλέξτε μια ενέργεια: "); int choice = scanner.nextInt(); switch (choice) { case 1: // Εισαγωγή Υπόπτου System.out.print("Εισάγετε ΑΦΜ: "); int afm = scanner.nextInt(); System.out.print("Εισάγετε Όνομα: "); String firstName = scanner.next(); System.out.print("Εισάγετε Επίθετο: "); String lastName = scanner.next(); System.out.print("Εισάγετε Αποταμιεύσεις: "); double savings = scanner.nextDouble(); System.out.print("Εισάγετε Δηλωμένο Εισόδημα: "); double taxedIncome = scanner.nextDouble(); LargeDepositor depositor = new LargeDepositor(afm, firstName, lastName, savings, taxedIncome); bst.insert(depositor); break; case 2: // Διαγραφή Υπόπτου System.out.print("Εισάγετε ΑΦΜ για διαγραφή: "); int afmToDelete = scanner.nextInt(); bst.remove(afmToDelete); break; case 3: // Αναζήτηση με ΑΦΜ System.out.print("Εισάγετε ΑΦΜ για αναζήτηση: "); int afmToSearch = scanner.nextInt(); LargeDepositor foundDepositor = bst.searchByAFM(afmToSearch); if (foundDepositor != null) { System.out.println("Βρέθηκε ο Υπόπτος: " + foundDepositor); } else { System.out.println("Δεν βρέθηκε Υπόπτος με ΑΦΜ: " + afmToSearch); } break; case 4: // Αναζήτηση με Επίθετο System.out.print("Εισάγετε Επίθετο για αναζήτηση: "); String lastNameToSearch = scanner.next(); bst.searchByLastName(lastNameToSearch); break; case 5: // Εμφάνιση Μέσου Ποσού Αποταμιεύσεων System.out.println("Μέσο ποσό αποταμιεύσεων: " + bst.getMeanSavings()); break; case 6: // Εμφάνιση Πρώτων Υπόπτων για Φοροδιαφυγή System.out.print("Εισάγετε τον αριθμό των υπόπτων προς εμφάνιση: "); int k = scanner.nextInt(); bst.printTopLargeDepositors(k); break; case 7: // Εμφάνιση Όλων των Υπόπτων Ανά ΑΦΜ bst.printByAFM(); break; case 8: // Έξοδος System.out.println("Έξοδος από το πρόγραμμα."); scanner.close(); System.exit(0); default: System.out.println("Μη έγκυρη επιλογή. Παρακαλώ επιλέξτε ξανά."); break; } } } private class SingleNode { LargeDepositor item; SingleNode next; SingleNode(LargeDepositor item) { this.item = item; this.next = null; } } }
krimits/domesproject3
RandomizedBST.java
902
/* Γράψτε ένα πρόγραμμα προσομοίωσης της ρίψεως 2 ζαριών. Η ρίψη κάθε ζαριού πρέπει να προσομοιώνεται με χρήση της μεθόδου Math.random και το άθροισμα των αποτελεσμάτων των 2 ζαριών να αποθηκεύεται σε ένα πίνακα αποτελεσμάτων. Η «διάρκεια» της προσομοίωσης είναι 30000 ρίψεις. Με την ολοκλήρωση της προσομοίωσης να εκτυπώνεται ο πίνακας αποτελεσμάτων. Παράδειγμα εκτέλεσης Result 2 : 819 times Result 3 : 1705 times Result 4 : 2570 times Result 5 : 3298 times Result 6 : 4186 times Result 7 : 4997 times Result 8 : 4168 times Result 9 : 3300 times Result 10 : 2425 times Result 11 : 1703 times Result 12 : 830 times Υποδείξεις: - Η πιο απλή αντιμετώπιση του προβλήματος είναι να κατασκευάσουμε μια μέθοδο εξαγωγής ενός αποτελέσματος ρίψεως ζαριού. - Ένας πιο κομψός τρόπος επίλυσης του προβλήματος είναι να δημιουργήσουμε μια die class η οποία και περιγράφει ένα ζάρι και περιέχει την μέθοδο εξαγωγής αποτελέσματος. - Προφανώς ένα ζάρι μπορεί να φέρει ως αποτέλεσμα ένα φυσικό αριθμό στο διάστημα [1,6] με τυχαίο τρόπο. Από την κλάση αυτή παράγουμε 2 αντικέιμενα-ζάρια. Τα ζάρια αυτά τα χρησιμοποιούμε τόσες φορές όσες και η διάρκεια της προσομοίωσης (30000 φορές) και κάθε φορά αθροίζουμε το αποτέλεσμα της ρίψης και ενημερώνουμε ένα μονοδιάστατο πίνακα αποτελεσμάτων. Στο τέλος εκτυπώνουμε τον πίνακα αποτελεσμάτων και παίρνουμε στην έξοδο ένα αποτέλεσμα παρόμοιο με αυτό του παραδείγματος εκτέλεσης. */ public class Dice { private String name; private int diceResult; //Constructor public Dice(String name) { this.name=name; diceResult=1; } public void rollDice() { diceResult = (int) (Math.round( (Math.random()*5) ))+1; } //Getters-Setters public int getResult() { return diceResult; } public String getName() { return name; } public void setResult(int diceResult) { this.diceResult=diceResult; } public void setName(String name) { this.name=name; } @Override public String toString() { return (name+" Result = "+diceResult); } }
alexoiik/Data-Structures-Java
DataStructures_Ex1(AbstractDataTypes)/src/Dice.java
904
package com.example.eshop3; import android.os.Bundle; import androidx.fragment.app.Fragment; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.Button; //κάνω implements View.OnclickListener ένας άλλος τρόπος αντί να κάνω setOncliCkListener(new View.OnclickListner) σε εάν κουμπί public class menu_pelates extends Fragment implements View.OnClickListener { //δημιουργώ 3 μεταβλητές τύπου Button Button B_insert, B_delete, B_edit; public menu_pelates() { // Required empty public constructor } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { //δημιορυγώ το view κάνοντας inflate το αντίστοιχο fragment View view = inflater.inflate(R.layout.fragment_menu_pelates, container, false ); //κάνω αντιστόιχηση τις μεταβλητές μου με τα ανάλογα button //χρησιμοποιόντας την findViewById //και ορίζω σε κάθε κουμπί την ιδιότητα setOnClickListener(this) ///δηλαδή τι θα γίνεται κάθε φορα που κάποιος πατάει κάποιο κουμπί B_insert = view.findViewById(R.id.insertButton); B_insert.setOnClickListener(this); B_delete = view.findViewById(R.id.deleteButton); B_delete.setOnClickListener(this); B_edit = view.findViewById(R.id.editButton); B_edit.setOnClickListener(this); return view; } //η onClick παίρνει σα παράμετρο τη View που έχω δημιουργήσει και ανάλογα τα id των κουμπιών // που έχει η view πάει στο ανόλογο case. Μέσα στο case ανάλογα ποιο κουμπί έχει πατηθεί //ξεκινάει μια συναλλαγή και δημιουργεί το αντίστοιχο fragment και με addToBackStack μπορεί //κανείς να πηγαίνει πίσω και φυσικά στο τέλος commit. public void onClick(View v){ switch (v.getId()){ case R.id.insertButton: MainActivity.fragmentManager.beginTransaction().replace(R.id.fragment_container,new InsertPelates()).addToBackStack(null).commit(); break; case R.id.deleteButton: MainActivity.fragmentManager.beginTransaction().replace(R.id.fragment_container, new DeletePelates()).addToBackStack(null).commit(); break; case R.id.editButton: MainActivity.fragmentManager.beginTransaction().replace(R.id.fragment_container, new UpdatePelates()).addToBackStack(null).commit(); break; } } }
EfthimisKele/E_Shop
app/src/main/java/com/example/eshop3/menu_pelates.java
905
package gr.aueb.cf.ch3; import java.util.Scanner; /** * Εκτυπώνει n οριζόντια αστεράκια, * όπου n ένας ακέραιος που δίνει ο * χρήστης. */ public class StarsApp { public static void main(String[] args) { Scanner in = new Scanner(System.in); int numberOfStars = 0; int i = 0; System.out.println("Please insert number of stars"); numberOfStars = in.nextInt(); while (i <= numberOfStars) { System.out.print("*"); i++; } } }
a8anassis/codingfactory23a
src/gr/aueb/cf/ch3/StarsApp.java
906
package api; import java.io.*; import java.util.HashSet; import java.util.Objects; /** * Η κλάση αυτή περιέχει μεθόδους για τη διαχείριση των χρηστών. */ public class ManageUsers implements Serializable { private HashSet<SimpleUser> simpleUsers; private HashSet<Provider> providers; /** * Κατασκευαστής της κλάσης ManageUsers. Αρχικοποιεί τα HashSets των απλών χρηστών και των παρόχων. */ public ManageUsers(){ simpleUsers = new HashSet<>(); providers = new HashSet<>(); } /** * Αποθηκεύει το παρόν αντικείμενο στο αντίστοιχο αρχείο εξόδου. */ public void saveToOutputFiles() { try (ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream("usersManager.bin"))) { out.writeObject(this); //out.flush(); } catch (IOException e1) { System.out.println("Δεν βρέθηκε αρχείο εξόδου"); } } /** * Η μέθοδος αυτή χρησιμοποιείται για την εύρεση κάποιου χρήστη με βάση το username του. Εάν βρεθεί επιστρέφεται το * αντικείμενο του αντίστοιχου χρήστη, διαφορετικά η μέθοδος επιστρέφει null. * @param username Το username του χρήστη. * @return Ο χρήστης που αναζητείται ή null αν δε βρεθεί. */ public User findUserWithUsername(String username) { if (!simpleUsers.isEmpty()) { for (SimpleUser simpleUser : simpleUsers) { if (Objects.equals(username, simpleUser.getUserName())) return simpleUser; } } if (!providers.isEmpty()) { for (Provider provider : providers) { if (Objects.equals(username, provider.getUserName())) return provider; } } return null; } /** * Η μέθοδος ελέγχει αν το αντικείμενο του χρήστη που δίνεται ως όρισμα είναι απλός χρήστης. * @param user Το αντικείμενο του χρήστη. * @return True αν το αντικείμενο του χρήστη που δίνεται ως όρισμα είναι απλός χρήστης, false διαφορετικά. */ public boolean isSimpleUser(User user) { return user instanceof SimpleUser; } //ελέγχει τον χρήστη που επιστρέφει η findUserWithUserName στο login /** * Η μέθοδος ελέγχει αν το αντικείμενο του χρήστη που δίνεται ως όρισμα είναι πάροχος. * @param user Το αντικείμενο του χρήστη. * @return True αν το αντικείμενο του χρήστη που δίνεται ως όρισμα είναι πάροχος, false διαφορετικά. */ public boolean isProvider(User user) { return user instanceof Provider; } //Δε χρησιμοποιείται γιατί αν ένας χρήστης δεν είναι SimpleUser Θα είναι Provider οπότε δεν απαιτείται έξτρα έλεγχος στο authentication (αν προστεθούν και άλλοι τύποι χρηστών θα είναι απαραίτητο /** * Η μέθοδος αυτή χρησιμοποιείται για τη δημιουργία νέου απλού χρήστη. * @param firstName Το μικρό όνομα χρήστη. * @param lastName Το επώνυμο όνομα χρήστη. * @param userName Το ειδικό όνομα χρήστη. * @param password Ο κωδικός. * @return Χρήστη. */ public SimpleUser createSimpleUser(String firstName, String lastName ,String userName, String password) { SimpleUser user = new SimpleUser(firstName, lastName, userName, password, "simpleUser"); simpleUsers.add(user); return user; } //Δεν ελέγχεται αν το username υπάρχει ήδη γιατί ο έλεγχος γίνεται στο checkSignUpInaccuracies /** * Η μέθοδος αυτή χρησιμοποιείται για τη δημιουργία νέου παρόχου. * @param firstName Το μικρό όνομα χρήστη. * @param lastName Το επώνυμο όνομα χρήστη. * @param userName Το ειδικό όνομα χρήστη. * @param password Ο κωδικός. * @return Χρήστη. */ public Provider createProvider(String firstName, String lastName ,String userName, String password) { Provider user = new Provider(firstName, lastName, userName, password, "provider"); providers.add(user); return user; } //Δεν ελέγχεται αν το username υπάρχει ήδη γιατί ο έλεγχος γίνεται στο checkSignUpInaccuracies /** * H μέθοδος αυτή χρησιμοποιείται για την επαλήθευση των στοιχείων του χρήστη κατά την είσοδό του. * Γίνεται η εύρεση του username με τη χρήση της findUserWithUsername() και έπειτα τον ελέγχεται η ορθότητα του * πληκτρολογημένου κωδικού. * @param username Το username που δόθηκε από τον χρήστη. * @param password Ο κωδικός. * @return True αν υπάρχει χρήστης με τέτοιο username και έχει δοθεί ο σωστός κωδικός, false διαφορετικά. */ public boolean authentication(String username, String password) { User user = findUserWithUsername(username); if (user == null) return false; return user.getPassword().equals(password); } /** * Η μέθοδος αυτή ελέγχει εάν τα πεδία για την εγγραφή κάποιου χρήστη έχουν συμπληρωθεί ορθά και επιστρέφει * κατάλληλο μήνυμα. Η ορθότητα εγγραφής κρίνεται από το αν τα στοιχεία του χρήστη έχουν μήκος συμβολοσειράς * μεγαλύτερο του μηδενός (χωρίς τους κενούς χαρακτήρες) και από το αν το username που δίνεται είναι * μοναδικό. Σε διαφορετική περίπτωση να επιστρέφει κατάλληλο μήνυμα. * @param firstName Μικρό όνομα νέου χρήστη * @param lastName Επίθετο νέου χρήστη * @param username username νέου χρήστη * @param password κωδικός νέου χρήστη * @return null αν πέρασε όλους τους ελέγχους, διαφορετικά κατάλληλο μήνυμα. */ public String checkSignUpInaccuracies(String firstName, String lastName, String username, String password) { if (firstName.trim().length() == 0 || lastName.trim().length() == 0 || username.trim().length() == 0 || password.trim().length() == 0) //Η μέθοδος trim() αφαιρεί όλα τα whitespaces ώστε να μην περνάει ως είσοδος το space return "Όλα τα πεδία κειμένου είναι υποχρεωτικά για την εγγραφή"; if (findUserWithUsername(username) != null) return "Το όνομα χρήστη " + username + " υπάρχει ήδη"; return null; } }
patiosga/myreviews
src/api/ManageUsers.java
907
package gr.aueb.cf.ch5; import java.util.Scanner; /** * Αποφασίζει αν ένας int είναι * άρτιος ή περιττός. */ public class EvenOddApp { public static void main(String[] args) { Scanner in = new Scanner(System.in); int num; //boolean isEven = false; System.out.println("Please insert an int"); num = in.nextInt(); //isEven = EvenOddApp.isEven(num); System.out.println("Num " + num + " is even: " + isEven(num)); } /** * Evaluates an int if it is even or not. * * @param n the number (int) to evaluate. * @return true, if n is even, false otherwise. */ public static boolean isEven(int n) { return n % 2 == 0; } }
a8anassis/codingfactory23a
src/gr/aueb/cf/ch5/EvenOddApp.java
908
package gr.aueb.cf.ch3; import java.util.Scanner; /** * Ελέγχει αν ένας αριθμός είναι Armstrong. * Δηλαδή το άθροισμα των δυνάμεων κάθε ψηφίου στη * δύναμη του πλήθους των ψηφίων ισούται με * τον αρχικό αριθμό. */ public class DigitCount2 { public static void main(String[] args) { Scanner in = new Scanner(System.in); int inputNum = 0; int num = 0; int digit = 0; int digits = 0; int sum = 0; boolean isArmstrong = false; System.out.println("Please insert a num"); inputNum = in.nextInt(); num = inputNum; do { digits++; num = num / 10; } while (num != 0); num = inputNum; do { digit = num % 10; sum += Math.pow(digit, digits); num = num / 10; } while (num != 0); System.out.println(sum); isArmstrong = (inputNum == sum); System.out.println(inputNum + " is Armstrong: " + isArmstrong); } }
a8anassis/cf4
src/gr/aueb/cf/ch3/DigitCount2.java
909
import java.util.ArrayList; import java.util.Random; import java.util.Scanner; public class Crc { //Μεταβλητή που μετρά όλα τα σφάλματα που προκύπτουν στο κανάλι public int countFromBER = 0; //Μεταβλητή που μετρά τα λάθη που ανιχνεύονται απο το crc στον αποδέκτη. public int countFromCrc = 0; /** * Η μέθοδος αυτή προσομοιώνει τη μετάδοση του μηνύματος μέσω ενός ενόρυβου καναλιού. * Δημιουργείται μία βοηθητική λίστα που αποτελεί αντίγραφο του μεταδιδόμενου μηνύματος. * Διατρέχεται επανάληψη όσο το μέγεθος της (αντίγραφης) λίστας και για κάθε μπιτ, δημιουργείται * μέσω της συνάρτησης rand ένας τυχαίος αριθμός διπλής ακρίβειας απο το 0 εως το 1. Εαν ο αριθμός είναι * μικρότερος του BER ( 0.001) τότε το συγκεκριμένο μπιτ στο μεταδιδόμενο μήνυμα αλλάζει. Στο τέλος * της επανάληψης, αν έχει υπάρξει ένα ή περισσότερα σφάλματα αυξάνεται ο μετρητής countFromBer κατά ένα. * @param Message Λίστα που στα κελία της περιέχει κάθε μπιτ του μεταδιδόμενου μηνύματος * @return Επιστρέφει σε μορφή λίστας το μήνυμα μετά την μετάδοση του από το κανάλι με BER = 10 ^ -6 */ ArrayList<Character> BitErrorChannel(ArrayList<Character> Message) { boolean temp = false; ArrayList<Character> message = new ArrayList<>(Message); Random rand = new Random(); for(int i=0;i<message.size(); i++) { //Για κάθε μπιτ του μηνύματος double x = rand.nextDouble(); //Generate τυχαίου double στο [0-1] if(x <= 0.001) { //Αν είναι μικρότερος του επιτρεπόμενου σφάλματος, // αλλάζει το μπιτ ανάλογα με την τιμή που αρχικά έχει temp = true; if(message.get(i) == '0') message.set(i,'1'); else message.set(i,'0'); } } if(temp) //Αν υπήρξε σφάλμα αύξηση του μετρητή. countFromBER++; return message; //Επιστροφή του (αλλαγμένου) μηνύματος. } /** * Η μέθοδος αυτή αποτελεί την υλοποίηση της πράξης αποκλειστικής διάζευξης (XOR). * Διατρέχεται μία επανάληψη όσο το μέγεθος του διεραίτη (y) και για κάθε στοιχείο * του διαιρετέου (x) εκτελείται η πράξη x XOR y με το αντιστοιχο ψηφίο του αριθμου y. * Χρησιμοποιείται μία βοηθητική λίστα που αποθηκεύει το αποτέλεσμα των πράξεων εντός της * επαναληψης. * @param x Διεραιτέος με τη μορφή λίστας * @param y Διεραίτης με τη μορφή λίστας * @return Λίστα αποτελούμενο από τα μπιτ της πράξης x XOR y */ ArrayList<Character> XOR(ArrayList<Character> x, ArrayList<Character> y) { ArrayList<Character> temp = new ArrayList<>(); //Βοηθητική λίστα for(int i=1;i<y.size(); i++) //Για κάθε στοιχείο του αριθμού y { if(x.get(i) == y.get(i)) // 1 XOR 1 = 0, 0 XOR O = 0 else 1 XOR O = 1, 0 XOR 1 = 1 temp.add('0'); else temp.add('1'); } return temp; //Επιστρέφεται η βοηθητική λίστα } /** * Η μέθοδος αυτή εκτελεί την modulo - 2 πράξη μεταξύ του μεταδιδόμενου μηνύματος και του αριθμού data * πρότυπο P. Χρησιμοποιείται για τον υπολογισμό του FCS αλλά και για την εύρεση του υπολοίπου στην πράξη * modulo - 2 μεταξύ FCS και P. * @param data Η λίστα που αποθηκεύει τον μήνυμα * @param P Ο αριθμός πρότυπο για τον υπολογισμό του CRC. * @return Λίστα με το αποτέλεσμα της modulo - 2 πράξης μεταξύ data - P */ ArrayList<Character> mod2div(ArrayList<Character> data, ArrayList<Character> P) { ArrayList<Character> temp = new ArrayList<>(); //Βοηθητική λίστα η οποία κρατά το υπόλοιπο της XOR σε κάθε βήμα int size_P = P.size(); //Ο αριθμός των μπιτ στα οποία θα εκτελεστεί η πράξη XOR κάθε φορά. int data_size = data.size(); //Μέγεθος μεταδιδόμενου μηνύματος //Αντιγράφονται τα πρώτα size στοιχεία της λίστας που έχει αποθηκευμένο το μεταδιδόμενο μήνυμα. for(int i=0;i<size_P;i++) temp.add(data.get(i)); //Διατρέχεται επανάληψη για κάθε στοιχείο αριθμόυ του μηνύματος όσο το μέγεθος P < data_size while (size_P < data_size) { if (temp.get(0) == '1') //Αν το πρώτο μπιτ της λίστας υπολοίπου είναι ΄1΄ //Εκτελούμε την πράξη XOR μεταξύ P και temp και "κατεβάζουμε" το επόμενο μπιτ του μηνύματος temp = XOR(P, temp); else //Αν το πρώτο μπιτ της λίστας υπολοίπου είναι '0' { //Χρησιμοποιόυμε ως P μία λίστα με '0' σε κάθε θέση και εκτελούμε την XOR //Έτσι κατεβάζουμε το επόμενο μπιτ από το μεταδιδόμενο μήνυμα και κάνουμε κάτι σαν swift //Στη λίστα υπολοίπου ώστε να μην κρατάει άχρηστα 0-νικά στην αρχή της. ArrayList<Character> dump = new ArrayList<>(); for (int i = 0; i < size_P; i++) dump.add('0'); temp = XOR(dump, temp); } temp.add((data.get(size_P))); //Αυξάνεται το size_P κατά ένα ώστε να κατεβεί το επόμενο μπιτ του //μεταδιδόμενου και να γίνει η XOR στα νέα μπιτ δεδομένων size_P ++; } //Τέλος για τα τελευτάια data_size μπιτς εκτελείται εκτός επανάληψης //Η ίδια διαδικασία ώστε να μην βγούμε εκτώς ορίων πίνακα και στο τέλος //Παίρνουμε ως αποτέλεσμα τον αριθμό των size_P μπιτ που αποτελέι το R κατά την εύρεση του FCS //και το υπόλοιπο στον έλεγχο του αποδέκτη όταν θέλουμε να ελέγξουμε αν ο CRC ανίχνευσε το σφάλμα. if (temp.get(0) == '1') temp = XOR(P, temp); else { ArrayList<Character> dump = new ArrayList<>(); for(int i=0;i<size_P;i++) dump.add('0'); temp = XOR(dump , temp);} return temp; } /** * Η μέθοδος αυτή εισάγει αρχικά (P_size -1) μηδενικά στο αρχικά μεταδιδόμενο μήνυμα. * Έπειτα καλεί την modulo -2 πράξη που εκτελείται μεταξύ μηνύματος και αριθμό προτύπου * για τον υπολογισμό του FCS. Η modulo - 2 με τον τρόπο που υλοποιήθηκε επιστρέφει το * υπόλοιπο των (P_size-1) μπιτ, οπότε στη συνέχεια αυτό το υπόλοιπο προσαρτάται στο τέλος * του αρχικού μηνύματος και πλέον αποτελεί το FCS * @param data Λίστα που αποθηκεύει το μεταδιδόμενο μήνυμα * @param P Ο αριθμός πρότυπο για τον υπολογισμό του CRC * @return FCS */ ArrayList<Character> encodeData(ArrayList<Character> data,ArrayList<Character> P) { int P_size = P.size(); //Μέγεθος αριθμού προτύπου P. //Λίστα που θα περιέχει το μήνυμα με τα P_size -1 μηδενικά στο τέλος της ArrayList<Character> appended_data = new ArrayList<>(data); //Αντιγραφή του μεταδιδόμενου μηνύματος for (int i = 0; i < P_size -1; i++) //Εισαγωγή των P_size - 1 μηδενικών. appended_data.add('0'); ArrayList<Character> remainder = mod2div(appended_data, P); //Λίστα που περιέχει το υπόλοιπο της modulo -2 πράξης ArrayList<Character> codeword = new ArrayList<>(); //Δημιουργία τελικού FCS το οποίο αποτελείται // από το αρχικό μήνυμα + το υπόλοιπο της πράξης modulo -2 codeword.addAll(data); codeword.addAll(remainder); return codeword; } /** * Η μέθοδος αυτή ελέγχει αν το μήνυμα (FCS) περιέχει σφάλμα και αυξάνει τον αντίστοιχο * μετρητή (ανίχνευσης λάθους στον αποδέκτη του CRC -> countFromCrc). Αν το μήνυμα περιέχει * σφάλμα, τότε μετά την πραγματοποίηση της modulo-2 πράξης με τον αριθμό πρότυπο P, θα περιέχει * τουλάχιστον έναν άσσο στο υπόλοιπο της πράξης. * @param FCS Το μήνυμα (FCS) αφότου έχει περάσει από το ενόρυβο κανάλι * @param P Ο αριθμός πρότυπο για τον υπολογισμό του CRC. */ void checkCRC(ArrayList<Character> FCS, ArrayList<Character> P) { ArrayList<Character> dump = mod2div(FCS,P); //Βοηθητική λίστα με το υπόλοιπο της modulo - 2 if(dump.contains('1')) //Αν το υπόλοιπο της πράξης περιέχει '1', αυξάνεται μετρητής. { countFromCrc++; } } public static void main(String[] args) { Crc object = new Crc(); //Δημιουργία αντικειμένου Crc int k = 20; //Αριθμός μπιτ που θα περιέχει κάθε μεταδιδόμενο μήνυμα. int numberOfMessages = 10000000; ArrayList<ArrayList<Character>> Messages = new ArrayList<>(); //Λίστα λιστών που θα περιέχει N πλήθος δυαδικών μηνυμάτων String number; //Προσωρινή μεταβλητή που αποθηκεύει το P όταν διαβαστεί από τον χρήστη //Όσο ο χρήστης δίνει ως είσοδο αριθμό που δεν ξεκινά ή/και δεν τελειώνει σε '1' η διαδικασία επαναλαμβάνεται do { System.out.println("Give the number P in this format e.g: 110101 (1st and last digit must be '1'"); Scanner input = new Scanner(System.in); number = input.nextLine(); }while(number.charAt(0) != '1' || number.charAt(number.length()-1) != '1'); ArrayList<Character> P = new ArrayList<>(); //Λίστα που σε κάθε κελί αποθηκεύει ένα μπιτ του αριθμού P for (int i = 0; i < number.length(); i++) { //Δηιμουργία του P μέσω του number που διαβάστηκε από τον χρήστη P.add(number.charAt(i)); } Random rand = new Random(); //Δημιουργία αντικειμένου από την κλάση Random της Java //Σε αυτήν την επανάληψη δημιουργούνται τα (numberOfMessages σε πλήθος) μηνύματα προς μετάδοση των k μπιτ for (int i = 0; i < numberOfMessages; i++) { ArrayList<Character> dump = new ArrayList<>(); //Βοηθητική λίστα που αποθηκεύει κάθε μπιτ του μηνύματος for (int j = 0; j < k; j++) { int n = rand.nextInt(2); dump.add((char) (n + '0')); } Messages.add(dump); //Εισαγωγή του μηνύματος στη λίστα λιστών που αποθηκεύει όλα τα μηνύματα. } //Για κάθε μήνυμα υπολογίζεται το FCS //έπειτα το FCS περνά από το κανάλι με BER //Τέλος ελέγχεται το crc στον αποδέκτη for(int i=0;i<numberOfMessages;i++) { ArrayList<Character> FCS = object.encodeData(Messages.get(i),P); ArrayList<Character> FCS_WITH_BER = object.BitErrorChannel(FCS); object.checkCRC(FCS_WITH_BER,P); } System.out.println("Errors found in BER: " + object.countFromBER); System.out.println("Errors found from CRC: " + object.countFromCrc); System.out.println("Errors not detected from CRC: " + (object.countFromBER - object.countFromCrc)); } }
NikosVogiatzis/UniProjects
java -Ψηφιακές επικοινωνίες - CRC/CRC/Crc.java
910
package org.mockserver.integration.server; import com.google.common.base.Charsets; import com.google.common.base.Strings; import com.google.common.net.MediaType; import com.google.common.util.concurrent.Uninterruptibles; import org.apache.commons.io.IOUtils; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Ignore; import org.junit.Test; import org.mockserver.client.netty.NettyHttpClient; import org.mockserver.client.netty.SocketConnectionException; import org.mockserver.client.serialization.ExpectationSerializer; import org.mockserver.client.server.MockServerClient; import org.mockserver.echo.http.EchoServer; import org.mockserver.matchers.HttpRequestMatcher; import org.mockserver.matchers.MatchType; import org.mockserver.matchers.TimeToLive; import org.mockserver.matchers.Times; import org.mockserver.mock.Expectation; import org.mockserver.model.*; import org.mockserver.socket.PortFactory; import org.mockserver.verify.VerificationTimes; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.IOException; import java.net.InetSocketAddress; import java.util.*; import java.util.concurrent.*; import static io.netty.handler.codec.http.HttpHeaderNames.*; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.*; import static org.hamcrest.core.Is.is; import static org.hamcrest.core.StringStartsWith.startsWith; import static org.hamcrest.number.OrderingComparison.greaterThan; import static org.junit.Assert.assertEquals; import static org.junit.Assert.fail; import static org.mockserver.character.Character.NEW_LINE; import static org.mockserver.matchers.Times.exactly; import static org.mockserver.matchers.Times.once; import static org.mockserver.model.BinaryBody.binary; import static org.mockserver.model.Cookie.cookie; import static org.mockserver.model.Header.header; import static org.mockserver.model.HttpClassCallback.callback; import static org.mockserver.model.HttpForward.forward; import static org.mockserver.model.HttpRequest.request; import static org.mockserver.model.HttpResponse.notFoundResponse; import static org.mockserver.model.HttpResponse.response; import static org.mockserver.model.HttpStatusCode.NOT_FOUND_404; import static org.mockserver.model.HttpStatusCode.OK_200; import static org.mockserver.model.JsonBody.json; import static org.mockserver.model.JsonSchemaBody.jsonSchema; import static org.mockserver.model.NottableString.not; import static org.mockserver.model.NottableString.string; import static org.mockserver.model.Parameter.param; import static org.mockserver.model.ParameterBody.params; import static org.mockserver.model.RegexBody.regex; import static org.mockserver.model.StringBody.exact; import static org.mockserver.model.XPathBody.xpath; import static org.mockserver.model.XmlBody.xml; import static org.mockserver.model.XmlSchemaBody.xmlSchema; /** * @author jamesdbloom */ public abstract class AbstractClientServerIntegrationTest { protected static final String TEXT_PLAIN = MediaType.create("text", "plain").toString(); protected static MockServerClient mockServerClient; protected static String servletContext = ""; private final Logger logger = LoggerFactory.getLogger(this.getClass()); protected List<String> headersToIgnore = Arrays.asList( "server", "expires", "date", "host", "connection", "user-agent", "content-length", "accept-encoding", "transfer-encoding", "access-control-allow-origin", "access-control-allow-methods", "access-control-allow-headers", "access-control-expose-headers", "access-control-max-age", "x-cors" ); private NettyHttpClient httpClient = new NettyHttpClient(); public static Expectation expectation(HttpRequest httpRequest) { return new Expectation(httpRequest, Times.unlimited(), TimeToLive.unlimited()); } @BeforeClass public static void resetServletContext() throws Exception { servletContext = ""; } public abstract int getMockServerPort(); public abstract int getMockServerSecurePort(); public abstract int getTestServerPort(); @Before public void resetServer() { mockServerClient.reset(); } @Test public void shouldForwardRequestInHTTP() { // when mockServerClient .when( request() .withPath(calculatePath("echo")) ) .forward( forward() .withHost("127.0.0.1") .withPort(getTestServerPort()) ); // then // - in http assertEquals( response() .withStatusCode(OK_200.code()) .withHeaders( header("x-test", "test_headers_and_body") ) .withBody("an_example_body_http"), makeRequest( request() .withPath(calculatePath("echo")) .withMethod("POST") .withHeaders( header("x-test", "test_headers_and_body") ) .withBody("an_example_body_http"), headersToIgnore) ); // - in https assertEquals( response() .withStatusCode(OK_200.code()) .withHeaders( header("x-test", "test_headers_and_body") ) .withBody("an_example_body_https"), makeRequest( request() .withSecure(true) .withPath(calculatePath("echo")) .withMethod("POST") .withHeaders( header("x-test", "test_headers_and_body") ) .withBody("an_example_body_https"), headersToIgnore) ); } @Test public void shouldForwardRequestInHTTPS() { int testServerHttpsPort = PortFactory.findFreePort(); EchoServer secureEchoServer = new EchoServer(testServerHttpsPort, true); try { // when mockServerClient .when( request() .withPath(calculatePath("echo")) ) .forward( forward() .withHost("127.0.0.1") .withPort(testServerHttpsPort) .withScheme(HttpForward.Scheme.HTTPS) ); // then // - in http assertEquals( response() .withStatusCode(OK_200.code()) .withHeaders( header("x-test", "test_headers_and_body") ) .withBody("an_example_body_http"), makeRequest( request() .withPath(calculatePath("echo")) .withMethod("POST") .withHeaders( header("x-test", "test_headers_and_body") ) .withBody("an_example_body_http"), headersToIgnore) ); // - in https assertEquals( response() .withStatusCode(OK_200.code()) .withHeaders( header("x-test", "test_headers_and_body") ) .withBody("an_example_body_https"), makeRequest( request() .withSecure(true) .withPath(calculatePath("echo")) .withMethod("POST") .withHeaders( header("x-test", "test_headers_and_body") ) .withBody("an_example_body_https"), headersToIgnore) ); } finally { secureEchoServer.stop(); } } @Test public void shouldAllowSimultaneousForwardAndResponseExpectations() { // when mockServerClient .when( request() .withPath(calculatePath("echo")), once() ) .forward( forward() .withHost("127.0.0.1") .withPort(getTestServerPort()) ); mockServerClient .when( request() .withPath(calculatePath("test_headers_and_body")), once() ) .respond( response() .withBody("some_body") ); // then // - forward assertEquals( response() .withStatusCode(OK_200.code()) .withHeaders( header("x-test", "test_headers_and_body") ) .withBody("an_example_body"), makeRequest( request() .withPath(calculatePath("echo")) .withMethod("POST") .withHeaders( header("x-test", "test_headers_and_body") ) .withBody("an_example_body"), headersToIgnore) ); // - respond assertEquals( response() .withStatusCode(OK_200.code()) .withBody("some_body"), makeRequest( request() .withPath(calculatePath("test_headers_and_body")), headersToIgnore) ); // - no response or forward assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()), makeRequest( request() .withPath(calculatePath("test_headers_and_body")), headersToIgnore) ); } @Test public void shouldCallbackToSpecifiedClassWithPrecannedResponse() { // when mockServerClient .when( request() .withPath(calculatePath("callback")) ) .callback( callback() .withCallbackClass("org.mockserver.integration.callback.PrecannedTestExpectationCallback") ); // then // - in http assertEquals( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withHeaders( header("x-callback", "test_callback_header") ) .withBody("a_callback_response"), makeRequest( request() .withPath(calculatePath("callback")) .withMethod("POST") .withHeaders( header("x-test", "test_headers_and_body") ) .withBody("an_example_body_http"), headersToIgnore ) ); // - in https assertEquals( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withHeaders( header("x-callback", "test_callback_header") ) .withBody("a_callback_response"), makeRequest( request() .withSecure(true) .withPath(calculatePath("callback")) .withMethod("POST") .withHeaders( header("x-test", "test_headers_and_body") ) .withBody("an_example_body_https"), headersToIgnore ) ); } @Test public void shouldReturnResponseWithOnlyBody() { // when mockServerClient.when(request()).respond(response().withBody("some_body")); // then // - in http assertEquals( response() .withStatusCode(OK_200.code()) .withBody("some_body"), makeRequest( request() .withPath(calculatePath("")), headersToIgnore) ); // - in https assertEquals( response() .withStatusCode(OK_200.code()) .withBody("some_body"), makeRequest( request() .withSecure(true) .withPath(calculatePath("")), headersToIgnore) ); } @Test public void shouldSupportBatchedExpectations() { // when new NettyHttpClient().sendRequest( request() .withMethod("PUT") .withHeader(HOST.toString(), "localhost:" + getMockServerPort()) .withPath(addContextToPath("/expectation")) .withBody("" + "[" + new ExpectationSerializer() .serialize( new Expectation(request("/path_one"), once(), TimeToLive.unlimited()) .thenRespond(response().withBody("some_body_one")) ) + "," + new ExpectationSerializer() .serialize( new Expectation(request("/path_two"), once(), TimeToLive.unlimited()) .thenRespond(response().withBody("some_body_two")) ) + "," + new ExpectationSerializer() .serialize( new Expectation(request("/path_three"), once(), TimeToLive.unlimited()) .thenRespond(response().withBody("some_body_three")) ) + "]" ) ); // then assertEquals( response() .withStatusCode(OK_200.code()) .withBody("some_body_one"), makeRequest( request() .withPath(calculatePath("/path_one")), headersToIgnore) ); assertEquals( response() .withStatusCode(OK_200.code()) .withBody("some_body_two"), makeRequest( request() .withPath(calculatePath("/path_two")), headersToIgnore) ); assertEquals( response() .withStatusCode(OK_200.code()) .withBody("some_body_three"), makeRequest( request() .withPath(calculatePath("/path_three")), headersToIgnore) ); } @Test public void shouldReturnResponseForRequestInSsl() { // when mockServerClient.when(request().withSecure(true)).respond(response().withBody("some_body")); // then // - in http assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()), makeRequest( request() .withPath(calculatePath("")), headersToIgnore) ); // - in https assertEquals( response() .withStatusCode(OK_200.code()) .withBody("some_body"), makeRequest( request() .withSecure(true) .withPath(calculatePath("")), headersToIgnore) ); } @Test public void shouldReturnResponseForRequestNotInSsl() { // when mockServerClient.when(request().withSecure(false)).respond(response().withBody("some_body")); // then // - in http assertEquals( response() .withStatusCode(OK_200.code()) .withBody("some_body"), makeRequest( request() .withPath(calculatePath("")), headersToIgnore) ); // - in https assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()), makeRequest( request() .withSecure(true) .withPath(calculatePath("")), headersToIgnore) ); } @Test public void shouldReturnMatchRequestWithBodyInUTF16() { // when String body = "我说中国话"; mockServerClient.when(request().withBody(body, Charsets.UTF_16)).respond(response().withBody(body, Charsets.UTF_8)); // then // - in http assertEquals( response() .withHeader(CONTENT_TYPE.toString(), MediaType.create("text", "plain").withCharset(Charsets.UTF_8).toString()) .withStatusCode(OK_200.code()) .withBody(body), makeRequest( request() .withPath(calculatePath("")) .withBody(body, Charsets.UTF_16), headersToIgnore) ); // - in https assertEquals( response() .withHeader(CONTENT_TYPE.toString(), MediaType.create("text", "plain").withCharset(Charsets.UTF_8).toString()) .withStatusCode(OK_200.code()) .withBody(body), makeRequest( request() .withSecure(true) .withPath(calculatePath("")) .withBody(body, Charsets.UTF_16), headersToIgnore) ); } @Test public void shouldReturnMatchRequestWithBodyInUTF16WithContentTypeHeader() { // when String body = "我说中国话"; mockServerClient .when( request() .withHeader(CONTENT_TYPE.toString(), MediaType.create("text", "plain").withCharset(Charsets.UTF_8).toString()) .withBody(body) ) .respond( response() .withBody(body, Charsets.UTF_8) ); // then // - in http assertEquals( response() .withHeader(CONTENT_TYPE.toString(), MediaType.create("text", "plain").withCharset(Charsets.UTF_8).toString()) .withStatusCode(OK_200.code()) .withBody(body), makeRequest( request() .withHeader(CONTENT_TYPE.toString(), MediaType.create("text", "plain").withCharset(Charsets.UTF_8).toString()) .withPath(calculatePath("")) .withBody(body), headersToIgnore) ); // - in https assertEquals( response() .withHeader(CONTENT_TYPE.toString(), MediaType.create("text", "plain").withCharset(Charsets.UTF_8).toString()) .withStatusCode(OK_200.code()) .withBody(body), makeRequest( request() .withHeader(CONTENT_TYPE.toString(), MediaType.create("text", "plain").withCharset(Charsets.UTF_8).toString()) .withSecure(true) .withPath(calculatePath("")) .withBody(body), headersToIgnore) ); } @Test public void shouldReturnResponseWithBodyInUTF8() { // when String body = "我说中国话"; mockServerClient.when(request()).respond(response().withBody(body, Charsets.UTF_16)); // then // - in http assertEquals( response() .withHeader(CONTENT_TYPE.toString(), MediaType.create("text", "plain").withCharset(Charsets.UTF_16).toString()) .withStatusCode(OK_200.code()) .withBody(body), makeRequest( request() .withPath(calculatePath("")), headersToIgnore) ); // - in https assertEquals( response() .withHeader(CONTENT_TYPE.toString(), MediaType.create("text", "plain").withCharset(Charsets.UTF_16).toString()) .withStatusCode(OK_200.code()) .withBody(body), makeRequest( request() .withSecure(true) .withPath(calculatePath("")), headersToIgnore) ); } @Test public void shouldReturnResponseWithBodyInUTF16WithContentTypeHeader() { // when String body = "我说中国话"; mockServerClient .when( request() ) .respond( response() .withHeader(CONTENT_TYPE.toString(), MediaType.create("text", "plain").withCharset(Charsets.UTF_8).toString()) .withBody(body) ); // then // - in http assertEquals( response() .withHeader(CONTENT_TYPE.toString(), MediaType.create("text", "plain").withCharset(Charsets.UTF_8).toString()) .withStatusCode(OK_200.code()) .withBody(body), makeRequest( request() .withPath(calculatePath("")), headersToIgnore) ); // - in https assertEquals( response() .withHeader(CONTENT_TYPE.toString(), MediaType.create("text", "plain").withCharset(Charsets.UTF_8).toString()) .withStatusCode(OK_200.code()) .withBody(body), makeRequest( request() .withSecure(true) .withPath(calculatePath("")), headersToIgnore) ); } @Test public void shouldReturnResponseWithOnlyStatusCode() { // when mockServerClient .when( request() .withMethod("POST") .withPath(calculatePath("some_path")) ) .respond( response() .withStatusCode(200) ); // then // - in http assertEquals( response() .withStatusCode(OK_200.code()), makeRequest( request() .withPath(calculatePath("some_path")) .withMethod("POST"), headersToIgnore) ); // - in https assertEquals( response() .withStatusCode(OK_200.code()), makeRequest( request() .withSecure(true) .withPath(calculatePath("some_path")) .withMethod("POST"), headersToIgnore) ); } @Test public void shouldReturnResponseByMatchingPath() { // when mockServerClient .when( request() .withPath(calculatePath("some_path1")) ) .respond( response() .withBody("some_body1") ); mockServerClient .when( request() .withPath(calculatePath("some_path2")) ) .respond( response() .withBody("some_body2") ); // then // - in http assertEquals( response() .withStatusCode(OK_200.code()) .withBody("some_body2"), makeRequest( request() .withPath(calculatePath("some_path2")), headersToIgnore) ); assertEquals( response() .withStatusCode(OK_200.code()) .withBody("some_body1"), makeRequest( request() .withPath(calculatePath("some_path1")), headersToIgnore) ); // - in https assertEquals( response() .withStatusCode(OK_200.code()) .withBody("some_body2"), makeRequest( request() .withSecure(true) .withPath(calculatePath("some_path2")), headersToIgnore) ); assertEquals( response() .withStatusCode(OK_200.code()) .withBody("some_body1"), makeRequest( request() .withSecure(true) .withPath(calculatePath("some_path1")), headersToIgnore) ); } @Test public void shouldReturnResponseByMatchingPathExactTimes() { // when mockServerClient .when( request() .withPath(calculatePath("some_path")), exactly(2) ) .respond( response() .withBody("some_body") ); // then // - in http assertEquals( response() .withStatusCode(OK_200.code()) .withBody("some_body"), makeRequest( request() .withPath(calculatePath("some_path")), headersToIgnore) ); // - in https assertEquals( response() .withStatusCode(OK_200.code()) .withBody("some_body"), makeRequest( request() .withSecure(true) .withPath(calculatePath("some_path")), headersToIgnore) ); // - in http assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()), makeRequest( request() .withPath(calculatePath("some_path")), headersToIgnore) ); // - in https assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()), makeRequest( request() .withSecure(true) .withPath(calculatePath("some_path")), headersToIgnore) ); } @Test public void shouldReturnResponseWhenTimeToLiveHasNotExpired() { // when mockServerClient .when( request().withPath(calculatePath("some_path")), exactly(2), TimeToLive.exactly(TimeUnit.HOURS, 1L) ) .respond( response().withBody("some_body") ); // then // - in http assertEquals( response() .withStatusCode(OK_200.code()) .withBody("some_body"), makeRequest( request() .withPath(calculatePath("some_path")), headersToIgnore) ); // - in https assertEquals( response() .withStatusCode(OK_200.code()) .withBody("some_body"), makeRequest( request() .withSecure(true) .withPath(calculatePath("some_path")), headersToIgnore) ); // - in http assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()), makeRequest( request() .withPath(calculatePath("some_path")), headersToIgnore) ); // - in https assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()), makeRequest( request() .withSecure(true) .withPath(calculatePath("some_path")), headersToIgnore) ); } @Test public void shouldReturnResponseByMatchingBodyWithXPath() { // when mockServerClient.when(request().withBody(xpath("/bookstore/book[price>30]/price")), exactly(2)).respond(response().withBody("some_body")); // then // - in http assertEquals( response() .withStatusCode(OK_200.code()) .withBody("some_body"), makeRequest( request() .withPath(calculatePath("some_path")) .withMethod("POST") .withBody(new StringBody("" + "<?xml version=\"1.0\" encoding=\"ISO-8859-1\"?>" + NEW_LINE + "<bookstore>" + NEW_LINE + " <book category=\"COOKING\">" + NEW_LINE + " <title lang=\"en\">Everyday Italian</title>" + NEW_LINE + " <author>Giada De Laurentiis</author>" + NEW_LINE + " <year>2005</year>" + NEW_LINE + " <price>30.00</price>" + NEW_LINE + " </book>" + NEW_LINE + " <book category=\"CHILDREN\">" + NEW_LINE + " <title lang=\"en\">Harry Potter</title>" + NEW_LINE + " <author>J K. Rowling</author>" + NEW_LINE + " <year>2005</year>" + NEW_LINE + " <price>29.99</price>" + NEW_LINE + " </book>" + NEW_LINE + " <book category=\"WEB\">" + NEW_LINE + " <title lang=\"en\">Learning XML</title>" + NEW_LINE + " <author>Erik T. Ray</author>" + NEW_LINE + " <year>2003</year>" + NEW_LINE + " <price>31.95</price>" + NEW_LINE + " </book>" + NEW_LINE + "</bookstore>")), headersToIgnore) ); // - in https assertEquals( response() .withStatusCode(OK_200.code()) .withBody("some_body"), makeRequest( request() .withSecure(true) .withPath(calculatePath("some_path")) .withMethod("POST") .withBody(new StringBody("" + "<?xml version=\"1.0\" encoding=\"ISO-8859-1\"?>" + NEW_LINE + "<bookstore>" + NEW_LINE + " <book category=\"COOKING\">" + NEW_LINE + " <title lang=\"en\">Everyday Italian</title>" + NEW_LINE + " <author>Giada De Laurentiis</author>" + NEW_LINE + " <year>2005</year>" + NEW_LINE + " <price>30.00</price>" + NEW_LINE + " </book>" + NEW_LINE + " <book category=\"CHILDREN\">" + NEW_LINE + " <title lang=\"en\">Harry Potter</title>" + NEW_LINE + " <author>J K. Rowling</author>" + NEW_LINE + " <year>2005</year>" + NEW_LINE + " <price>29.99</price>" + NEW_LINE + " </book>" + NEW_LINE + " <book category=\"WEB\">" + NEW_LINE + " <title lang=\"en\">Learning XML</title>" + NEW_LINE + " <author>Erik T. Ray</author>" + NEW_LINE + " <year>2003</year>" + NEW_LINE + " <price>31.95</price>" + NEW_LINE + " </book>" + NEW_LINE + "</bookstore>")), headersToIgnore) ); } @Test public void shouldReturnResponseByMatchingBodyWithXml() { // when mockServerClient.when(request().withBody(xml("" + "<bookstore>" + NEW_LINE + " <book nationality=\"ITALIAN\" category=\"COOKING\"><title lang=\"en\">Everyday Italian</title><author>Giada De Laurentiis</author><year>2005</year><price>30.00</price></book>" + NEW_LINE + "</bookstore>")), exactly(2)).respond(response().withBody("some_body")); // then // - in http assertEquals( response() .withStatusCode(OK_200.code()) .withBody("some_body"), makeRequest( request() .withPath(calculatePath("some_path")) .withMethod("POST") .withBody(new StringBody("" + "<?xml version=\"1.0\" encoding=\"ISO-8859-1\"?>" + NEW_LINE + "<bookstore>" + NEW_LINE + " <book category=\"COOKING\" nationality=\"ITALIAN\">" + NEW_LINE + " <title lang=\"en\">Everyday Italian</title>" + NEW_LINE + " <author>Giada De Laurentiis</author>" + NEW_LINE + " <year>2005</year>" + NEW_LINE + " <price>30.00</price>" + NEW_LINE + " </book>" + NEW_LINE + "</bookstore>")), headersToIgnore) ); // - in https assertEquals( response() .withStatusCode(OK_200.code()) .withBody("some_body"), makeRequest( request() .withSecure(true) .withPath(calculatePath("some_path")) .withMethod("POST") .withBody(new StringBody("" + "<?xml version=\"1.0\" encoding=\"ISO-8859-1\"?>" + NEW_LINE + "<bookstore>" + NEW_LINE + " <book category=\"COOKING\" nationality=\"ITALIAN\">" + NEW_LINE + " <title lang=\"en\">Everyday Italian</title>" + NEW_LINE + " <author>Giada De Laurentiis</author>" + NEW_LINE + " <year>2005</year>" + NEW_LINE + " <price>30.00</price>" + NEW_LINE + " </book>" + NEW_LINE + "</bookstore>")), headersToIgnore) ); } @Test public void shouldReturnResponseByMatchingBodyWithJson() { // when mockServerClient .when( request() .withBody(json("{" + NEW_LINE + " \"id\": 1," + NEW_LINE + " \"name\": \"A green door\"," + NEW_LINE + " \"price\": 12.50," + NEW_LINE + " \"tags\": [\"home\", \"green\"]" + NEW_LINE + "}")), exactly(2) ) .respond( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body") ); // then // - in http assertEquals( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body"), makeRequest( request() .withPath(calculatePath("some_path")) .withMethod("POST") .withBody("{" + NEW_LINE + " \"id\": 1," + NEW_LINE + " \"extra ignored field\": \"some value\"," + NEW_LINE + " \"name\": \"A green door\"," + NEW_LINE + " \"price\": 12.50," + NEW_LINE + " \"tags\": [\"home\", \"green\"]" + NEW_LINE + "}"), headersToIgnore) ); // - in https assertEquals( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body"), makeRequest( request() .withSecure(true) .withPath(calculatePath("some_path")) .withMethod("POST") .withBody("{" + NEW_LINE + " \"id\": 1," + NEW_LINE + " \"extra ignored array\": [\"one\", \"two\"]," + NEW_LINE + " \"name\": \"A green door\"," + NEW_LINE + " \"price\": 12.50," + NEW_LINE + " \"tags\": [\"home\", \"green\"]" + NEW_LINE + "}"), headersToIgnore) ); } @Test public void shouldReturnResponseByMatchingBodyWithJsonWithCharsetUTF8() { // when mockServerClient .when( request() .withBody(json("{" + NEW_LINE + " \"ταυτότητα\": 1," + NEW_LINE + " \"όνομα\": \"μια πράσινη πόρτα\"," + NEW_LINE + " \"τιμή\": 12.50," + NEW_LINE + " \"ετικέτες\": [\"σπίτι\", \"πράσινος\"]" + NEW_LINE + "}", Charsets.UTF_16, MatchType.ONLY_MATCHING_FIELDS)), exactly(2) ) .respond( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body") ); // then // - in http assertEquals( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body"), makeRequest( request() .withPath(calculatePath("some_path")) .withMethod("POST") .withBody(json("{" + NEW_LINE + " \"ταυτότητα\": 1," + NEW_LINE + " \"επιπλέον αγνοούνται τομέα\": \"κάποια αξία\"," + NEW_LINE + " \"όνομα\": \"μια πράσινη πόρτα\"," + NEW_LINE + " \"τιμή\": 12.50," + NEW_LINE + " \"ετικέτες\": [\"σπίτι\", \"πράσινος\"]" + NEW_LINE + "}", Charsets.UTF_16, MatchType.ONLY_MATCHING_FIELDS)), headersToIgnore) ); // - in https assertEquals( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body"), makeRequest( request() .withSecure(true) .withPath(calculatePath("some_path")) .withMethod("POST") .withBody(json("{" + NEW_LINE + " \"ταυτότητα\": 1," + NEW_LINE + " \"επιπλέον αγνοούνται σειρά\": [\"ένας\", \"δυο\"]," + NEW_LINE + " \"όνομα\": \"μια πράσινη πόρτα\"," + NEW_LINE + " \"τιμή\": 12.50," + NEW_LINE + " \"ετικέτες\": [\"σπίτι\", \"πράσινος\"]" + NEW_LINE + "}", Charsets.UTF_16, MatchType.ONLY_MATCHING_FIELDS)), headersToIgnore) ); } @Test public void shouldReturnResponseByMatchingBodyWithJsonWithContentTypeHeader() { // when mockServerClient .when( request() .withBody(json("{" + NEW_LINE + " \"ταυτότητα\": 1," + NEW_LINE + " \"όνομα\": \"μια πράσινη πόρτα\"," + NEW_LINE + " \"τιμή\": 12.50," + NEW_LINE + " \"ετικέτες\": [\"σπίτι\", \"πράσινος\"]" + NEW_LINE + "}", Charsets.UTF_16, MatchType.ONLY_MATCHING_FIELDS)), exactly(2) ) .respond( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body") ); // then // - in http assertEquals( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body"), makeRequest( request() .withHeader(CONTENT_TYPE.toString(), MediaType.create("text", "plain").withCharset(Charsets.UTF_16).toString()) .withPath(calculatePath("some_path")) .withMethod("POST") .withBody(json("{" + NEW_LINE + " \"ταυτότητα\": 1," + NEW_LINE + " \"επιπλέον αγνοούνται τομέα\": \"κάποια αξία\"," + NEW_LINE + " \"όνομα\": \"μια πράσινη πόρτα\"," + NEW_LINE + " \"τιμή\": 12.50," + NEW_LINE + " \"ετικέτες\": [\"σπίτι\", \"πράσινος\"]" + NEW_LINE + "}")), headersToIgnore) ); // - in https assertEquals( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body"), makeRequest( request() .withSecure(true) .withHeader(CONTENT_TYPE.toString(), MediaType.create("text", "plain").withCharset(Charsets.UTF_16).toString()) .withPath(calculatePath("some_path")) .withMethod("POST") .withBody(json("{" + NEW_LINE + " \"ταυτότητα\": 1," + NEW_LINE + " \"επιπλέον αγνοούνται σειρά\": [\"ένας\", \"δυο\"]," + NEW_LINE + " \"όνομα\": \"μια πράσινη πόρτα\"," + NEW_LINE + " \"τιμή\": 12.50," + NEW_LINE + " \"ετικέτες\": [\"σπίτι\", \"πράσινος\"]" + NEW_LINE + "}")), headersToIgnore) ); } @Test public void shouldReturnResponseByMatchingBodyWithJsonWithMatchType() { // when mockServerClient .when( request() .withBody(json("{" + NEW_LINE + " \"id\": 1," + NEW_LINE + " \"name\": \"A green door\"," + NEW_LINE + " \"price\": 12.50," + NEW_LINE + " \"tags\": [\"home\", \"green\"]" + NEW_LINE + "}", MatchType.ONLY_MATCHING_FIELDS)), exactly(2) ) .respond( response() .withBody("some_body") ); // then // - in http assertEquals( response("some_body"), makeRequest( request() .withPath(calculatePath("some_path")) .withMethod("POST") .withBody("{" + NEW_LINE + " \"id\": 1," + NEW_LINE + " \"extra field\": \"some value\"," + NEW_LINE + " \"name\": \"A green door\"," + NEW_LINE + " \"price\": 12.50," + NEW_LINE + " \"tags\": [\"home\", \"green\"]" + NEW_LINE + "}"), headersToIgnore) ); // - in https assertEquals( response("some_body"), makeRequest( request() .withSecure(true) .withPath(calculatePath("some_path")) .withMethod("POST") .withBody("{" + NEW_LINE + " \"id\": 1," + NEW_LINE + " \"extra field\": \"some value\"," + NEW_LINE + " \"name\": \"A green door\"," + NEW_LINE + " \"price\": 12.50," + NEW_LINE + " \"tags\": [\"home\", \"green\"]" + NEW_LINE + "}"), headersToIgnore) ); } @Test public void shouldReturnResponseByMatchingBodyWithJsonSchema() { // when mockServerClient.when(request().withBody(jsonSchema("{" + NEW_LINE + " \"$schema\": \"http://json-schema.org/draft-04/schema#\"," + NEW_LINE + " \"title\": \"Product\"," + NEW_LINE + " \"description\": \"A product from Acme's catalog\"," + NEW_LINE + " \"type\": \"object\"," + NEW_LINE + " \"properties\": {" + NEW_LINE + " \"id\": {" + NEW_LINE + " \"description\": \"The unique identifier for a product\"," + NEW_LINE + " \"type\": \"integer\"" + NEW_LINE + " }," + NEW_LINE + " \"name\": {" + NEW_LINE + " \"description\": \"Name of the product\"," + NEW_LINE + " \"type\": \"string\"" + NEW_LINE + " }," + NEW_LINE + " \"price\": {" + NEW_LINE + " \"type\": \"number\"," + NEW_LINE + " \"minimum\": 0," + NEW_LINE + " \"exclusiveMinimum\": true" + NEW_LINE + " }," + NEW_LINE + " \"tags\": {" + NEW_LINE + " \"type\": \"array\"," + NEW_LINE + " \"items\": {" + NEW_LINE + " \"type\": \"string\"" + NEW_LINE + " }," + NEW_LINE + " \"minItems\": 1," + NEW_LINE + " \"uniqueItems\": true" + NEW_LINE + " }" + NEW_LINE + " }," + NEW_LINE + " \"required\": [\"id\", \"name\", \"price\"]" + NEW_LINE + "}")), exactly(2)).respond(response().withBody("some_body")); // then // - in http assertEquals( response() .withStatusCode(OK_200.code()) .withBody("some_body"), makeRequest( request() .withPath(calculatePath("some_path")) .withMethod("POST") .withBody("{" + NEW_LINE + " \"id\": 1," + NEW_LINE + " \"name\": \"A green door\"," + NEW_LINE + " \"price\": 12.50," + NEW_LINE + " \"tags\": [\"home\", \"green\"]" + NEW_LINE + "}"), headersToIgnore) ); // - in https assertEquals( response() .withStatusCode(OK_200.code()) .withBody("some_body"), makeRequest( request() .withSecure(true) .withPath(calculatePath("some_path")) .withMethod("POST") .withBody("{" + NEW_LINE + " \"id\": 1," + NEW_LINE + " \"name\": \"A green door\"," + NEW_LINE + " \"price\": 12.50," + NEW_LINE + " \"tags\": [\"home\", \"green\"]" + NEW_LINE + "}"), headersToIgnore) ); } @Test public void shouldReturnResponseByMatchingBodyWithXmlSchema() { // when mockServerClient.when(request() .withBody( xmlSchema("<?xml version=\"1.0\" encoding=\"UTF-8\"?>" + NEW_LINE + "<xs:schema xmlns:xs=\"http://www.w3.org/2001/XMLSchema\" elementFormDefault=\"qualified\" attributeFormDefault=\"unqualified\">" + NEW_LINE + " <!-- XML Schema Generated from XML Document on Wed Jun 28 2017 21:52:45 GMT+0100 (BST) -->" + NEW_LINE + " <!-- with XmlGrid.net Free Online Service http://xmlgrid.net -->" + NEW_LINE + " <xs:element name=\"notes\">" + NEW_LINE + " <xs:complexType>" + NEW_LINE + " <xs:sequence>" + NEW_LINE + " <xs:element name=\"note\" maxOccurs=\"unbounded\">" + NEW_LINE + " <xs:complexType>" + NEW_LINE + " <xs:sequence>" + NEW_LINE + " <xs:element name=\"to\" minOccurs=\"1\" maxOccurs=\"1\" type=\"xs:string\"></xs:element>" + NEW_LINE + " <xs:element name=\"from\" minOccurs=\"1\" maxOccurs=\"1\" type=\"xs:string\"></xs:element>" + NEW_LINE + " <xs:element name=\"heading\" minOccurs=\"1\" maxOccurs=\"1\" type=\"xs:string\"></xs:element>" + NEW_LINE + " <xs:element name=\"body\" minOccurs=\"1\" maxOccurs=\"1\" type=\"xs:string\"></xs:element>" + NEW_LINE + " </xs:sequence>" + NEW_LINE + " </xs:complexType>" + NEW_LINE + " </xs:element>" + NEW_LINE + " </xs:sequence>" + NEW_LINE + " </xs:complexType>" + NEW_LINE + " </xs:element>" + NEW_LINE + "</xs:schema>")), exactly(2) ) .respond( response() .withBody("some_body") ); // then // - in http assertEquals( response() .withStatusCode(NOT_FOUND_404.code()), makeRequest( request() .withMethod("POST") .withBody("<?xml version=\"1.0\" encoding=\"utf-8\"?>" + NEW_LINE + "<notes>" + NEW_LINE + " <note>" + NEW_LINE + " <to>Bob</to>" + NEW_LINE + " <heading>Reminder</heading>" + NEW_LINE + " <body>Buy Bread</body>" + NEW_LINE + " </note>" + NEW_LINE + " <note>" + NEW_LINE + " <to>Jack</to>" + NEW_LINE + " <from>Jill</from>" + NEW_LINE + " <heading>Reminder</heading>" + NEW_LINE + " <body>Wash Shirts</body>" + NEW_LINE + " </note>" + NEW_LINE + "</notes>"), headersToIgnore) ); assertEquals( response() .withStatusCode(OK_200.code()) .withBody("some_body"), makeRequest( request() .withPath(calculatePath("some_path")) .withMethod("POST") .withBody("<?xml version=\"1.0\" encoding=\"utf-8\"?>" + NEW_LINE + "<notes>" + NEW_LINE + " <note>" + NEW_LINE + " <to>Bob</to>" + NEW_LINE + " <from>Bill</from>" + NEW_LINE + " <heading>Reminder</heading>" + NEW_LINE + " <body>Buy Bread</body>" + NEW_LINE + " </note>" + NEW_LINE + " <note>" + NEW_LINE + " <to>Jack</to>" + NEW_LINE + " <from>Jill</from>" + NEW_LINE + " <heading>Reminder</heading>" + NEW_LINE + " <body>Wash Shirts</body>" + NEW_LINE + " </note>" + NEW_LINE + "</notes>"), headersToIgnore) ); // - in https assertEquals( response() .withStatusCode(OK_200.code()) .withBody("some_body"), makeRequest( request() .withSecure(true) .withPath(calculatePath("some_path")) .withMethod("POST") .withBody("<?xml version=\"1.0\" encoding=\"utf-8\"?>" + NEW_LINE + "<notes>" + NEW_LINE + " <note>" + NEW_LINE + " <to>Bob</to>" + NEW_LINE + " <from>Bill</from>" + NEW_LINE + " <heading>Reminder</heading>" + NEW_LINE + " <body>Buy Bread</body>" + NEW_LINE + " </note>" + NEW_LINE + " <note>" + NEW_LINE + " <to>Jack</to>" + NEW_LINE + " <from>Jill</from>" + NEW_LINE + " <heading>Reminder</heading>" + NEW_LINE + " <body>Wash Shirts</body>" + NEW_LINE + " </note>" + NEW_LINE + "</notes>"), headersToIgnore) ); } @Test @Ignore public void shouldReturnResponseByMatchingBodyWithXmlSchemaByClasspath() { // when mockServerClient.when(request() .withBody( xmlSchema("org/mockserver/model/testXmlSchema.xsd")), exactly(2) ) .respond( response() .withBody("some_body") ); // then // - in http assertEquals( response() .withStatusCode(NOT_FOUND_404.code()), makeRequest( request() .withMethod("POST") .withBody("<?xml version=\"1.0\" encoding=\"utf-8\"?>" + NEW_LINE + "<notes>" + NEW_LINE + " <note>" + NEW_LINE + " <to>Bob</to>" + NEW_LINE + " <heading>Reminder</heading>" + NEW_LINE + " <body>Buy Bread</body>" + NEW_LINE + " </note>" + NEW_LINE + " <note>" + NEW_LINE + " <to>Jack</to>" + NEW_LINE + " <from>Jill</from>" + NEW_LINE + " <heading>Reminder</heading>" + NEW_LINE + " <body>Wash Shirts</body>" + NEW_LINE + " </note>" + NEW_LINE + "</notes>"), headersToIgnore) ); assertEquals( response() .withStatusCode(OK_200.code()) .withBody("some_body"), makeRequest( request() .withPath(calculatePath("some_path")) .withMethod("POST") .withBody("<?xml version=\"1.0\" encoding=\"utf-8\"?>" + NEW_LINE + "<notes>" + NEW_LINE + " <note>" + NEW_LINE + " <to>Bob</to>" + NEW_LINE + " <from>Bill</from>" + NEW_LINE + " <heading>Reminder</heading>" + NEW_LINE + " <body>Buy Bread</body>" + NEW_LINE + " </note>" + NEW_LINE + " <note>" + NEW_LINE + " <to>Jack</to>" + NEW_LINE + " <from>Jill</from>" + NEW_LINE + " <heading>Reminder</heading>" + NEW_LINE + " <body>Wash Shirts</body>" + NEW_LINE + " </note>" + NEW_LINE + "</notes>"), headersToIgnore) ); // - in https assertEquals( response() .withStatusCode(OK_200.code()) .withBody("some_body"), makeRequest( request() .withSecure(true) .withPath(calculatePath("some_path")) .withMethod("POST") .withBody("<?xml version=\"1.0\" encoding=\"utf-8\"?>" + NEW_LINE + "<notes>" + NEW_LINE + " <note>" + NEW_LINE + " <to>Bob</to>" + NEW_LINE + " <from>Bill</from>" + NEW_LINE + " <heading>Reminder</heading>" + NEW_LINE + " <body>Buy Bread</body>" + NEW_LINE + " </note>" + NEW_LINE + " <note>" + NEW_LINE + " <to>Jack</to>" + NEW_LINE + " <from>Jill</from>" + NEW_LINE + " <heading>Reminder</heading>" + NEW_LINE + " <body>Wash Shirts</body>" + NEW_LINE + " </note>" + NEW_LINE + "</notes>"), headersToIgnore) ); } @Test public void shouldReturnPDFResponseByMatchingPath() throws IOException { // when byte[] pdfBytes = IOUtils.toByteArray(getClass().getClassLoader().getResourceAsStream("test.pdf")); mockServerClient .when( request() .withPath(calculatePath("ws/rest/user/[0-9]+/document/[0-9]+\\.pdf")) ) .respond( response() .withStatusCode(OK_200.code()) .withHeaders( header(CONTENT_TYPE.toString(), MediaType.PDF.toString()), header(CONTENT_DISPOSITION.toString(), "form-data; name=\"test.pdf\"; filename=\"test.pdf\""), header(CACHE_CONTROL.toString(), "must-revalidate, post-check=0, pre-check=0") ) .withBody(binary(pdfBytes)) ); // then // - in http assertEquals( response() .withStatusCode(OK_200.code()) .withHeaders( header(CONTENT_DISPOSITION.toString(), "form-data; name=\"test.pdf\"; filename=\"test.pdf\""), header(CACHE_CONTROL.toString(), "must-revalidate, post-check=0, pre-check=0"), header(CONTENT_TYPE.toString(), MediaType.PDF.toString()) ) .withBody(binary(pdfBytes)), makeRequest( request() .withPath(calculatePath("ws/rest/user/1/document/2.pdf")) .withMethod("GET"), headersToIgnore) ); // - in https assertEquals( response() .withStatusCode(OK_200.code()) .withHeaders( header(CONTENT_DISPOSITION.toString(), "form-data; name=\"test.pdf\"; filename=\"test.pdf\""), header(CACHE_CONTROL.toString(), "must-revalidate, post-check=0, pre-check=0"), header(CONTENT_TYPE.toString(), MediaType.PDF.toString()) ) .withBody(binary(pdfBytes)), makeRequest( request() .withSecure(true) .withPath(calculatePath("ws/rest/user/1/document/2.pdf")) .withMethod("GET"), headersToIgnore) ); } @Test public void shouldReturnPNGResponseByMatchingPath() throws IOException { // when byte[] pngBytes = IOUtils.toByteArray(getClass().getClassLoader().getResourceAsStream("test.png")); mockServerClient .when( request() .withPath(calculatePath("ws/rest/user/[0-9]+/icon/[0-9]+\\.png")) ) .respond( response() .withStatusCode(OK_200.code()) .withHeaders( header(CONTENT_TYPE.toString(), MediaType.PNG.toString()), header(CONTENT_DISPOSITION.toString(), "form-data; name=\"test.png\"; filename=\"test.png\"") ) .withBody(binary(pngBytes)) ); // then // - in http assertEquals( response() .withStatusCode(OK_200.code()) .withHeaders( header(CONTENT_DISPOSITION.toString(), "form-data; name=\"test.png\"; filename=\"test.png\""), header(CONTENT_TYPE.toString(), MediaType.PNG.toString()) ) .withBody(binary(pngBytes)), makeRequest( request() .withPath(calculatePath("ws/rest/user/1/icon/1.png")) .withMethod("GET"), headersToIgnore) ); // - in https assertEquals( response() .withStatusCode(OK_200.code()) .withHeaders( header(CONTENT_DISPOSITION.toString(), "form-data; name=\"test.png\"; filename=\"test.png\""), header(CONTENT_TYPE.toString(), MediaType.PNG.toString()) ) .withBody(binary(pngBytes)), makeRequest( request() .withSecure(true) .withPath(calculatePath("ws/rest/user/1/icon/1.png")) .withMethod("GET"), headersToIgnore) ); } @Test public void shouldReturnPDFResponseByMatchingBinaryPDFBody() throws IOException { // when byte[] pdfBytes = IOUtils.toByteArray(getClass().getClassLoader().getResourceAsStream("test.pdf")); mockServerClient .when( request().withBody(binary(pdfBytes)) ) .respond( response() .withStatusCode(OK_200.code()) .withHeaders( header(CONTENT_TYPE.toString(), MediaType.PDF.toString()), header(CONTENT_DISPOSITION.toString(), "form-data; name=\"test.pdf\"; filename=\"test.pdf\""), header(CACHE_CONTROL.toString(), "must-revalidate, post-check=0, pre-check=0") ) .withBody(binary(pdfBytes)) ); // then // - in http assertEquals( response() .withStatusCode(OK_200.code()) .withHeaders( header(CONTENT_DISPOSITION.toString(), "form-data; name=\"test.pdf\"; filename=\"test.pdf\""), header(CACHE_CONTROL.toString(), "must-revalidate, post-check=0, pre-check=0"), header(CONTENT_TYPE.toString(), MediaType.PDF.toString()) ) .withBody(binary(pdfBytes)), makeRequest( request() .withPath(calculatePath("ws/rest/user/1/document/2.pdf")) .withBody(binary(pdfBytes)) .withMethod("POST"), headersToIgnore) ); // - in https assertEquals( response() .withStatusCode(OK_200.code()) .withHeaders( header(CONTENT_DISPOSITION.toString(), "form-data; name=\"test.pdf\"; filename=\"test.pdf\""), header(CACHE_CONTROL.toString(), "must-revalidate, post-check=0, pre-check=0"), header(CONTENT_TYPE.toString(), MediaType.PDF.toString()) ) .withBody(binary(pdfBytes)), makeRequest( request() .withSecure(true) .withPath(calculatePath("ws/rest/user/1/document/2.pdf")) .withBody(binary(pdfBytes)) .withMethod("POST"), headersToIgnore) ); } @Test public void shouldReturnPNGResponseByMatchingBinaryPNGBody() throws IOException { // when byte[] pngBytes = IOUtils.toByteArray(getClass().getClassLoader().getResourceAsStream("test.png")); mockServerClient .when( request().withBody(binary(pngBytes)) ) .respond( response() .withStatusCode(OK_200.code()) .withHeaders( header(CONTENT_TYPE.toString(), MediaType.PNG.toString()), header(CONTENT_DISPOSITION.toString(), "form-data; name=\"test.png\"; filename=\"test.png\"") ) .withBody(binary(pngBytes)) ); // then // - in http assertEquals( response() .withStatusCode(OK_200.code()) .withHeaders( header(CONTENT_DISPOSITION.toString(), "form-data; name=\"test.png\"; filename=\"test.png\""), header(CONTENT_TYPE.toString(), MediaType.PNG.toString()) ) .withBody(binary(pngBytes)), makeRequest( request() .withPath(calculatePath("ws/rest/user/1/icon/1.png")) .withBody(binary(pngBytes)) .withMethod("POST"), headersToIgnore) ); // - in https assertEquals( response() .withStatusCode(OK_200.code()) .withHeaders( header(CONTENT_DISPOSITION.toString(), "form-data; name=\"test.png\"; filename=\"test.png\""), header(CONTENT_TYPE.toString(), MediaType.PNG.toString()) ) .withBody(binary(pngBytes)), makeRequest( request() .withSecure(true) .withPath(calculatePath("ws/rest/user/1/icon/1.png")) .withBody(binary(pngBytes)) .withMethod("POST"), headersToIgnore) ); } @Test public void shouldReturnResponseForExpectationWithDelay() { // when mockServerClient .when( request() .withPath(calculatePath("some_path1")) ) .respond( response() .withBody("some_body1") .withDelay(new Delay(TimeUnit.MILLISECONDS, 10)) ); mockServerClient .when( request() .withPath(calculatePath("some_path2")) ) .respond( response() .withBody("some_body2") .withDelay(new Delay(TimeUnit.MILLISECONDS, 20)) ); // then // - in http assertEquals( response() .withStatusCode(OK_200.code()) .withBody("some_body2"), makeRequest( request() .withPath(calculatePath("some_path2")), headersToIgnore) ); assertEquals( response() .withStatusCode(OK_200.code()) .withBody("some_body1"), makeRequest( request() .withPath(calculatePath("some_path1")), headersToIgnore) ); // - in https assertEquals( response() .withStatusCode(OK_200.code()) .withBody("some_body2"), makeRequest( request() .withSecure(true) .withPath(calculatePath("some_path2")), headersToIgnore) ); assertEquals( response() .withStatusCode(OK_200.code()) .withBody("some_body1"), makeRequest( request() .withSecure(true) .withPath(calculatePath("some_path1")), headersToIgnore) ); } @Test public void shouldReturnResponseByMatchingPathAndMethod() { // when mockServerClient .when( request() .withMethod("GET") .withPath(calculatePath("some_pathRequest")) ) .respond( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body_response") ); // then // - in http assertEquals( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body_response"), makeRequest( request() .withMethod("GET") .withPath(calculatePath("some_pathRequest")) .withQueryStringParameters( param("queryStringParameterOneName", "queryStringParameterOneValue"), param("queryStringParameterTwoName", "queryStringParameterTwoValue") ) .withHeaders(header("headerNameRequest", "headerValueRequest")) .withCookies(cookie("cookieNameRequest", "cookieValueRequest")), headersToIgnore) ); // - in https assertEquals( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body_response"), makeRequest( request() .withMethod("GET") .withSecure(true) .withPath(calculatePath("some_pathRequest")) .withQueryStringParameters( param("queryStringParameterOneName", "queryStringParameterOneValue"), param("queryStringParameterTwoName", "queryStringParameterTwoValue") ) .withHeaders(header("headerNameRequest", "headerValueRequest")) .withCookies(cookie("cookieNameRequest", "cookieValueRequest")), headersToIgnore) ); } @Test public void shouldReturnResponseByNotMatchingPathWithNotOperator() { // when mockServerClient .when( request() .withPath(not(calculatePath("some_path"))) ) .respond( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body_response") ); // then // - in http assertEquals( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body_response"), makeRequest( request() .withPath(calculatePath("some_other_path")), headersToIgnore) ); // - in https assertEquals( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body_response"), makeRequest( request() .withPath(calculatePath("some_other_path")), headersToIgnore) ); } @Test public void shouldReturnResponseByNotMatchingMethodWithNotOperator() { // when mockServerClient .when( request() .withMethod(not("GET")) ) .respond( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body_response") ); // then // - in http assertEquals( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body_response"), makeRequest( request() .withMethod("POST"), headersToIgnore) ); // - in https assertEquals( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body_response"), makeRequest( request() .withMethod("POST"), headersToIgnore) ); } @Test public void shouldReturnResponseByMatchingPathAndMethodAndBody() { // when mockServerClient .when( request() .withMethod("POST") .withPath(calculatePath("some_pathRequest")) .withBody("some_bodyRequest") ) .respond( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body_response") .withHeaders(header("headerNameResponse", "headerValueResponse")) ); // then // - in http assertEquals( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body_response") .withHeaders( header("headerNameResponse", "headerValueResponse") ), makeRequest( request() .withMethod("POST") .withPath(calculatePath("some_pathRequest")) .withQueryStringParameters( param("queryStringParameterOneName", "queryStringParameterOneValue"), param("queryStringParameterTwoName", "queryStringParameterTwoValue") ) .withBody("some_bodyRequest") .withHeaders(header("headerNameRequest", "headerValueRequest")) .withCookies(cookie("cookieNameRequest", "cookieValueRequest")), headersToIgnore) ); // - in https assertEquals( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body_response") .withHeaders( header("headerNameResponse", "headerValueResponse") ), makeRequest( request() .withMethod("POST") .withSecure(true) .withPath(calculatePath("some_pathRequest")) .withQueryStringParameters( param("queryStringParameterOneName", "queryStringParameterOneValue"), param("queryStringParameterTwoName", "queryStringParameterTwoValue") ) .withBody("some_bodyRequest") .withHeaders(header("headerNameRequest", "headerValueRequest")) .withCookies(cookie("cookieNameRequest", "cookieValueRequest")), headersToIgnore) ); } @Test public void shouldReturnResponseByMatchingPathAndMethodAndQueryStringParameters() { // when mockServerClient .when( request() .withMethod("GET") .withPath(calculatePath("some_pathRequest")) .withQueryStringParameters( param("queryStringParameterOneName", "queryStringParameterOneValue"), param("queryStringParameterTwoName", "queryStringParameterTwoValue") ) ) .respond( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body_response") .withCookies(cookie("cookieNameResponse", "cookieValueResponse")) ); // then // - in http assertEquals( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body_response") .withCookies(cookie("cookieNameResponse", "cookieValueResponse")) .withHeaders( header(SET_COOKIE.toString(), "cookieNameResponse=cookieValueResponse") ), makeRequest( request() .withMethod("GET") .withPath(calculatePath("some_pathRequest")) .withQueryStringParameters( param("queryStringParameterOneName", "queryStringParameterOneValue"), param("queryStringParameterTwoName", "queryStringParameterTwoValue") ) .withHeaders(header("headerNameRequest", "headerValueRequest")) .withCookies(cookie("cookieNameRequest", "cookieValueRequest")), headersToIgnore) ); // - in https assertEquals( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body_response") .withCookies(cookie("cookieNameResponse", "cookieValueResponse")) .withHeaders( header(SET_COOKIE.toString(), "cookieNameResponse=cookieValueResponse") ), makeRequest( request() .withMethod("GET") .withSecure(true) .withPath(calculatePath("some_pathRequest")) .withQueryStringParameters( param("queryStringParameterOneName", "queryStringParameterOneValue"), param("queryStringParameterTwoName", "queryStringParameterTwoValue") ) .withHeaders(header("headerNameRequest", "headerValueRequest")) .withCookies(cookie("cookieNameRequest", "cookieValueRequest")), headersToIgnore) ); } @Test public void shouldReturnResponseByMatchingPathAndMethodAndHeaders() { // when mockServerClient .when( request() .withMethod("GET") .withPath(calculatePath("some_pathRequest")) .withHeaders( header("requestHeaderNameOne", "requestHeaderValueOne_One", "requestHeaderValueOne_Two"), header("requestHeaderNameTwo", "requestHeaderValueTwo") ) ) .respond( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body_response") .withCookies(cookie("cookieNameResponse", "cookieValueResponse")) ); // then // - in http assertEquals( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body_response") .withCookies(cookie("cookieNameResponse", "cookieValueResponse")) .withHeaders( header(SET_COOKIE.toString(), "cookieNameResponse=cookieValueResponse") ), makeRequest( request() .withMethod("GET") .withPath(calculatePath("some_pathRequest")) .withHeaders( header("requestHeaderNameOne", "requestHeaderValueOne_One", "requestHeaderValueOne_Two"), header("requestHeaderNameTwo", "requestHeaderValueTwo") ) .withCookies(cookie("cookieNameRequest", "cookieValueRequest")), headersToIgnore) ); // - in https assertEquals( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body_response") .withCookies(cookie("cookieNameResponse", "cookieValueResponse")) .withHeaders( header(SET_COOKIE.toString(), "cookieNameResponse=cookieValueResponse") ), makeRequest( request() .withMethod("GET") .withSecure(true) .withPath(calculatePath("some_pathRequest")) .withHeaders( header("requestHeaderNameOne", "requestHeaderValueOne_One", "requestHeaderValueOne_Two"), header("requestHeaderNameTwo", "requestHeaderValueTwo") ) .withCookies(cookie("cookieNameRequest", "cookieValueRequest")), headersToIgnore) ); } @Test public void shouldReturnResponseByMatchingPathAndMethodAndCookies() { // when mockServerClient .when( request() .withMethod("GET") .withPath(calculatePath("some_pathRequest")) .withCookies( cookie("requestCookieNameOne", "requestCookieValueOne"), cookie("requestCookieNameTwo", "requestCookieValueTwo") ) ) .respond( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body_response") .withCookies( cookie("responseCookieNameOne", "responseCookieValueOne"), cookie("responseCookieNameTwo", "responseCookieValueTwo") ) ); // then // - in http - cookie objects assertEquals( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body_response") .withCookies( cookie("responseCookieNameOne", "responseCookieValueOne"), cookie("responseCookieNameTwo", "responseCookieValueTwo") ) .withHeaders( header(SET_COOKIE.toString(), "responseCookieNameOne=responseCookieValueOne", "responseCookieNameTwo=responseCookieValueTwo") ), makeRequest( request() .withMethod("GET") .withPath(calculatePath("some_pathRequest")) .withHeaders( header("headerNameRequest", "headerValueRequest"), header(CONTENT_TYPE.toString(), TEXT_PLAIN) ) .withCookies( cookie("requestCookieNameOne", "requestCookieValueOne"), cookie("requestCookieNameTwo", "requestCookieValueTwo") ), headersToIgnore) ); // - in http - cookie header assertEquals( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body_response") .withCookies( cookie("responseCookieNameOne", "responseCookieValueOne"), cookie("responseCookieNameTwo", "responseCookieValueTwo") ) .withHeaders( header(SET_COOKIE.toString(), "responseCookieNameOne=responseCookieValueOne", "responseCookieNameTwo=responseCookieValueTwo") ), makeRequest( request() .withMethod("GET") .withPath(calculatePath("some_pathRequest")) .withHeaders( header("headerNameRequest", "headerValueRequest"), header("Cookie", "requestCookieNameOne=requestCookieValueOne; requestCookieNameTwo=requestCookieValueTwo") ), headersToIgnore) ); // - in https - cookie objects assertEquals( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body_response") .withCookies( cookie("responseCookieNameOne", "responseCookieValueOne"), cookie("responseCookieNameTwo", "responseCookieValueTwo") ) .withHeaders( header(SET_COOKIE.toString(), "responseCookieNameOne=responseCookieValueOne", "responseCookieNameTwo=responseCookieValueTwo") ), makeRequest( request() .withMethod("GET") .withSecure(true) .withPath(calculatePath("some_pathRequest")) .withHeaders( header("headerNameRequest", "headerValueRequest") ) .withCookies( cookie("requestCookieNameOne", "requestCookieValueOne"), cookie("requestCookieNameTwo", "requestCookieValueTwo") ), headersToIgnore) ); // - in https - cookie header assertEquals( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body_response") .withCookies( cookie("responseCookieNameOne", "responseCookieValueOne"), cookie("responseCookieNameTwo", "responseCookieValueTwo") ) .withHeaders( header(SET_COOKIE.toString(), "responseCookieNameOne=responseCookieValueOne", "responseCookieNameTwo=responseCookieValueTwo") ), makeRequest( request() .withMethod("GET") .withSecure(true) .withPath(calculatePath("some_pathRequest")) .withHeaders( header("headerNameRequest", "headerValueRequest"), header("Cookie", "requestCookieNameOne=requestCookieValueOne; requestCookieNameTwo=requestCookieValueTwo") ), headersToIgnore) ); } @Test public void shouldReturnResponseByMatchingPathAndMethodAndQueryStringParametersAndBodyParameters() { // when mockServerClient .when( request() .withMethod("POST") .withPath(calculatePath("some_pathRequest")) .withQueryStringParameters( param("queryStringParameterOneName", "queryStringParameterOneValueOne", "queryStringParameterOneValueTwo"), param("queryStringParameterTwoName", "queryStringParameterTwoValue") ) .withBody(params(param("bodyParameterName", "bodyParameterValue"))) ) .respond( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body") ); // then // - in http - url query string assertEquals( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body"), makeRequest( request() .withMethod("POST") .withPath(calculatePath("some_pathRequest")) .withQueryStringParameters( param("queryStringParameterOneName", "queryStringParameterOneValueOne", "queryStringParameterOneValueTwo"), param("queryStringParameterTwoName", "queryStringParameterTwoValue") ) .withBody(params(param("bodyParameterName", "bodyParameterValue"))), headersToIgnore) ); // - in https - query string parameter objects assertEquals( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body"), makeRequest( request() .withSecure(true) .withMethod("POST") .withPath(calculatePath("some_pathRequest")) .withQueryStringParameters( param("queryStringParameterOneName", "queryStringParameterOneValueOne", "queryStringParameterOneValueTwo"), param("queryStringParameterTwoName", "queryStringParameterTwoValue") ) .withBody(params(param("bodyParameterName", "bodyParameterValue"))), headersToIgnore) ); } @Test public void shouldReturnResponseByMatchingPathAndMethodAndQueryStringParametersAndBody() { // when mockServerClient .when( request() .withMethod("POST") .withPath(calculatePath("some_pathRequest")) .withQueryStringParameters( param("queryStringParameterOneName", "queryStringParameterOneValueOne", "queryStringParameterOneValueTwo"), param("queryStringParameterTwoName", "queryStringParameterTwoValue") ) .withBody("some_bodyRequest") ) .respond( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body_response") .withHeaders(header("headerNameResponse", "headerValueResponse")) .withCookies(cookie("cookieNameResponse", "cookieValueResponse")) ); // then // - in http - url query string assertEquals( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body_response") .withCookies(cookie("cookieNameResponse", "cookieValueResponse")) .withHeaders( header("headerNameResponse", "headerValueResponse"), header(SET_COOKIE.toString(), "cookieNameResponse=cookieValueResponse") ), makeRequest( request() .withMethod("POST") .withPath(calculatePath("some_pathRequest")) .withQueryStringParameters( param("queryStringParameterOneName", "queryStringParameterOneValueOne", "queryStringParameterOneValueTwo"), param("queryStringParameterTwoName", "queryStringParameterTwoValue") ) .withBody("some_bodyRequest") .withHeaders(header("headerNameRequest", "headerValueRequest")) .withCookies(cookie("cookieNameRequest", "cookieValueRequest")), headersToIgnore) ); // - in http - query string parameter objects assertEquals( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body_response") .withCookies(cookie("cookieNameResponse", "cookieValueResponse")) .withHeaders( header("headerNameResponse", "headerValueResponse"), header(SET_COOKIE.toString(), "cookieNameResponse=cookieValueResponse") ), makeRequest( request() .withMethod("POST") .withPath(calculatePath("some_pathRequest")) .withQueryStringParameters( param("queryStringParameterOneName", "queryStringParameterOneValueOne", "queryStringParameterOneValueTwo"), param("queryStringParameterTwoName", "queryStringParameterTwoValue") ) .withBody("some_bodyRequest") .withHeaders(header("headerNameRequest", "headerValueRequest")) .withCookies(cookie("cookieNameRequest", "cookieValueRequest")), headersToIgnore) ); // - in https - url string and query string parameter objects assertEquals( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body_response") .withCookies(cookie("cookieNameResponse", "cookieValueResponse")) .withHeaders( header("headerNameResponse", "headerValueResponse"), header(SET_COOKIE.toString(), "cookieNameResponse=cookieValueResponse") ), makeRequest( request() .withMethod("POST") .withPath(calculatePath("some_pathRequest")) .withQueryStringParameters( param("queryStringParameterOneName", "queryStringParameterOneValueOne", "queryStringParameterOneValueTwo"), param("queryStringParameterTwoName", "queryStringParameterTwoValue") ) .withBody("some_bodyRequest") .withHeaders(header("headerNameRequest", "headerValueRequest")) .withCookies(cookie("cookieNameRequest", "cookieValueRequest")), headersToIgnore) ); } @Test public void shouldReturnResponseByMatchingPathAndMethodAndBodyParameters() { // when mockServerClient .when( request() .withMethod("POST") .withPath(calculatePath("some_pathRequest")) .withBody(params( param("bodyParameterOneName", "Parameter One Value One", "Parameter One Value Two"), param("bodyParameterTwoName", "Parameter Two") )) ) .respond( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body_response") .withHeaders(header("headerNameResponse", "headerValueResponse")) .withCookies(cookie("cookieNameResponse", "cookieValueResponse")) ); // then // - in http - body string assertEquals( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body_response") .withCookies(cookie("cookieNameResponse", "cookieValueResponse")) .withHeaders( header("headerNameResponse", "headerValueResponse"), header(SET_COOKIE.toString(), "cookieNameResponse=cookieValueResponse") ), makeRequest( request() .withMethod("POST") .withPath(calculatePath("some_pathRequest")) .withBody(new StringBody("bodyParameterOneName=Parameter+One+Value+One" + "&bodyParameterOneName=Parameter+One+Value+Two" + "&bodyParameterTwoName=Parameter+Two")) .withHeaders(header("headerNameRequest", "headerValueRequest")) .withCookies(cookie("cookieNameRequest", "cookieValueRequest")), headersToIgnore) ); // - in http - body parameter objects assertEquals( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body_response") .withCookies(cookie("cookieNameResponse", "cookieValueResponse")) .withHeaders( header("headerNameResponse", "headerValueResponse"), header(SET_COOKIE.toString(), "cookieNameResponse=cookieValueResponse") ), makeRequest( request() .withMethod("POST") .withPath(calculatePath("some_pathRequest")) .withBody(params( param("bodyParameterOneName", "Parameter One Value One", "Parameter One Value Two"), param("bodyParameterTwoName", "Parameter Two") )) .withHeaders(header("headerNameRequest", "headerValueRequest")) .withCookies(cookie("cookieNameRequest", "cookieValueRequest")), headersToIgnore) ); // - in https - url string and query string parameter objects assertEquals( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body_response") .withCookies(cookie("cookieNameResponse", "cookieValueResponse")) .withHeaders( header("headerNameResponse", "headerValueResponse"), header(SET_COOKIE.toString(), "cookieNameResponse=cookieValueResponse") ), makeRequest( request() .withMethod("POST") .withPath(calculatePath("some_pathRequest")) .withBody(params( param("bodyParameterOneName", "Parameter One Value One", "Parameter One Value Two"), param("bodyParameterTwoName", "Parameter Two") )) .withHeaders(header("headerNameRequest", "headerValueRequest")) .withCookies(cookie("cookieNameRequest", "cookieValueRequest")), headersToIgnore) ); } @Test public void shouldReturnResponseByMatchingPathAndMethodAndParametersAndHeadersAndCookies() { // when mockServerClient .when( request() .withMethod("PUT") .withPath(calculatePath("some_pathRequest")) .withBody(new StringBody("bodyParameterOneName=Parameter+One+Value+One" + "&bodyParameterOneName=Parameter+One+Value+Two" + "&bodyParameterTwoName=Parameter+Two")) .withHeaders(header("headerNameRequest", "headerValueRequest")) .withCookies(cookie("cookieNameRequest", "cookieValueRequest")) ) .respond( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body_response") .withHeaders(header("headerNameResponse", "headerValueResponse")) .withCookies(cookie("cookieNameResponse", "cookieValueResponse")) ); // then // - in http - body string assertEquals( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body_response") .withCookies(cookie("cookieNameResponse", "cookieValueResponse")) .withHeaders( header("headerNameResponse", "headerValueResponse"), header(SET_COOKIE.toString(), "cookieNameResponse=cookieValueResponse") ), makeRequest( request() .withMethod("PUT") .withPath(calculatePath("some_pathRequest")) .withBody(new StringBody("bodyParameterOneName=Parameter+One+Value+One" + "&bodyParameterOneName=Parameter+One+Value+Two" + "&bodyParameterTwoName=Parameter+Two")) .withHeaders( header("headerNameRequest", "headerValueRequest"), header("Cookie", "cookieNameRequest=cookieValueRequest") ), headersToIgnore) ); // - in http - body parameter objects assertEquals( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body_response") .withCookies(cookie("cookieNameResponse", "cookieValueResponse")) .withHeaders( header("headerNameResponse", "headerValueResponse"), header(SET_COOKIE.toString(), "cookieNameResponse=cookieValueResponse") ), makeRequest( request() .withMethod("PUT") .withPath(calculatePath("some_pathRequest")) .withBody(params( param("bodyParameterOneName", "Parameter One Value One", "Parameter One Value Two"), param("bodyParameterTwoName", "Parameter Two") )) .withHeaders(header("headerNameRequest", "headerValueRequest")) .withCookies(cookie("cookieNameRequest", "cookieValueRequest")), headersToIgnore) ); } @Test public void shouldReturnResponseByNotMatchingBodyParameterWithNotOperatorForNameAndValue() { // when mockServerClient .when( request() .withMethod("POST") .withPath(calculatePath("some_pathRequest")) .withBody(params( param(not("bodyParameterOneName"), not("Parameter One Value One"), not("Parameter One Value Two")), param("bodyParameterTwoName", "Parameter Two") )) ) .respond( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body_response") ); // then // wrong query string parameter name assertEquals( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body_response"), makeRequest( request() .withMethod("POST") .withPath(calculatePath("some_pathRequest")) .withBody(params( param("OTHERBodyParameterOneName", "Parameter One Value One", "Parameter One Value Two"), param("bodyParameterTwoName", "Parameter Two") )) .withHeaders(header("headerNameRequest", "headerValueRequest")) .withCookies(cookie("cookieNameRequest", "cookieValueRequest")), headersToIgnore) ); // wrong query string parameter name assertEquals( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body_response"), makeRequest( request() .withMethod("POST") .withPath(calculatePath("some_pathRequest")) .withBody(new StringBody("OTHERBodyParameterOneName=Parameter+One+Value+One" + "&OTHERBodyParameterOneName=Parameter+One+Value+Two" + "&bodyParameterTwoName=Parameter+Two")) .withHeaders(header("headerNameRequest", "headerValueRequest")) .withCookies(cookie("cookieNameRequest", "cookieValueRequest")), headersToIgnore) ); // wrong query string parameter value assertEquals( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body_response"), makeRequest( request() .withMethod("POST") .withPath(calculatePath("some_pathRequest")) .withBody(params( param("bodyParameterOneName", "OTHER Parameter One Value One", "OTHER Parameter One Value Two"), param("bodyParameterTwoName", "Parameter Two") )) .withHeaders(header("headerNameRequest", "headerValueRequest")) .withCookies(cookie("cookieNameRequest", "cookieValueRequest")), headersToIgnore) ); // wrong query string parameter value assertEquals( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body_response"), makeRequest( request() .withMethod("POST") .withPath(calculatePath("some_pathRequest")) .withBody(new StringBody("bodyParameterOneName=OTHER Parameter+One+Value+One" + "&bodyParameterOneName=OTHER Parameter+One+Value+Two" + "&bodyParameterTwoName=Parameter+Two")) .withHeaders(header("headerNameRequest", "headerValueRequest")) .withCookies(cookie("cookieNameRequest", "cookieValueRequest")), headersToIgnore) ); } @Test public void shouldReturnResponseByNotMatchingBodyParameterWithNotOperatorForName() { // when mockServerClient .when( request() .withMethod("POST") .withPath(calculatePath("some_pathRequest")) .withBody(params( param(not("bodyParameterOneName"), string("Parameter One Value One"), string("Parameter One Value Two")), param("bodyParameterTwoName", "Parameter Two") )) ) .respond( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body_response") ); // then // wrong query string parameter name assertEquals( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body_response"), makeRequest( request() .withMethod("POST") .withPath(calculatePath("some_pathRequest")) .withBody(params( param("OTHERBodyParameterOneName", "Parameter One Value One", "Parameter One Value Two"), param("bodyParameterTwoName", "Parameter Two") )) .withHeaders(header("headerNameRequest", "headerValueRequest")) .withCookies(cookie("cookieNameRequest", "cookieValueRequest")), headersToIgnore) ); // wrong query string parameter name assertEquals( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body_response"), makeRequest( request() .withMethod("POST") .withPath(calculatePath("some_pathRequest")) .withBody(new StringBody("OTHERBodyParameterOneName=Parameter+One+Value+One" + "&OTHERBodyParameterOneName=Parameter+One+Value+Two" + "&bodyParameterTwoName=Parameter+Two")) .withHeaders(header("headerNameRequest", "headerValueRequest")) .withCookies(cookie("cookieNameRequest", "cookieValueRequest")), headersToIgnore) ); } @Test public void shouldReturnResponseByNotMatchingBodyParameterWithNotOperatorForValue() { // when mockServerClient .when( request() .withMethod("POST") .withPath(calculatePath("some_pathRequest")) .withBody(params( param(string("bodyParameterOneName"), not("Parameter One Value One"), not("Parameter One Value Two")), param("bodyParameterTwoName", "Parameter Two") )) ) .respond( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body_response") ); // then // wrong query string parameter value assertEquals( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body_response"), makeRequest( request() .withMethod("POST") .withPath(calculatePath("some_pathRequest")) .withBody(params( param("bodyParameterOneName", "OTHER Parameter One Value One", "OTHER Parameter One Value Two"), param("bodyParameterTwoName", "Parameter Two") )) .withHeaders(header("headerNameRequest", "headerValueRequest")) .withCookies(cookie("cookieNameRequest", "cookieValueRequest")), headersToIgnore) ); // wrong query string parameter value assertEquals( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body_response"), makeRequest( request() .withMethod("POST") .withPath(calculatePath("some_pathRequest")) .withBody(new StringBody("bodyParameterOneName=OTHER Parameter+One+Value+One" + "&bodyParameterOneName=OTHER Parameter+One+Value+Two" + "&bodyParameterTwoName=Parameter+Two")) .withHeaders(header("headerNameRequest", "headerValueRequest")) .withCookies(cookie("cookieNameRequest", "cookieValueRequest")), headersToIgnore) ); } @Test public void shouldReturnResponseByNotMatchingQueryStringParameterWithNotOperatorForNameAndValue() { // when mockServerClient .when( request() .withMethod("POST") .withPath(calculatePath("some_pathRequest")) .withQueryStringParameters( param(not("queryStringParameterOneName"), not("Parameter One Value One"), not("Parameter One Value Two")), param("queryStringParameterTwoName", "Parameter Two") ) ) .respond( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body_response") ); // then // wrong query string parameter name assertEquals( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body_response"), makeRequest( request() .withMethod("POST") .withPath(calculatePath("some_pathRequest")) .withQueryStringParameters( param("OTHERQueryStringParameterOneName", "Parameter One Value One", "Parameter One Value Two"), param("queryStringParameterTwoName", "Parameter Two") ), headersToIgnore) ); // wrong query string parameter value assertEquals( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body_response"), makeRequest( request() .withMethod("POST") .withPath(calculatePath("some_pathRequest")) .withQueryStringParameters( param("queryStringParameterOneName", "OTHER Parameter One Value One", "OTHER Parameter One Value Two"), param("queryStringParameterTwoName", "Parameter Two") ), headersToIgnore) ); } @Test public void shouldReturnResponseByNotMatchingQueryStringParameterWithNotOperatorForName() { // when mockServerClient .when( request() .withMethod("POST") .withPath(calculatePath("some_pathRequest")) .withQueryStringParameters( param(not("queryStringParameterOneName"), string("Parameter One Value One"), string("Parameter One Value Two")), param("queryStringParameterTwoName", "Parameter Two") ) ) .respond( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body_response") ); // then // wrong query string parameter name assertEquals( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body_response"), makeRequest( request() .withMethod("POST") .withPath(calculatePath("some_pathRequest")) .withQueryStringParameters( param("OTHERQueryStringParameterOneName", "Parameter One Value One", "Parameter One Value Two"), param("queryStringParameterTwoName", "Parameter Two") ), headersToIgnore) ); } @Test public void shouldReturnResponseByNotMatchingQueryStringParameterWithNotOperatorForValue() { // when mockServerClient .when( request() .withMethod("POST") .withPath(calculatePath("some_pathRequest")) .withQueryStringParameters( param(string("queryStringParameterOneName"), not("Parameter One Value One"), not("Parameter One Value Two")), param("queryStringParameterTwoName", "Parameter Two") ) ) .respond( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body_response") ); // then // wrong query string parameter value assertEquals( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body_response"), makeRequest( request() .withMethod("POST") .withPath(calculatePath("some_pathRequest")) .withQueryStringParameters( param("queryStringParameterOneName", "OTHER Parameter One Value One", "OTHER Parameter One Value Two"), param("queryStringParameterTwoName", "Parameter Two") ), headersToIgnore) ); } @Test public void shouldReturnResponseByNotMatchingCookieWithNotOperatorForNameAndValue() { // when mockServerClient .when( request() .withMethod("GET") .withPath(calculatePath("some_pathRequest")) .withCookies( cookie(not("requestCookieNameOne"), not("requestCookieValueOne")), cookie("requestCookieNameTwo", "requestCookieValueTwo") ) ) .respond( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body_response") ); // then // wrong query string cookie name assertEquals( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body_response"), makeRequest( request() .withMethod("GET") .withPath(calculatePath("some_pathRequest")) .withCookies( cookie("OTHERrequestCookieNameOne", "requestCookieValueOne"), cookie("requestCookieNameTwo", "requestCookieValueTwo") ), headersToIgnore) ); // wrong query string cookie value assertEquals( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body_response"), makeRequest( request() .withMethod("GET") .withPath(calculatePath("some_pathRequest")) .withCookies( cookie("requestCookieNameOne", "OTHERrequestCookieValueOne"), cookie("requestCookieNameTwo", "requestCookieValueTwo") ), headersToIgnore) ); } @Test public void shouldReturnResponseByNotMatchingCookieWithNotOperatorForName() { // when mockServerClient .when( request() .withMethod("GET") .withPath(calculatePath("some_pathRequest")) .withCookies( cookie(not("requestCookieNameOne"), string("requestCookieValueOne")), cookie("requestCookieNameTwo", "requestCookieValueTwo") ) ) .respond( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body_response") ); // then // wrong query string cookie name assertEquals( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body_response"), makeRequest( request() .withMethod("GET") .withPath(calculatePath("some_pathRequest")) .withCookies( cookie("OTHERrequestCookieNameOne", "requestCookieValueOne"), cookie("requestCookieNameTwo", "requestCookieValueTwo") ), headersToIgnore) ); } @Test public void shouldReturnResponseByNotMatchingCookieWithNotOperatorForValue() { // when mockServerClient .when( request() .withMethod("GET") .withPath(calculatePath("some_pathRequest")) .withCookies( cookie(string("requestCookieNameOne"), not("requestCookieValueOne")), cookie("requestCookieNameTwo", "requestCookieValueTwo") ) ) .respond( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body_response") ); // then // wrong query string cookie value assertEquals( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body_response"), makeRequest( request() .withMethod("GET") .withPath(calculatePath("some_pathRequest")) .withCookies( cookie("requestCookieNameOne", "OTHERrequestCookieValueOne"), cookie("requestCookieNameTwo", "requestCookieValueTwo") ), headersToIgnore) ); } @Test public void shouldReturnResponseByNotMatchingHeaderWithNotOperatorForNameAndValue() { // when mockServerClient .when( request() .withMethod("GET") .withPath(calculatePath("some_pathRequest")) .withHeaders( header(not("requestHeaderNameOne"), not("requestHeaderValueOne")), header("requestHeaderNameTwo", "requestHeaderValueTwo") ) ) .respond( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body_response") ); // then // wrong query string header name assertEquals( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body_response"), makeRequest( request() .withMethod("GET") .withPath(calculatePath("some_pathRequest")) .withHeaders( header("OTHERrequestHeaderNameOne", "requestHeaderValueOne"), header("requestHeaderNameTwo", "requestHeaderValueTwo") ), headersToIgnore) ); // wrong query string header value assertEquals( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body_response"), makeRequest( request() .withMethod("GET") .withPath(calculatePath("some_pathRequest")) .withHeaders( header("requestHeaderNameOne", "OTHERrequestHeaderValueOne"), header("requestHeaderNameTwo", "requestHeaderValueTwo") ), headersToIgnore) ); } @Test public void shouldReturnResponseByNotMatchingHeaderWithNotOperatorForName() { // when mockServerClient .when( request() .withMethod("GET") .withPath(calculatePath("some_pathRequest")) .withHeaders( header(not("requestHeaderNameOne"), string("requestHeaderValueOne")), header("requestHeaderNameTwo", "requestHeaderValueTwo") ) ) .respond( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body_response") ); // then // wrong query string header name assertEquals( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body_response"), makeRequest( request() .withMethod("GET") .withPath(calculatePath("some_pathRequest")) .withHeaders( header("OTHERrequestHeaderNameOne", "requestHeaderValueOne"), header("requestHeaderNameTwo", "requestHeaderValueTwo") ), headersToIgnore) ); } @Test public void shouldReturnResponseByNotMatchingHeaderWithNotOperatorForValue() { // when mockServerClient .when( request() .withMethod("GET") .withPath(calculatePath("some_pathRequest")) .withHeaders( header(string("requestHeaderNameOne"), not("requestHeaderValueOne")), header("requestHeaderNameTwo", "requestHeaderValueTwo") ) ) .respond( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body_response") ); // then // wrong query string header value assertEquals( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body_response"), makeRequest( request() .withMethod("GET") .withPath(calculatePath("some_pathRequest")) .withHeaders( header("requestHeaderNameOne", "OTHERrequestHeaderValueOne"), header("requestHeaderNameTwo", "requestHeaderValueTwo") ), headersToIgnore) ); } @Test public void shouldNotReturnResponseForWhenTimeToLiveExpired() { // when mockServerClient .when( request().withPath(calculatePath("some_path")), exactly(2), TimeToLive.exactly(TimeUnit.SECONDS, 3L) ) .respond( response().withBody("some_body").withDelay(TimeUnit.SECONDS, 3L) ); // then assertEquals( response() .withStatusCode(OK_200.code()) .withBody("some_body"), makeRequest( request() .withPath(calculatePath("some_path")), headersToIgnore) ); // - in http assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()), makeRequest( request() .withPath(calculatePath("some_path")), headersToIgnore) ); // - in https assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()), makeRequest( request() .withSecure(true) .withPath(calculatePath("some_path")), headersToIgnore) ); } @Test public void shouldNotReturnResponseForNonMatchingBody() { // when mockServerClient .when( request() .withMethod("GET") .withPath(calculatePath("some_path")) .withQueryStringParameters( param("queryStringParameterOneName", "queryStringParameterOneValue"), param("queryStringParameterTwoName", "queryStringParameterTwoValue") ) .withBody(exact("some_body")) .withHeaders(header("headerName", "headerValue")) .withCookies(cookie("cookieName", "cookieValue")) ) .respond( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body") .withHeaders(header("headerName", "headerValue")) .withCookies(cookie("cookieName", "cookieValue")) ); // then // - in http assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()), makeRequest( request() .withMethod("GET") .withPath(calculatePath("some_path")) .withQueryStringParameters( param("queryStringParameterOneName", "queryStringParameterOneValue"), param("queryStringParameterTwoName", "queryStringParameterTwoValue") ) .withBody(exact("some_other_body")) .withHeaders(header("headerName", "headerValue")) .withCookies(cookie("cookieName", "cookieValue")), headersToIgnore) ); // - in https assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()), makeRequest( request() .withMethod("GET") .withSecure(true) .withPath(calculatePath("some_path")) .withQueryStringParameters( param("queryStringParameterOneName", "queryStringParameterOneValue"), param("queryStringParameterTwoName", "queryStringParameterTwoValue") ) .withBody(exact("some_other_body")) .withHeaders(header("headerName", "headerValue")) .withCookies(cookie("cookieName", "cookieValue")), headersToIgnore) ); } @Test public void shouldNotReturnResponseForMatchingBodyWithNotOperator() { // when mockServerClient .when( request() .withBody(Not.not(json("{" + NEW_LINE + " \"id\": 1," + NEW_LINE + " \"name\": \"A green door\"," + NEW_LINE + " \"price\": 12.50," + NEW_LINE + " \"tags\": [\"home\", \"green\"]" + NEW_LINE + "}"))), exactly(2) ) .respond( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body") ); // then // - in http assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()), makeRequest( request() .withPath(calculatePath("some_path")) .withMethod("POST") .withBody("{" + NEW_LINE + " \"id\": 1," + NEW_LINE + " \"extra_ignored_field\": \"some value\"," + NEW_LINE + " \"name\": \"A green door\"," + NEW_LINE + " \"price\": 12.50," + NEW_LINE + " \"tags\": [\"home\", \"green\"]" + NEW_LINE + "}"), headersToIgnore) ); // - in https assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()), makeRequest( request() .withSecure(true) .withPath(calculatePath("some_path")) .withMethod("POST") .withBody("{" + NEW_LINE + " \"id\": 1," + NEW_LINE + " \"extra_ignored_array\": [\"one\", \"two\"]," + NEW_LINE + " \"name\": \"A green door\"," + NEW_LINE + " \"price\": 12.50," + NEW_LINE + " \"tags\": [\"home\", \"green\"]" + NEW_LINE + "}"), headersToIgnore) ); } @Test public void shouldNotReturnResponseForNonMatchingXPathBody() { // when mockServerClient.when(request().withBody(new XPathBody("/bookstore/book[price>35]/price")), exactly(2)).respond(response().withBody("some_body")); // then // - in http assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()), makeRequest( request() .withSecure(true) .withPath(calculatePath("some_path")) .withMethod("POST") .withBody(new StringBody("" + "<?xml version=\"1.0\" encoding=\"ISO-8859-1\"?>" + NEW_LINE + "<bookstore>" + NEW_LINE + " <book category=\"COOKING\">" + NEW_LINE + " <title lang=\"en\">Everyday Italian</title>" + NEW_LINE + " <author>Giada De Laurentiis</author>" + NEW_LINE + " <year>2005</year>" + NEW_LINE + " <price>30.00</price>" + NEW_LINE + " </book>" + NEW_LINE + " <book category=\"CHILDREN\">" + NEW_LINE + " <title lang=\"en\">Harry Potter</title>" + NEW_LINE + " <author>J K. Rowling</author>" + NEW_LINE + " <year>2005</year>" + NEW_LINE + " <price>29.99</price>" + NEW_LINE + " </book>" + NEW_LINE + " <book category=\"WEB\">" + NEW_LINE + " <title lang=\"en\">Learning XML</title>" + NEW_LINE + " <author>Erik T. Ray</author>" + NEW_LINE + " <year>2003</year>" + NEW_LINE + " <price>31.95</price>" + NEW_LINE + " </book>" + NEW_LINE + "</bookstore>")), headersToIgnore) ); // - in https assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()), makeRequest( request() .withSecure(true) .withPath(calculatePath("some_path")) .withMethod("POST") .withBody(new StringBody("" + "<?xml version=\"1.0\" encoding=\"ISO-8859-1\"?>" + NEW_LINE + "<bookstore>" + NEW_LINE + " <book category=\"COOKING\">" + NEW_LINE + " <title lang=\"en\">Everyday Italian</title>" + NEW_LINE + " <author>Giada De Laurentiis</author>" + NEW_LINE + " <year>2005</year>" + NEW_LINE + " <price>30.00</price>" + NEW_LINE + " </book>" + NEW_LINE + " <book category=\"CHILDREN\">" + NEW_LINE + " <title lang=\"en\">Harry Potter</title>" + NEW_LINE + " <author>J K. Rowling</author>" + NEW_LINE + " <year>2005</year>" + NEW_LINE + " <price>29.99</price>" + NEW_LINE + " </book>" + NEW_LINE + " <book category=\"WEB\">" + NEW_LINE + " <title lang=\"en\">Learning XML</title>" + NEW_LINE + " <author>Erik T. Ray</author>" + NEW_LINE + " <year>2003</year>" + NEW_LINE + " <price>31.95</price>" + NEW_LINE + " </book>" + NEW_LINE + "</bookstore>")), headersToIgnore) ); } @Test public void shouldNotReturnResponseForNonMatchingXmlBody() { // when mockServerClient.when(request().withBody(xml("" + "<?xml version=\"1.0\" encoding=\"ISO-8859-1\"?>" + NEW_LINE + "<bookstore>" + NEW_LINE + " <book category=\"COOKING\" nationality=\"ITALIAN\">" + NEW_LINE + " <title lang=\"en\">Everyday Italian</title>" + NEW_LINE + " <author>Giada De Laurentiis</author>" + NEW_LINE + " <year>2005</year>" + NEW_LINE + " <price>30.00</price>" + NEW_LINE + " </book>" + NEW_LINE + "</bookstore>")), exactly(2)).respond(response().withBody("some_body")); // then // - in http assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()), makeRequest( request() .withSecure(true) .withPath(calculatePath("some_path")) .withMethod("POST") .withBody(new StringBody("" + "<?xml version=\"1.0\" encoding=\"ISO-8859-1\"?>" + NEW_LINE + "<bookstore>" + NEW_LINE + " <book category=\"COOKING\">" + NEW_LINE + " <title lang=\"en\">Everyday Italian</title>" + NEW_LINE + " <author>Giada De Laurentiis</author>" + NEW_LINE + " <year>2005</year>" + NEW_LINE + " <price>30.00</price>" + NEW_LINE + " </book>" + NEW_LINE + "</bookstore>")), headersToIgnore) ); // - in https assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()), makeRequest( request() .withSecure(true) .withPath(calculatePath("some_path")) .withMethod("POST") .withBody(new StringBody("" + "<?xml version=\"1.0\" encoding=\"ISO-8859-1\"?>" + NEW_LINE + "<bookstore>" + NEW_LINE + " <book category=\"COOKING\">" + NEW_LINE + " <title lang=\"en\">Everyday Italian</title>" + NEW_LINE + " <author>Giada De Laurentiis</author>" + NEW_LINE + " <year>2005</year>" + NEW_LINE + " <price>30.00</price>" + NEW_LINE + " </book>" + NEW_LINE + "</bookstore>")), headersToIgnore) ); } @Test public void shouldNotReturnResponseForNonMatchingJsonBody() { // when mockServerClient.when(request().withBody(json("{" + NEW_LINE + " \"id\": 1," + NEW_LINE + " \"name\": \"A green door\"," + NEW_LINE + " \"price\": 12.50," + NEW_LINE + " \"tags\": [\"home\", \"green\"]" + NEW_LINE + "}")), exactly(2)).respond(response().withBody("some_body")); // then // - in http assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()), makeRequest( request() .withPath(calculatePath("some_path")) .withMethod("POST") .withBody("{" + NEW_LINE + " \"id\": 1," + NEW_LINE + " \"name\": \"---- XXXX WRONG VALUE XXXX ----\"," + NEW_LINE + " \"price\": 12.50," + NEW_LINE + " \"tags\": [\"home\", \"green\"]" + NEW_LINE + "}"), headersToIgnore) ); // - in https assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()), makeRequest( request() .withSecure(true) .withPath(calculatePath("some_path")) .withMethod("POST") .withBody("{" + NEW_LINE + " \"id\": 1," + NEW_LINE + " \"name\": \"---- XXXX WRONG VALUE XXXX ----\"," + NEW_LINE + " \"price\": 12.50," + NEW_LINE + " \"tags\": [\"home\", \"green\"]" + NEW_LINE + "}"), headersToIgnore) ); } @Test public void shouldNotReturnResponseForNonMatchingJsonBodyWithMatchType() { // when mockServerClient .when( request() .withBody(json("{" + NEW_LINE + " \"id\": 1," + NEW_LINE + " \"name\": \"A green door\"," + NEW_LINE + " \"price\": 12.50," + NEW_LINE + " \"tags\": [\"home\", \"green\"]" + NEW_LINE + "}", MatchType.STRICT)), exactly(2)) .respond( response() .withBody("some_body") ); // then // - in http assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()), makeRequest( request() .withPath(calculatePath("some_path")) .withMethod("POST") .withBody("{" + NEW_LINE + " \"id\": 1," + NEW_LINE + " \"extra field\": \"some value\"," + NEW_LINE + " \"name\": \"A green door\"," + NEW_LINE + " \"price\": 12.50," + NEW_LINE + " \"tags\": [\"home\", \"green\"]" + NEW_LINE + "}"), headersToIgnore) ); // - in https assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()), makeRequest( request() .withSecure(true) .withPath(calculatePath("some_path")) .withMethod("POST") .withBody("{" + NEW_LINE + " \"id\": 1," + NEW_LINE + " \"extra field\": \"some value\"," + NEW_LINE + " \"name\": \"A green door\"," + NEW_LINE + " \"price\": 12.50," + NEW_LINE + " \"tags\": [\"home\", \"green\"]" + NEW_LINE + "}"), headersToIgnore) ); } @Test public void shouldNotReturnResponseForNonMatchingJsonSchema() { // when mockServerClient.when(request().withBody(jsonSchema("{" + NEW_LINE + " \"$schema\": \"http://json-schema.org/draft-04/schema#\"," + NEW_LINE + " \"title\": \"Product\"," + NEW_LINE + " \"description\": \"A product from Acme's catalog\"," + NEW_LINE + " \"type\": \"object\"," + NEW_LINE + " \"properties\": {" + NEW_LINE + " \"id\": {" + NEW_LINE + " \"description\": \"The unique identifier for a product\"," + NEW_LINE + " \"type\": \"integer\"" + NEW_LINE + " }," + NEW_LINE + " \"name\": {" + NEW_LINE + " \"description\": \"Name of the product\"," + NEW_LINE + " \"type\": \"string\"" + NEW_LINE + " }," + NEW_LINE + " \"price\": {" + NEW_LINE + " \"type\": \"number\"," + NEW_LINE + " \"minimum\": 0," + NEW_LINE + " \"exclusiveMinimum\": true" + NEW_LINE + " }," + NEW_LINE + " \"tags\": {" + NEW_LINE + " \"type\": \"array\"," + NEW_LINE + " \"items\": {" + NEW_LINE + " \"type\": \"string\"" + NEW_LINE + " }," + NEW_LINE + " \"minItems\": 1," + NEW_LINE + " \"uniqueItems\": true" + NEW_LINE + " }" + NEW_LINE + " }," + NEW_LINE + " \"required\": [\"id\", \"name\", \"price\"]" + NEW_LINE + "}")), exactly(2)).respond(response().withBody("some_body")); // then // - in http assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()), makeRequest( request() .withPath(calculatePath("some_path")) .withMethod("POST") .withBody("{" + NEW_LINE + " \"id\": 1," + NEW_LINE + " \"wrong field name\": \"A green door\"," + NEW_LINE + " \"price\": 12.50," + NEW_LINE + " \"tags\": [\"home\", \"green\"]" + NEW_LINE + "}"), headersToIgnore) ); // - in https assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()), makeRequest( request() .withSecure(true) .withPath(calculatePath("some_path")) .withMethod("POST") .withBody("{" + NEW_LINE + " \"id\": 1," + NEW_LINE + " \"name\": \"A green door\"," + NEW_LINE + " \"wrong field name\": 12.50," + NEW_LINE + " \"tags\": [\"home\", \"green\"]" + NEW_LINE + "}"), headersToIgnore) ); } @Test public void shouldNotReturnResponseForNonMatchingPath() { // when mockServerClient .when( request() .withMethod("GET") .withPath(calculatePath("some_path")) .withQueryStringParameters( param("queryStringParameterOneName", "queryStringParameterOneValue"), param("queryStringParameterTwoName", "queryStringParameterTwoValue") ) .withBody(exact("some_body")) .withHeaders(header("headerName", "headerValue")) .withCookies(cookie("cookieName", "cookieValue")) ) .respond( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body") .withHeaders(header("headerName", "headerValue")) .withCookies(cookie("cookieName", "cookieValue")) ); // then // - in http assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()), makeRequest( request() .withMethod("GET") .withPath(calculatePath("some_other_path")) .withQueryStringParameters( param("queryStringParameterOneName", "queryStringParameterOneValue"), param("queryStringParameterTwoName", "queryStringParameterTwoValue") ) .withBody(exact("some_body")) .withHeaders(header("headerName", "headerValue")) .withCookies(cookie("cookieName", "cookieValue")), headersToIgnore) ); // - in https assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()), makeRequest( request() .withMethod("GET") .withSecure(true) .withPath(calculatePath("some_other_path")) .withQueryStringParameters( param("queryStringParameterOneName", "queryStringParameterOneValue"), param("queryStringParameterTwoName", "queryStringParameterTwoValue") ) .withBody(exact("some_body")) .withHeaders(header("headerName", "headerValue")) .withCookies(cookie("cookieName", "cookieValue")), headersToIgnore) ); } @Test public void shouldNotReturnResponseForMatchingPathWithNotOperator() { // when mockServerClient .when( request() .withPath(not(calculatePath("some_path"))) ) .respond( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body_response") ); // then // - in http assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()), makeRequest( request() .withPath(calculatePath("some_path")), headersToIgnore) ); // - in https assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()), makeRequest( request() .withPath(calculatePath("some_path")), headersToIgnore) ); } @Test public void shouldNotReturnResponseForMatchingMethodWithNotOperator() { // when mockServerClient .when( request() .withMethod(not("GET")) ) .respond( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body_response") ); // then // - in http assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()), makeRequest( request() .withMethod("GET"), headersToIgnore) ); // - in https assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()), makeRequest( request() .withMethod("GET"), headersToIgnore) ); } @Test public void shouldNotReturnResponseForNonMatchingBodyParameterName() { // when mockServerClient .when( request() .withMethod("POST") .withPath(calculatePath("some_pathRequest")) .withBody(params( param("bodyParameterOneName", "Parameter One Value One", "Parameter One Value Two"), param("bodyParameterTwoName", "Parameter Two") )) ) .respond( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body_response") .withHeaders(header("headerNameResponse", "headerValueResponse")) .withCookies(cookie("cookieNameResponse", "cookieValueResponse")) ); // then // wrong query string parameter name assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()), makeRequest( request() .withMethod("POST") .withPath(calculatePath("some_pathRequest")) .withBody(params( param("OTHERBodyParameterOneName", "Parameter One Value One", "Parameter One Value Two"), param("bodyParameterTwoName", "Parameter Two") )) .withHeaders(header("headerNameRequest", "headerValueRequest")) .withCookies(cookie("cookieNameRequest", "cookieValueRequest")), headersToIgnore) ); // wrong query string parameter name assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()), makeRequest( request() .withMethod("POST") .withPath(calculatePath("some_pathRequest")) .withBody(new StringBody("OTHERBodyParameterOneName=Parameter+One+Value+One" + "&bodyParameterOneName=Parameter+One+Value+Two" + "&bodyParameterTwoName=Parameter+Two")) .withHeaders(header("headerNameRequest", "headerValueRequest")) .withCookies(cookie("cookieNameRequest", "cookieValueRequest")), headersToIgnore) ); } @Test public void shouldNotReturnResponseForMatchingBodyParameterWithNotOperator() { // when mockServerClient .when( request() .withMethod("POST") .withPath(calculatePath("some_pathRequest")) .withBody(params( param(not("bodyParameterOneName"), not("Parameter One Value One"), not("Parameter One Value Two")), param("bodyParameterTwoName", "Parameter Two") )) ) .respond( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body_response") ); // then // wrong query string parameter name assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()), makeRequest( request() .withMethod("POST") .withPath(calculatePath("some_pathRequest")) .withBody(params( param("bodyParameterOneName", "Parameter One Value One", "Parameter One Value Two"), param("bodyParameterTwoName", "Parameter Two") )) .withHeaders(header("headerNameRequest", "headerValueRequest")) .withCookies(cookie("cookieNameRequest", "cookieValueRequest")), headersToIgnore) ); // wrong query string parameter name assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()), makeRequest( request() .withMethod("POST") .withPath(calculatePath("some_pathRequest")) .withBody(new StringBody("bodyParameterOneName=Other Parameter+One+Value+One" + "&bodyParameterOneName=Parameter+One+Value+Two" + "&bodyParameterTwoName=Parameter+Two")) .withHeaders(header("headerNameRequest", "headerValueRequest")) .withCookies(cookie("cookieNameRequest", "cookieValueRequest")), headersToIgnore) ); } @Test public void shouldNotReturnResponseForNonMatchingBodyParameterValue() { // when mockServerClient .when( request() .withMethod("POST") .withPath(calculatePath("some_pathRequest")) .withBody(params( param("bodyParameterOneName", "Parameter One Value One", "Parameter One Value Two"), param("bodyParameterTwoName", "Parameter Two") )) ) .respond( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body_response") .withHeaders(header("headerNameResponse", "headerValueResponse")) .withCookies(cookie("cookieNameResponse", "cookieValueResponse")) ); // then // wrong body parameter value assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()), makeRequest( request() .withMethod("POST") .withPath(calculatePath("some_pathRequest")) .withBody(params( param("bodyParameterOneName", "Other Parameter One Value One", "Parameter One Value Two"), param("bodyParameterTwoName", "Parameter Two") )) .withHeaders(header("headerNameRequest", "headerValueRequest")) .withCookies(cookie("cookieNameRequest", "cookieValueRequest")), headersToIgnore) ); // wrong body parameter value assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()), makeRequest( request() .withMethod("POST") .withPath(calculatePath("some_pathRequest")) .withBody(new StringBody("bodyParameterOneName=Other Parameter+One+Value+One" + "&bodyParameterOneName=Parameter+One+Value+Two" + "&bodyParameterTwoName=Parameter+Two")) .withHeaders(header("headerNameRequest", "headerValueRequest")) .withCookies(cookie("cookieNameRequest", "cookieValueRequest")), headersToIgnore) ); } @Test public void shouldNotReturnResponseForNonMatchingQueryStringParameterName() { // when mockServerClient .when( request() .withMethod("POST") .withPath(calculatePath("some_pathRequest")) .withQueryStringParameters( param("queryStringParameterOneName", "queryStringParameterOneValueOne", "queryStringParameterOneValueTwo"), param("queryStringParameterTwoName", "queryStringParameterTwoValue") ) .withBody("some_bodyRequest") ) .respond( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body_response") .withHeaders(header("headerNameResponse", "headerValueResponse")) .withCookies(cookie("cookieNameResponse", "cookieValueResponse")) ); // then // wrong query string parameter name assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()), makeRequest( request() .withMethod("POST") .withPath(calculatePath("some_pathRequest")) .withQueryStringParameters( param("OTHERQueryStringParameterOneName", "queryStringParameterOneValueOne", "queryStringParameterOneValueTwo"), param("queryStringParameterTwoName", "queryStringParameterTwoValue") ) .withBody("some_bodyRequest") .withHeaders( header("headerNameRequest", "headerValueRequest") ) .withCookies(cookie("cookieNameRequest", "cookieValueRequest")), headersToIgnore) ); } @Test public void shouldNotReturnResponseForNonMatchingQueryStringParameterValue() { // when mockServerClient .when( request() .withMethod("POST") .withPath(calculatePath("some_pathRequest")) .withQueryStringParameters( param("queryStringParameterOneName", "queryStringParameterOneValueOne", "queryStringParameterOneValueTwo"), param("queryStringParameterTwoName", "queryStringParameterTwoValue") ) .withBody("some_bodyRequest") ) .respond( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body_response") .withHeaders(header("headerNameResponse", "headerValueResponse")) .withCookies(cookie("cookieNameResponse", "cookieValueResponse")) ); // then // wrong query string parameter value assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()), makeRequest( request() .withMethod("POST") .withPath(calculatePath("some_pathRequest")) .withQueryStringParameters( param("queryStringParameterOneName", "OTHERqueryStringParameterOneValueOne", "queryStringParameterOneValueTwo"), param("queryStringParameterTwoName", "queryStringParameterTwoValue") ) .withBody("some_bodyRequest") .withHeaders(header("headerNameRequest", "headerValueRequest")) .withCookies(cookie("cookieNameRequest", "cookieValueRequest")), headersToIgnore) ); } @Test public void shouldNotReturnResponseForMatchingQueryStringParameterWithNotOperator() { // when mockServerClient .when( request() .withMethod("POST") .withPath(calculatePath("some_pathRequest")) .withQueryStringParameters( param(not("queryStringParameterOneName"), not("Parameter One Value One"), not("Parameter One Value Two")), param("queryStringParameterTwoName", "Parameter Two") ) ) .respond( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body_response") ); // then // wrong query string parameter name assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()), makeRequest( request() .withMethod("POST") .withPath(calculatePath("some_pathRequest")) .withQueryStringParameters( param("queryStringParameterOneName", "Parameter One Value One", "Parameter One Value Two"), param("queryStringParameterTwoName", "Parameter Two") ), headersToIgnore) ); // wrong query string parameter name assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()), makeRequest( request() .withMethod("POST") .withPath(calculatePath("some_pathRequest")) .withQueryStringParameters( param("queryStringParameterOneName", "Parameter One Value One", "Parameter One Value Two"), param("queryStringParameterTwoName", "Parameter Two") ), headersToIgnore) ); } @Test public void shouldNotReturnResponseForNonMatchingCookieName() { // when mockServerClient .when( request() .withMethod("GET") .withPath(calculatePath("some_path")) .withQueryStringParameters( param("queryStringParameterOneName", "queryStringParameterOneValue"), param("queryStringParameterTwoName", "queryStringParameterTwoValue") ) .withBody(exact("some_body")) .withHeaders(header("headerName", "headerValue")) .withCookies(cookie("cookieName", "cookieValue")) ) .respond( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body") .withHeaders(header("headerName", "headerValue")) .withCookies(cookie("cookieName", "cookieValue")) ); // then // - in http assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()), makeRequest( request() .withMethod("GET") .withPath(calculatePath("some_path")) .withQueryStringParameters( param("queryStringParameterOneName", "queryStringParameterOneValue"), param("queryStringParameterTwoName", "queryStringParameterTwoValue") ) .withBody(exact("some_body")) .withHeaders(header("headerName", "headerValue")) .withCookies(cookie("cookieOtherName", "cookieValue")), headersToIgnore) ); // - in https assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()), makeRequest( request() .withMethod("GET") .withSecure(true) .withPath(calculatePath("some_path")) .withQueryStringParameters( param("queryStringParameterOneName", "queryStringParameterOneValue"), param("queryStringParameterTwoName", "queryStringParameterTwoValue") ) .withBody(exact("some_body")) .withHeaders(header("headerName", "headerValue")) .withCookies(cookie("cookieOtherName", "cookieValue")), headersToIgnore) ); } @Test public void shouldNotReturnResponseForNonMatchingCookieValue() { // when mockServerClient .when( request() .withMethod("GET") .withPath(calculatePath("some_path")) .withQueryStringParameters( param("queryStringParameterOneName", "queryStringParameterOneValue"), param("queryStringParameterTwoName", "queryStringParameterTwoValue") ) .withBody(exact("some_body")) .withHeaders(header("headerName", "headerValue")) .withCookies(cookie("cookieName", "cookieValue")) ) .respond( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body") .withHeaders(header("headerName", "headerValue")) .withCookies(cookie("cookieName", "cookieValue")) ); // then // - in http assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()), makeRequest( request() .withMethod("GET") .withPath(calculatePath("some_path")) .withQueryStringParameters( param("queryStringParameterOneName", "queryStringParameterOneValue"), param("queryStringParameterTwoName", "queryStringParameterTwoValue") ) .withBody(exact("some_body")) .withHeaders(header("headerName", "headerValue")) .withCookies(cookie("cookieName", "cookieOtherValue")), headersToIgnore) ); // - in https assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()), makeRequest( request() .withMethod("GET") .withSecure(true) .withPath(calculatePath("some_path")) .withQueryStringParameters( param("queryStringParameterOneName", "queryStringParameterOneValue"), param("queryStringParameterTwoName", "queryStringParameterTwoValue") ) .withBody(exact("some_body")) .withHeaders(header("headerName", "headerValue")) .withCookies(cookie("cookieName", "cookieOtherValue")), headersToIgnore) ); } @Test public void shouldNotReturnResponseForMatchingCookieWithNotOperator() { // when mockServerClient .when( request() .withMethod("GET") .withPath(calculatePath("some_pathRequest")) .withCookies( cookie(not("requestCookieNameOne"), not("requestCookieValueOne")), cookie("requestCookieNameTwo", "requestCookieValueTwo") ) ) .respond( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body_response") ); // then // wrong query string parameter name assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()), makeRequest( request() .withMethod("GET") .withPath(calculatePath("some_pathRequest")) .withCookies( cookie("requestCookieNameOne", "requestCookieValueOne"), cookie("requestCookieNameTwo", "requestCookieValueTwo") ), headersToIgnore) ); // wrong query string parameter name assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()), makeRequest( request() .withMethod("GET") .withPath(calculatePath("some_pathRequest")) .withCookies( cookie("requestCookieNameOne", "requestCookieValueOne"), cookie("requestCookieNameTwo", "requestCookieValueTwo") ), headersToIgnore) ); } @Test public void shouldNotReturnResponseForNonMatchingHeaderName() { // when mockServerClient .when( request() .withMethod("GET") .withPath(calculatePath("some_path")) .withQueryStringParameters( param("queryStringParameterOneName", "queryStringParameterOneValue"), param("queryStringParameterTwoName", "queryStringParameterTwoValue") ) .withBody(exact("some_body")) .withHeaders(header("headerName", "headerValue")) .withCookies(cookie("cookieName", "cookieValue")) ) .respond( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body") .withHeaders(header("headerName", "headerValue")) .withCookies(cookie("cookieName", "cookieValue")) ); // then // - in http assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()), makeRequest( request() .withMethod("GET") .withPath(calculatePath("some_path")) .withQueryStringParameters( param("queryStringParameterOneName", "queryStringParameterOneValue"), param("queryStringParameterTwoName", "queryStringParameterTwoValue") ) .withBody(exact("some_body")) .withHeaders(header("headerOtherName", "headerValue")) .withCookies(cookie("cookieName", "cookieValue")), headersToIgnore) ); // - in https assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()), makeRequest( request() .withMethod("GET") .withSecure(true) .withPath(calculatePath("some_path")) .withQueryStringParameters( param("queryStringParameterOneName", "queryStringParameterOneValue"), param("queryStringParameterTwoName", "queryStringParameterTwoValue") ) .withBody(exact("some_body")) .withHeaders(header("headerOtherName", "headerValue")) .withCookies(cookie("cookieName", "cookieValue")), headersToIgnore) ); } @Test public void shouldNotReturnResponseForNonMatchingHeaderValue() { // when mockServerClient .when( request() .withMethod("GET") .withPath(calculatePath("some_path")) .withQueryStringParameters( param("queryStringParameterOneName", "queryStringParameterOneValue"), param("queryStringParameterTwoName", "queryStringParameterTwoValue") ) .withBody(exact("some_body")) .withHeaders(header("headerName", "headerValue")) .withCookies(cookie("cookieName", "cookieValue")) ) .respond( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body") .withHeaders(header("headerName", "headerValue")) .withCookies(cookie("cookieName", "cookieValue")) ); // then // - in http assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()), makeRequest( request() .withMethod("GET") .withPath(calculatePath("some_path")) .withQueryStringParameters( param("queryStringParameterOneName", "queryStringParameterOneValue"), param("queryStringParameterTwoName", "queryStringParameterTwoValue") ) .withBody(exact("some_body")) .withHeaders(header("headerName", "headerOtherValue")) .withCookies(cookie("cookieName", "cookieValue")), headersToIgnore) ); // - in https assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()), makeRequest( request() .withMethod("GET") .withSecure(true) .withPath(calculatePath("some_path")) .withQueryStringParameters( param("queryStringParameterOneName", "queryStringParameterOneValue"), param("queryStringParameterTwoName", "queryStringParameterTwoValue") ) .withBody(exact("some_body")) .withHeaders(header("headerName", "headerOtherValue")) .withCookies(cookie("cookieName", "cookieValue")), headersToIgnore) ); } @Test public void shouldNotReturnResponseForMatchingHeaderWithNotOperator() { // when mockServerClient .when( request() .withMethod("GET") .withPath(calculatePath("some_pathRequest")) .withHeaders( header(not("requestHeaderNameOne"), not("requestHeaderValueOne")), header("requestHeaderNameTwo", "requestHeaderValueTwo") ) ) .respond( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body_response") ); // then // wrong query string parameter name assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()), makeRequest( request() .withMethod("GET") .withPath(calculatePath("some_pathRequest")) .withHeaders( header("requestHeaderNameOne", "requestHeaderValueOne"), header("requestHeaderNameTwo", "requestHeaderValueTwo") ), headersToIgnore) ); // wrong query string parameter name assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()), makeRequest( request() .withMethod("GET") .withPath(calculatePath("some_pathRequest")) .withHeaders( header("requestHeaderNameOne", "requestHeaderValueOne"), header("requestHeaderNameTwo", "requestHeaderValueTwo") ), headersToIgnore) ); } @Test public void shouldVerifyReceivedRequests() { // when mockServerClient .when( request() .withPath(calculatePath("some_path")), exactly(2) ) .respond( response() .withBody("some_body") ); // then // - in http assertEquals( response() .withStatusCode(OK_200.code()) .withBody("some_body"), makeRequest( request() .withPath(calculatePath("some_path")), headersToIgnore) ); mockServerClient.verify(request() .withPath(calculatePath("some_path"))); mockServerClient.verify(request() .withPath(calculatePath("some_path")), VerificationTimes.exactly(1)); // - in https assertEquals( response() .withStatusCode(OK_200.code()) .withBody("some_body"), makeRequest( request() .withSecure(true) .withPath(calculatePath("some_path")), headersToIgnore) ); mockServerClient.verify(request().withPath(calculatePath("some_path")), VerificationTimes.atLeast(1)); mockServerClient.verify(request().withPath(calculatePath("some_path")), VerificationTimes.exactly(2)); } @Test public void shouldVerifyReceivedRequestInSsl() { // when mockServerClient .when( request() .withPath(calculatePath("some.*path")), exactly(2) ) .respond( response() .withBody("some_body") ); // then // - in http assertEquals( response() .withStatusCode(OK_200.code()) .withBody("some_body"), makeRequest( request() .withPath(calculatePath("some_path")), headersToIgnore) ); mockServerClient.verify(request() .withPath(calculatePath("some_path")) .withSecure(false)); mockServerClient.verify(request() .withPath(calculatePath("some_path")) .withSecure(false), VerificationTimes.exactly(1)); // - in https assertEquals( response() .withStatusCode(OK_200.code()) .withBody("some_body"), makeRequest( request() .withPath(calculatePath("some_secure_path")) .withSecure(true), headersToIgnore) ); mockServerClient.verify(request() .withPath(calculatePath("some_secure_path")) .withSecure(true)); mockServerClient.verify(request() .withPath(calculatePath("some_secure_path")) .withSecure(true), VerificationTimes.exactly(1)); } @Test public void shouldVerifyReceivedRequestsWithRegexBody() { // when mockServerClient .when( request() .withMethod("POST") .withPath(calculatePath("some_path")) .withBody("{type: 'some_random_type', value: 'some_random_value'}"), exactly(2) ) .respond( response() .withBody("some_response") ); // then // - in http assertEquals( response() .withStatusCode(OK_200.code()) .withBody("some_response"), makeRequest( request() .withMethod("POST") .withPath(calculatePath("some_path")) .withBody("{type: 'some_random_type', value: 'some_random_value'}"), headersToIgnore) ); mockServerClient.verify( request() .withBody(regex("\\{type\\: \\'some_random_type\\'\\, value\\: \\'some_random_value\\'\\}")) ); mockServerClient.verify( request() .withBody(regex("\\{type\\: \\'some_random_type\\'\\, value\\: \\'some_random_value\\'\\}")), VerificationTimes.exactly(1) ); // - in https assertEquals( response() .withStatusCode(OK_200.code()) .withBody("some_response"), makeRequest( request() .withSecure(true) .withMethod("POST") .withPath(calculatePath("some_path")) .withBody("{type: 'some_random_type', value: 'some_random_value'}"), headersToIgnore) ); mockServerClient.verify( request() .withSecure(true) .withBody(regex("\\{type\\: \\'some_random_type\\'\\, value\\: \\'some_random_value\\'\\}")) ); mockServerClient.verify( request() .withSecure(true) .withBody(regex("\\{type\\: \\'some_random_type\\'\\, value\\: \\'some_random_value\\'\\}")), VerificationTimes.atLeast(1) ); } @Test public void shouldVerifyReceivedRequestsWithNoBody() { // when mockServerClient.when(request().withPath(calculatePath("some_path")), exactly(2)).respond(response()); // then // - in http assertEquals( response() .withStatusCode(OK_200.code()), makeRequest( request() .withPath(calculatePath("some_path")), headersToIgnore) ); mockServerClient.verify(request() .withPath(calculatePath("some_path"))); mockServerClient.verify(request() .withPath(calculatePath("some_path")), VerificationTimes.exactly(1)); } @Test public void shouldVerifyNotEnoughRequestsReceived() { // when mockServerClient.when(request().withPath(calculatePath("some_path")), exactly(2)).respond(response().withBody("some_body")); // then assertEquals( response() .withStatusCode(OK_200.code()) .withBody("some_body"), makeRequest( request() .withPath(calculatePath("some_path")), headersToIgnore) ); try { mockServerClient.verify(request() .withPath(calculatePath("some_path")), VerificationTimes.atLeast(2)); fail(); } catch (AssertionError ae) { assertThat(ae.getMessage(), startsWith("Request not found at least 2 times, expected:<{" + NEW_LINE + " \"path\" : \"" + calculatePath("some_path") + "\"" + NEW_LINE + "}> but was:<{" + NEW_LINE + " \"method\" : \"GET\"," + NEW_LINE + " \"path\" : \"" + calculatePath("some_path") + "\"," + NEW_LINE)); } } @Test public void shouldVerifyTooManyRequestsReceived() { // when mockServerClient.when(request().withPath(calculatePath("some_path")), exactly(2)).respond(response().withBody("some_body")); // then assertEquals( response() .withStatusCode(OK_200.code()) .withBody("some_body"), makeRequest( request() .withPath(calculatePath("some_path")), headersToIgnore) ); try { mockServerClient.verify(request() .withPath(calculatePath("some_path")), VerificationTimes.exactly(0)); fail(); } catch (AssertionError ae) { assertThat(ae.getMessage(), startsWith("Request not found exactly 0 times, expected:<{" + NEW_LINE + " \"path\" : \"" + calculatePath("some_path") + "\"" + NEW_LINE + "}> but was:<{" + NEW_LINE + " \"method\" : \"GET\"," + NEW_LINE + " \"path\" : \"" + calculatePath("some_path") + "\"," + NEW_LINE)); } } @Test public void shouldVerifyNoMatchingRequestsReceived() { // when mockServerClient.when(request().withPath(calculatePath("some_path")), exactly(2)).respond(response().withBody("some_body")); // then assertEquals( response() .withStatusCode(OK_200.code()) .withBody("some_body"), makeRequest( request() .withPath(calculatePath("some_path")), headersToIgnore) ); try { mockServerClient.verify(request() .withPath(calculatePath("some_other_path")), VerificationTimes.exactly(2)); fail(); } catch (AssertionError ae) { assertThat(ae.getMessage(), startsWith("Request not found exactly 2 times, expected:<{" + NEW_LINE + " \"path\" : \"" + calculatePath("some_other_path") + "\"" + NEW_LINE + "}> but was:<{" + NEW_LINE + " \"method\" : \"GET\"," + NEW_LINE + " \"path\" : \"" + calculatePath("some_path") + "\"," + NEW_LINE)); } } @Test public void shouldVerifyNoRequestsReceived() { // when mockServerClient.reset(); // then mockServerClient.verifyZeroInteractions(); } @Test public void shouldNotVerifyNoRequestsReceived() { // when mockServerClient.when(request().withPath(calculatePath("some_path")), exactly(2)).respond(response().withBody("some_body")); // then assertEquals( response() .withStatusCode(OK_200.code()) .withBody("some_body"), makeRequest( request() .withPath(calculatePath("some_path")), headersToIgnore) ); try { mockServerClient.verifyZeroInteractions(); fail(); } catch (AssertionError ae) { assertThat(ae.getMessage(), startsWith("Request not found exactly 0 times, expected:<{ }> but was:<{" + NEW_LINE + " \"method\" : \"GET\"," + NEW_LINE + " \"path\" : \"" + calculatePath("some_path") + "\"," + NEW_LINE)); } } @Test public void shouldVerifyNoMatchingRequestsReceivedInSsl() { // when mockServerClient.when(request().withPath(calculatePath("some.*path")), exactly(2)).respond(response().withBody("some_body")); // then // - in http assertEquals( response() .withStatusCode(OK_200.code()) .withBody("some_body"), makeRequest( request() .withPath(calculatePath("some_path")), headersToIgnore) ); try { mockServerClient.verify( request() .withPath(calculatePath("some_path")) .withSecure(true), VerificationTimes.atLeast(1) ); fail(); } catch (AssertionError ae) { assertThat(ae.getMessage(), startsWith("Request not found at least once, expected:<{" + NEW_LINE + " \"path\" : \"" + calculatePath("some_path") + "\"," + NEW_LINE + " \"secure\" : true" + NEW_LINE + "}> but was:<{" + NEW_LINE + " \"method\" : \"GET\"," + NEW_LINE + " \"path\" : \"" + calculatePath("some_path") + "\"," + NEW_LINE)); } // - in https assertEquals( response() .withStatusCode(OK_200.code()) .withBody("some_body"), makeRequest( request() .withPath(calculatePath("some_secure_path")) .withSecure(true), headersToIgnore) ); try { mockServerClient.verify( request() .withPath(calculatePath("some_secure_path")) .withSecure(false), VerificationTimes.atLeast(1) ); fail(); } catch (AssertionError ae) { assertThat(ae.getMessage(), startsWith("Request not found at least once, expected:<{" + NEW_LINE + " \"path\" : \"" + calculatePath("some_secure_path") + "\"," + NEW_LINE + " \"secure\" : false" + NEW_LINE + "}> but was:<[ {" + NEW_LINE + " \"method\" : \"GET\"," + NEW_LINE + " \"path\" : \"" + calculatePath("some_path") + "\"," + NEW_LINE)); } } @Test public void shouldVerifySequenceOfRequestsReceived() { // when mockServerClient.when(request().withPath(calculatePath("some_path.*")), exactly(6)).respond(response().withBody("some_body")); // then assertEquals( response("some_body"), makeRequest( request().withPath(calculatePath("some_path_one")), headersToIgnore) ); assertEquals( response("some_body"), makeRequest( request().withPath(calculatePath("some_path_two")), headersToIgnore) ); assertEquals( response("some_body"), makeRequest( request().withPath(calculatePath("some_path_three")), headersToIgnore) ); mockServerClient.verify(request(calculatePath("some_path_one")), request(calculatePath("some_path_three"))); mockServerClient.verify(request(calculatePath("some_path_one")), request(calculatePath("some_path_two"))); mockServerClient.verify(request(calculatePath("some_path_one")), request(calculatePath("some_path_two")), request(calculatePath("some_path_three"))); } @Test public void shouldVerifySequenceOfRequestsReceivedIncludingThoseNotMatchingAnException() { // when mockServerClient.when(request().withPath(calculatePath("some_path.*")), exactly(4)).respond(response().withBody("some_body")); // then assertEquals( response("some_body"), makeRequest( request().withPath(calculatePath("some_path_one")), headersToIgnore) ); assertEquals( notFoundResponse(), makeRequest( request().withPath(calculatePath("not_found")), headersToIgnore) ); assertEquals( response("some_body"), makeRequest( request().withPath(calculatePath("some_path_three")), headersToIgnore) ); mockServerClient.verify(request(calculatePath("some_path_one")), request(calculatePath("some_path_three"))); mockServerClient.verify(request(calculatePath("some_path_one")), request(calculatePath("not_found"))); mockServerClient.verify(request(calculatePath("some_path_one")), request(calculatePath("not_found")), request(calculatePath("some_path_three"))); mockServerClient.verify(request(calculatePath("some_path_one")), request(calculatePath("not_found")), request(calculatePath("some_path_three"))); } @Test public void shouldRetrieveSequenceOfRequestsReceivedIncludingThoseNotMatchingAnException() { // when mockServerClient.when(request().withPath(calculatePath("some_path.*")), exactly(4)).respond(response().withBody("some_body")); assertEquals( response("some_body"), makeRequest( request().withPath(calculatePath("some_path_one")), headersToIgnore) ); assertEquals( notFoundResponse(), makeRequest( request().withPath(calculatePath("not_found")), headersToIgnore) ); assertEquals( response("some_body"), makeRequest( request().withPath(calculatePath("some_path_three")), headersToIgnore) ); // then verifyRequestMatches( mockServerClient.retrieveRecordedRequests(request().withPath(calculatePath("some_path.*"))), request(calculatePath("some_path_one")), request(calculatePath("some_path_three")) ); verifyRequestMatches( mockServerClient.retrieveRecordedRequests(request()), request(calculatePath("some_path_one")), request(calculatePath("not_found")), request(calculatePath("some_path_three")) ); verifyRequestMatches( mockServerClient.retrieveRecordedRequests(null), request(calculatePath("some_path_one")), request(calculatePath("not_found")), request(calculatePath("some_path_three")) ); } @Test public void shouldRetrieveSequenceOfExpectationsSetup() { // when mockServerClient.when(request().withPath(calculatePath("some_path.*")), exactly(4)) .respond(response().withBody("some_body")); mockServerClient.when(request().withPath(calculatePath("some_path.*"))) .respond(response().withBody("some_body")); mockServerClient.when(request().withPath(calculatePath("some_other_path"))) .respond(response().withBody("some_other_body")); mockServerClient.when(request().withPath(calculatePath("some_forward_path"))) .forward(forward()); // then assertThat( mockServerClient.retrieveExistingExpectations(request().withPath(calculatePath("some_path.*"))), arrayContaining( new Expectation(request().withPath(calculatePath("some_path.*")), exactly(4), TimeToLive.unlimited()) .thenRespond(response().withBody("some_body")), expectation(request().withPath(calculatePath("some_path.*"))) .thenRespond(response().withBody("some_body")) ) ); assertThat( mockServerClient.retrieveExistingExpectations(null), arrayContaining( new Expectation(request().withPath(calculatePath("some_path.*")), exactly(4), TimeToLive.unlimited()) .thenRespond(response().withBody("some_body")), expectation(request().withPath(calculatePath("some_path.*"))) .thenRespond(response().withBody("some_body")), expectation(request().withPath(calculatePath("some_other_path"))) .thenRespond(response().withBody("some_other_body")), expectation(request().withPath(calculatePath("some_forward_path"))) .thenForward(forward()) ) ); assertThat( mockServerClient.retrieveExistingExpectations(request()), arrayContaining( new Expectation(request().withPath(calculatePath("some_path.*")), exactly(4), TimeToLive.unlimited()) .thenRespond(response().withBody("some_body")), expectation(request().withPath(calculatePath("some_path.*"))) .thenRespond(response().withBody("some_body")), expectation(request().withPath(calculatePath("some_other_path"))) .thenRespond(response().withBody("some_other_body")), expectation(request().withPath(calculatePath("some_forward_path"))) .thenForward(forward()) ) ); } @Test public void shouldVerifySequenceOfRequestsNotReceived() { // when mockServerClient.when(request().withPath(calculatePath("some_path.*")), exactly(6)).respond(response().withBody("some_body")); // then assertEquals( response("some_body"), makeRequest( request().withPath(calculatePath("some_path_one")), headersToIgnore) ); assertEquals( response("some_body"), makeRequest( request().withPath(calculatePath("some_path_two")), headersToIgnore) ); assertEquals( response("some_body"), makeRequest( request().withPath(calculatePath("some_path_three")), headersToIgnore) ); try { mockServerClient.verify(request(calculatePath("some_path_two")), request(calculatePath("some_path_one"))); fail(); } catch (AssertionError ae) { assertThat(ae.getMessage(), startsWith("Request sequence not found, expected:<[ {" + NEW_LINE + " \"path\" : \"" + calculatePath("some_path_two") + "\"" + NEW_LINE + "}, {" + NEW_LINE + " \"path\" : \"" + calculatePath("some_path_one") + "\"" + NEW_LINE + "} ]> but was:<[ {" + NEW_LINE + " \"method\" : \"GET\"," + NEW_LINE + " \"path\" : \"" + calculatePath("some_path_one") + "\"," + NEW_LINE)); } try { mockServerClient.verify(request(calculatePath("some_path_three")), request(calculatePath("some_path_two"))); fail(); } catch (AssertionError ae) { assertThat(ae.getMessage(), startsWith("Request sequence not found, expected:<[ {" + NEW_LINE + " \"path\" : \"" + calculatePath("some_path_three") + "\"" + NEW_LINE + "}, {" + NEW_LINE + " \"path\" : \"" + calculatePath("some_path_two") + "\"" + NEW_LINE + "} ]> but was:<[ {" + NEW_LINE + " \"method\" : \"GET\"," + NEW_LINE + " \"path\" : \"" + calculatePath("some_path_one") + "\"," + NEW_LINE)); } try { mockServerClient.verify(request(calculatePath("some_path_four"))); fail(); } catch (AssertionError ae) { assertThat(ae.getMessage(), startsWith("Request sequence not found, expected:<[ {" + NEW_LINE + " \"path\" : \"" + calculatePath("some_path_four") + "\"" + NEW_LINE + "} ]> but was:<[ {" + NEW_LINE + " \"method\" : \"GET\"," + NEW_LINE + " \"path\" : \"" + calculatePath("some_path_one") + "\"," + NEW_LINE)); } } @Test public void shouldClearExpectationsAndLogs() { // given - some expectations mockServerClient .when( request() .withPath(calculatePath("some_path1")) ) .respond( response() .withBody("some_body1") ); mockServerClient .when( request() .withPath(calculatePath("some_path2")) ) .respond( response() .withBody("some_body2") ); // and - some matching requests assertEquals( response() .withStatusCode(OK_200.code()) .withBody("some_body1"), makeRequest( request() .withPath(calculatePath("some_path1")), headersToIgnore) ); assertEquals( response() .withStatusCode(OK_200.code()) .withBody("some_body2"), makeRequest( request() .withPath(calculatePath("some_path2")), headersToIgnore) ); // when mockServerClient .clear( request() .withPath(calculatePath("some_path1")) ); // then - expectations cleared assertThat( mockServerClient.retrieveExistingExpectations(null), arrayContaining( expectation( request() .withPath(calculatePath("some_path2")) ) .thenRespond( response() .withBody("some_body2") ) ) ); // and then - request log cleared verifyRequestMatches( mockServerClient.retrieveRecordedRequests(null), request(calculatePath("some_path2")) ); // and then - remaining expectations not cleared assertEquals( response() .withStatusCode(OK_200.code()) .withBody("some_body2"), makeRequest( request() .withPath(calculatePath("some_path2")), headersToIgnore) ); assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()), makeRequest( request() .withPath(calculatePath("some_path1")), headersToIgnore) ); } @Test public void shouldClearExpectationsOnly() { // given - some expectations mockServerClient .when( request() .withPath(calculatePath("some_path1")) ) .respond( response() .withBody("some_body1") ); mockServerClient .when( request() .withPath(calculatePath("some_path2")) ) .respond( response() .withBody("some_body2") ); // and - some matching requests assertEquals( response() .withStatusCode(OK_200.code()) .withBody("some_body1"), makeRequest( request() .withPath(calculatePath("some_path1")), headersToIgnore) ); assertEquals( response() .withStatusCode(OK_200.code()) .withBody("some_body2"), makeRequest( request() .withPath(calculatePath("some_path2")), headersToIgnore) ); // when mockServerClient .clear( request() .withPath(calculatePath("some_path1")), MockServerClient.TYPE.EXPECTATION ); // then - expectations cleared assertThat( mockServerClient.retrieveExistingExpectations(null), arrayContaining( expectation( request() .withPath(calculatePath("some_path2")) ) .thenRespond( response() .withBody("some_body2") ) ) ); // and then - request log not cleared verifyRequestMatches( mockServerClient.retrieveRecordedRequests(null), request(calculatePath("some_path1")), request(calculatePath("some_path2")) ); } @Test public void shouldClearLogsOnly() { // given - some expectations mockServerClient .when( request() .withPath(calculatePath("some_path1")) ) .respond( response() .withBody("some_body1") ); mockServerClient .when( request() .withPath(calculatePath("some_path2")) ) .respond( response() .withBody("some_body2") ); // and - some matching requests assertEquals( response() .withStatusCode(OK_200.code()) .withBody("some_body1"), makeRequest( request() .withPath(calculatePath("some_path1")), headersToIgnore) ); assertEquals( response() .withStatusCode(OK_200.code()) .withBody("some_body2"), makeRequest( request() .withPath(calculatePath("some_path2")), headersToIgnore) ); // when mockServerClient .clear( request() .withPath(calculatePath("some_path1")), MockServerClient.TYPE.LOG ); // then - expectations cleared assertThat( mockServerClient.retrieveExistingExpectations(null), arrayContaining( expectation( request() .withPath(calculatePath("some_path1")) ) .thenRespond( response() .withBody("some_body1") ), expectation( request() .withPath(calculatePath("some_path2")) ) .thenRespond( response() .withBody("some_body2") ) ) ); // and then - request log cleared verifyRequestMatches( mockServerClient.retrieveRecordedRequests(null), request(calculatePath("some_path2")) ); } @Test public void shouldClearAllExpectationsWithNull() { // given mockServerClient .when( request() .withPath(calculatePath("some_path1")) ) .respond( response() .withBody("some_body1") ); mockServerClient .when( request() .withPath(calculatePath("some_path2")) ) .respond( response() .withBody("some_body2") ); assertEquals( response() .withStatusCode(OK_200.code()) .withBody("some_body2"), makeRequest( request() .withPath(calculatePath("some_path2")), headersToIgnore) ); // when mockServerClient.clear(null); // then assertThat(mockServerClient.retrieveExistingExpectations(null), emptyArray()); assertThat(mockServerClient.retrieveRecordedRequests(null), emptyArray()); } @Test public void shouldClearAllExpectationsWithEmptyRequest() { // given mockServerClient .when( request() .withPath(calculatePath("some_path1")) ) .respond( response() .withBody("some_body1") ); mockServerClient .when( request() .withPath(calculatePath("some_path2")) ) .respond( response() .withBody("some_body2") ); assertEquals( response() .withStatusCode(OK_200.code()) .withBody("some_body2"), makeRequest( request() .withPath(calculatePath("some_path2")), headersToIgnore) ); // when mockServerClient.clear(request()); // then assertThat(mockServerClient.retrieveExistingExpectations(null), emptyArray()); assertThat(mockServerClient.retrieveRecordedRequests(null), emptyArray()); } @Test public void shouldClearExpectationsWithXPathBody() { // given mockServerClient .when( request() .withBody(xpath("/bookstore/book[year=2005]/price")) ) .respond( response() .withBody("some_body1") ); mockServerClient .when( request() .withBody(xpath("/bookstore/book[year=2006]/price")) ) .respond( response() .withBody("some_body2") ); // and StringBody xmlBody = new StringBody("" + "<?xml version=\"1.0\" encoding=\"ISO-8859-1\"?>" + NEW_LINE + "<bookstore>" + NEW_LINE + " <book category=\"COOKING\">" + NEW_LINE + " <title lang=\"en\">Everyday Italian</title>" + NEW_LINE + " <author>Giada De Laurentiis</author>" + NEW_LINE + " <year>2005</year>" + NEW_LINE + " <price>30.00</price>" + NEW_LINE + " </book>" + NEW_LINE + " <book category=\"CHILDREN\">" + NEW_LINE + " <title lang=\"en\">Harry Potter</title>" + NEW_LINE + " <author>J K. Rowling</author>" + NEW_LINE + " <year>2006</year>" + NEW_LINE + " <price>29.99</price>" + NEW_LINE + " </book>" + NEW_LINE + " <book category=\"WEB\">" + NEW_LINE + " <title lang=\"en\">Learning XML</title>" + NEW_LINE + " <author>Erik T. Ray</author>" + NEW_LINE + " <year>2003</year>" + NEW_LINE + " <price>31.95</price>" + NEW_LINE + " </book>" + NEW_LINE + "</bookstore>"); // then assertEquals( response() .withStatusCode(OK_200.code()) .withBody("some_body1"), makeRequest( request() .withBody(xmlBody), headersToIgnore) ); // when mockServerClient .clear( request() .withBody(xpath("/bookstore/book[year=2005]/price")) ); // then assertThat( mockServerClient.retrieveExistingExpectations(null), arrayContaining( expectation( request() .withBody(xpath("/bookstore/book[year=2006]/price")) ) .thenRespond( response() .withBody("some_body2") ) ) ); // - in http assertEquals( response() .withStatusCode(OK_200.code()) .withBody("some_body2"), makeRequest( request() .withBody(xmlBody), headersToIgnore) ); // - in https assertEquals( response() .withStatusCode(OK_200.code()) .withBody("some_body2"), makeRequest( request() .withSecure(true) .withBody(xmlBody), headersToIgnore) ); } @Test public void shouldClearExpectationsWithJsonSchemaBody() { // given JsonSchemaBody jsonSchemaBodyOne = jsonSchema("{" + NEW_LINE + " \"$schema\": \"http://json-schema.org/draft-04/schema#\"," + NEW_LINE + " \"title\": \"Product\"," + NEW_LINE + " \"description\": \"A product from Acme's catalog\"," + NEW_LINE + " \"type\": \"object\"," + NEW_LINE + " \"properties\": {" + NEW_LINE + " \"id\": {" + NEW_LINE + " \"description\": \"The unique identifier for a product\"," + NEW_LINE + " \"type\": \"integer\"" + NEW_LINE + " }," + NEW_LINE + " \"name\": {" + NEW_LINE + " \"description\": \"Name of the product\"," + NEW_LINE + " \"type\": \"string\"" + NEW_LINE + " }," + NEW_LINE + " \"price\": {" + NEW_LINE + " \"type\": \"number\"," + NEW_LINE + " \"minimum\": 0," + NEW_LINE + " \"exclusiveMinimum\": true" + NEW_LINE + " }," + NEW_LINE + " \"tags\": {" + NEW_LINE + " \"type\": \"array\"," + NEW_LINE + " \"items\": {" + NEW_LINE + " \"type\": \"string\"" + NEW_LINE + " }," + NEW_LINE + " \"minItems\": 1," + NEW_LINE + " \"uniqueItems\": true" + NEW_LINE + " }" + NEW_LINE + " }," + NEW_LINE + " \"required\": [\"id\", \"name\", \"price\"]" + NEW_LINE + "}"); JsonSchemaBody jsonSchemaBodyTwo = jsonSchema("{" + NEW_LINE + " \"$schema\": \"http://json-schema.org/draft-04/schema#\"," + NEW_LINE + " \"title\": \"Product\"," + NEW_LINE + " \"description\": \"A product from Acme's catalog\"," + NEW_LINE + " \"type\": \"object\"," + NEW_LINE + " \"properties\": {" + NEW_LINE + " \"id\": {" + NEW_LINE + " \"description\": \"The unique identifier for a product\"," + NEW_LINE + " \"type\": \"integer\"" + NEW_LINE + " }," + NEW_LINE + " \"name\": {" + NEW_LINE + " \"description\": \"Name of the product\"," + NEW_LINE + " \"type\": \"string\"" + NEW_LINE + " }," + NEW_LINE + " \"price\": {" + NEW_LINE + " \"type\": \"number\"," + NEW_LINE + " \"minimum\": 10," + NEW_LINE + " \"exclusiveMinimum\": true" + NEW_LINE + " }," + NEW_LINE + " \"tags\": {" + NEW_LINE + " \"type\": \"array\"," + NEW_LINE + " \"items\": {" + NEW_LINE + " \"type\": \"string\"" + NEW_LINE + " }," + NEW_LINE + " \"minItems\": 1," + NEW_LINE + " \"uniqueItems\": true" + NEW_LINE + " }" + NEW_LINE + " }," + NEW_LINE + " \"required\": [\"id\", \"name\", \"price\"]" + NEW_LINE + "}"); mockServerClient .when( request() .withBody(jsonSchemaBodyOne) ) .respond( response() .withBody("some_body1") ); mockServerClient .when( request() .withBody(jsonSchemaBodyTwo) ) .respond( response() .withBody("some_body2") ); // then assertEquals( response() .withStatusCode(OK_200.code()) .withBody("some_body1"), makeRequest( request() .withBody("{" + NEW_LINE + " \"id\": 1," + NEW_LINE + " \"name\": \"A green door\"," + NEW_LINE + " \"price\": 12.50," + NEW_LINE + " \"tags\": [\"home\", \"green\"]" + NEW_LINE + "}"), headersToIgnore) ); // when mockServerClient .clear( request() .withBody(jsonSchemaBodyOne) ); // then assertThat( mockServerClient.retrieveExistingExpectations(null), arrayContaining( expectation( request() .withBody(jsonSchemaBodyTwo) ) .thenRespond( response() .withBody("some_body2") ) ) ); // - in http assertEquals( response() .withStatusCode(OK_200.code()) .withBody("some_body2"), makeRequest( request() .withBody("{" + NEW_LINE + " \"id\": 1," + NEW_LINE + " \"name\": \"A green door\"," + NEW_LINE + " \"price\": 12.50," + NEW_LINE + " \"tags\": [\"home\", \"green\"]" + NEW_LINE + "}"), headersToIgnore) ); // - in https assertEquals( response() .withStatusCode(OK_200.code()) .withBody("some_body2"), makeRequest( request() .withSecure(true) .withBody("{" + NEW_LINE + " \"id\": 1," + NEW_LINE + " \"name\": \"A green door\"," + NEW_LINE + " \"price\": 12.50," + NEW_LINE + " \"tags\": [\"home\", \"green\"]" + NEW_LINE + "}"), headersToIgnore) ); } @Test public void shouldClearExpectationsWithParameterBody() { // given mockServerClient .when( request() .withBody(params(param("bodyParameterNameOne", "bodyParameterValueOne"))) ) .respond( response() .withBody("some_body1") ); mockServerClient .when( request() .withBody(params(param("bodyParameterNameTwo", "bodyParameterValueTwo"))) ) .respond( response() .withBody("some_body2") ); // then assertEquals( response() .withStatusCode(OK_200.code()) .withBody("some_body1"), makeRequest( request() .withBody(params(param("bodyParameterName.*", "bodyParameterValue.*"))), headersToIgnore) ); // when mockServerClient .clear( request() .withBody(params(param("bodyParameterNameOne", "bodyParameterValueOne"))) ); // then assertThat( mockServerClient.retrieveExistingExpectations(null), arrayContaining( expectation( request() .withBody(params(param("bodyParameterNameTwo", "bodyParameterValueTwo"))) ) .thenRespond( response() .withBody("some_body2") ) ) ); // - in http assertEquals( response() .withStatusCode(OK_200.code()) .withBody("some_body2"), makeRequest( request() .withBody(params(param("bodyParameterName.*", "bodyParameterValue.*"))), headersToIgnore) ); // - in https assertEquals( response() .withStatusCode(OK_200.code()) .withBody("some_body2"), makeRequest( request() .withSecure(true) .withBody(params(param("bodyParameterName.*", "bodyParameterValue.*"))), headersToIgnore) ); } @Test public void shouldReset() { // given mockServerClient .when( request() .withPath(calculatePath("some_path1")) ) .respond( response() .withBody("some_body1") ); mockServerClient .when( request() .withPath(calculatePath("some_path2")) ) .respond( response() .withBody("some_body2") ); // when mockServerClient.reset(); // then // - in http assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()), makeRequest( request() .withPath(calculatePath("some_path1")), headersToIgnore) ); assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()), makeRequest( request() .withPath(calculatePath("some_path2")), headersToIgnore) ); // - in https assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()), makeRequest( request() .withSecure(true) .withPath(calculatePath("some_path1")), headersToIgnore) ); assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()), makeRequest( request() .withSecure(true) .withPath(calculatePath("some_path2")), headersToIgnore) ); } @Test public void shouldEnsureThatInterruptedRequestsAreVerifiable() throws Exception { mockServerClient .when( request(calculatePath("delayed")) ) .respond( response("delayed data") .withDelay(new Delay(TimeUnit.SECONDS, 3)) ); Future<HttpResponse> delayedFuture = Executors.newSingleThreadExecutor().submit(new Callable<HttpResponse>() { @Override public HttpResponse call() throws Exception { return httpClient.sendRequest( request(addContextToPath(calculatePath("delayed"))) .withHeader(HOST.toString(), "localhost:" + getMockServerPort()) ); } }); Uninterruptibles.sleepUninterruptibly(1, TimeUnit.SECONDS); // Let request reach server delayedFuture.cancel(true); // Then interrupt requesting thread mockServerClient.verify(request(calculatePath("delayed"))); // We should be able to verify request that reached server even though its later interrupted } @Test public void shouldEnsureThatRequestDelaysDoNotAffectOtherRequests() throws Exception { mockServerClient .when( request("/slow") ) .respond( response("super slow") .withDelay(new Delay(TimeUnit.SECONDS, 5)) ); mockServerClient .when( request("/fast") ) .respond( response("quite fast") ); ExecutorService executorService = Executors.newFixedThreadPool(2); Future<Long> slowFuture = executorService.submit(new Callable<Long>() { @Override public Long call() throws Exception { long start = System.currentTimeMillis(); makeRequest(request("/slow")); return System.currentTimeMillis() - start; } }); // Let fast request come to the server slightly after slow request Uninterruptibles.sleepUninterruptibly(1, TimeUnit.SECONDS); Future<Long> fastFuture = executorService.submit(new Callable<Long>() { @Override public Long call() throws Exception { long start = System.currentTimeMillis(); makeRequest(request("/fast")); return System.currentTimeMillis() - start; } }); Long slowRequestElapsedMillis = slowFuture.get(); Long fastRequestElapsedMillis = fastFuture.get(); assertThat("Slow request takes less than expected", slowRequestElapsedMillis, is(greaterThan(5 * 1000L))); assertThat("Fast request takes longer than expected", fastRequestElapsedMillis, is(lessThan(3 * 1000L))); } @Test public void shouldReturnErrorForInvalidExpectation() { // when HttpResponse httpResponse = new NettyHttpClient().sendRequest( request() .withMethod("PUT") .withHeader(HOST.toString(), "localhost:" + getMockServerPort()) .withPath(addContextToPath("/expectation")) .withBody("{" + NEW_LINE + " \"httpRequest\" : {" + NEW_LINE + " \"path\" : \"/path_one\"" + NEW_LINE + " }," + NEW_LINE + " \"incorrectField\" : {" + NEW_LINE + " \"body\" : \"some_body_one\"" + NEW_LINE + " }," + NEW_LINE + " \"times\" : {" + NEW_LINE + " \"remainingTimes\" : 1," + NEW_LINE + " \"unlimited\" : false" + NEW_LINE + " }," + NEW_LINE + " \"timeToLive\" : {" + NEW_LINE + " \"unlimited\" : true" + NEW_LINE + " }" + NEW_LINE + "}") ); // then assertThat(httpResponse.getStatusCode(), is(400)); assertThat(httpResponse.getBodyAsString(), is("2 errors:" + NEW_LINE + " - object instance has properties which are not allowed by the schema: [\"incorrectField\"]" + NEW_LINE + " - oneOf of the following must be specified \"httpResponse\" \"httpForward\" \"httpClassCallback\" \"httpError\" \"httpObjectCallback\" ")); } @Test public void shouldReturnErrorForInvalidRequest() { // when HttpResponse httpResponse = new NettyHttpClient().sendRequest( request() .withMethod("PUT") .withHeader(HOST.toString(), "localhost:" + getMockServerPort()) .withPath(addContextToPath("/clear")) .withBody("{" + NEW_LINE + " \"path\" : 500," + NEW_LINE + " \"method\" : true," + NEW_LINE + " \"keepAlive\" : \"false\"" + NEW_LINE + " }") ); // then assertThat(httpResponse.getStatusCode(), is(400)); assertThat(httpResponse.getBodyAsString(), is("3 errors:" + NEW_LINE + " - instance type (string) does not match any allowed primitive type (allowed: [\"boolean\"]) for field \"/keepAlive\"" + NEW_LINE + " - instance type (boolean) does not match any allowed primitive type (allowed: [\"string\"]) for field \"/method\"" + NEW_LINE + " - instance type (integer) does not match any allowed primitive type (allowed: [\"string\"]) for field \"/path\"")); } protected void verifyRequestMatches(HttpRequest[] httpRequests, HttpRequest... httpRequestMatchers) { if (httpRequests.length != httpRequestMatchers.length) { throw new AssertionError("Number of request matchers does not match number of requests, expected:<" + httpRequestMatchers.length + "> but was:<" + httpRequests.length + ">"); } else { for (int i = 0; i < httpRequestMatchers.length; i++) { if (!new HttpRequestMatcher(httpRequestMatchers[i]).matches(httpRequests[i])) { throw new AssertionError("Request does not match request matcher, expected:<" + httpRequestMatchers[i] + "> but was:<" + httpRequests[i] + ">"); } } } } protected HttpResponse makeRequest(HttpRequest httpRequest) { return makeRequest(httpRequest, Collections.<String>emptySet()); } protected String calculatePath(String path) { return (!path.startsWith("/") ? "/" : "") + path; } protected String addContextToPath(String path) { String cleanedPath = path; if (!Strings.isNullOrEmpty(servletContext)) { cleanedPath = (!servletContext.startsWith("/") ? "/" : "") + servletContext + (!servletContext.endsWith("/") ? "/" : "") + (cleanedPath.startsWith("/") ? cleanedPath.substring(1) : cleanedPath); } return (!cleanedPath.startsWith("/") ? "/" : "") + cleanedPath; } protected HttpResponse makeRequest(HttpRequest httpRequest, Collection<String> headersToIgnore) { int attemptsRemaining = 10; while (attemptsRemaining > 0) { try { boolean isSsl = httpRequest.isSecure() != null && httpRequest.isSecure(); int port = (isSsl ? getMockServerSecurePort() : getMockServerPort()); httpRequest.withPath(addContextToPath(httpRequest.getPath().getValue())); httpRequest.withHeader(HOST.toString(), "localhost:" + port); HttpResponse httpResponse = httpClient.sendRequest(httpRequest, new InetSocketAddress("localhost", port)); List<Header> headers = new ArrayList<Header>(); for (Header header : httpResponse.getHeaders()) { if (!headersToIgnore.contains(header.getName().getValue().toLowerCase())) { if (header.getName().getValue().equalsIgnoreCase(CONTENT_TYPE.toString())) { // this fixes Tomcat which removes the space between // media type and charset in the Content-Type header for (NottableString value : new ArrayList<NottableString>(header.getValues())) { header.getValues().clear(); header.addValues(value.getValue().replace(";charset", "; charset")); } header = header(header.getName().lowercase(), header.getValues()); } headers.add(header); } } httpResponse.withHeaders(headers); return httpResponse; } catch (SocketConnectionException caught) { attemptsRemaining--; logger.info("Retrying connection to mock server, attempts remaining: " + attemptsRemaining); try { TimeUnit.MILLISECONDS.sleep(50); } catch (InterruptedException e) { // do nothing } } } throw new RuntimeException("Failed to send request:" + NEW_LINE + httpRequest); } }
Avarko/mockserver
mockserver-integration-testing/src/main/java/org/mockserver/integration/server/AbstractClientServerIntegrationTest.java
911
package com.mobile.physiolink.ui.psf; import android.os.Bundle; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import androidx.fragment.app.Fragment; import androidx.navigation.Navigation; import android.text.Editable; import android.text.TextWatcher; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.Toast; import com.google.android.material.textfield.TextInputEditText; import com.google.android.material.textfield.TextInputLayout; import com.mobile.physiolink.R; import com.mobile.physiolink.databinding.FragmentCreateServiceBinding; import com.mobile.physiolink.model.service.Service; import com.mobile.physiolink.service.api.error.Error; import com.mobile.physiolink.service.dao.ServiceDAO; import com.mobile.physiolink.ui.popup.ConfirmationPopUp; import java.io.IOException; import java.util.ArrayList; import okhttp3.Call; import okhttp3.Callback; import okhttp3.Response; public class CreateServiceFragment extends Fragment { private FragmentCreateServiceBinding binding; private boolean input_erros; private final ArrayList<TextInputLayout> all_inputs_layouts = new ArrayList<>(); private final ArrayList<TextInputEditText> all_inputs = new ArrayList<>(); public CreateServiceFragment() {} @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // Inflate the layout for this fragment binding = FragmentCreateServiceBinding.inflate(inflater, container, false); return binding.getRoot(); } @Override public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) { populateAllInputs(); // Σε αυτή τη λούπα δημιουργήτε ένας onchange listener για κάθε στοιχείο της λίστας for(int j =0; j<all_inputs.size(); j++) { TextInputEditText current = all_inputs.get(j); TextInputLayout current_layout = all_inputs_layouts.get(j); current.addTextChangedListener(new TextWatcher() { @Override public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) { } @Override public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) { if (current.getText().length() == 0) { current_layout.setError("Το πεδίο πρέπει να συμπληρωθεί!"); input_erros = true; } else { current_layout.setError(null); current_layout.setHelperText(null); input_erros = false; } } @Override public void afterTextChanged(Editable editable) { } }); } binding.saveButton.setOnClickListener(v -> { for(int i = 0; i< all_inputs.size(); i++){ if(all_inputs.get(i).getText().length() == 0){ all_inputs_layouts.get(i).setError("Το πεδίο πρέπει να συμπληρωθεί!"); input_erros = true; } if(all_inputs.get(i).getText().length() > all_inputs_layouts.get(i).getCounterMaxLength()){ input_erros = true; } } if(input_erros){ Toast.makeText(getActivity(), "Πρέπει να συμπληρώσετε σωστά όλα τα υποχρεωτικά πεδία", Toast.LENGTH_SHORT).show(); } else{ ConfirmationPopUp confirmation = new ConfirmationPopUp("Αποθήκευση", "Είστε σίγουρος για την επιλογή σας;", "Ναι", "Οχι"); confirmation.setPositiveOnClick((dialog, which) -> { Service service = new Service(binding.serviceIdInput.getText().toString(), binding.serviceNameInput.getText().toString(), binding.serviceDescriptionInput.getText().toString(), Double.parseDouble(binding.serviceCostInput.getText().toString())); try { ServiceDAO.getInstance().create(service, new Callback() { @Override public void onFailure(Call call, IOException e) { call.cancel(); } @Override public void onResponse(Call call, Response response) throws IOException { String res = response.body().string(); getActivity().runOnUiThread(() -> { if (res.contains(Error.RESOURCE_EXISTS)) { Toast.makeText(getActivity(), "Υπάρχει παροχή με το ίδιο όνομα/κωδικό", Toast.LENGTH_SHORT).show(); return; } Toast.makeText(getActivity(), "Έγινε αποθήκευση Παροχής!", Toast.LENGTH_SHORT).show(); Navigation.findNavController(getActivity(), R.id.fragmentContainerView) .navigate(R.id.action_fragment_create_service_to_fragment_services); }); } }); } catch (IOException ignored) {} }); confirmation.setNegativeOnClick(((dialog, which) -> { Toast.makeText(getActivity(), "Δεν έγινε αποθήκευση Παροχής!", Toast.LENGTH_SHORT).show(); })); confirmation.show(getActivity().getSupportFragmentManager(), "Confirmation pop up"); } }); } private void populateAllInputs() { all_inputs_layouts.add(binding.serviceCostInputLayout); all_inputs.add(binding.serviceCostInput); all_inputs_layouts.add(binding.serviceNameInputLayout); all_inputs.add(binding.serviceNameInput); all_inputs_layouts.add(binding.serviceIdInputLayout); all_inputs.add(binding.serviceIdInput); all_inputs_layouts.add(binding.serviceDescriptionInputLayout); all_inputs.add(binding.serviceDescriptionInput); } }
setokk/PhysioLink
app/src/main/java/com/mobile/physiolink/ui/psf/CreateServiceFragment.java
912
package javaproject; import java.awt.event.MouseAdapter; import java.awt.event.MouseEvent; import java.util.ArrayList; import java.util.Locale; import java.util.Timer; import java.util.TimerTask; import javax.swing.ImageIcon; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JOptionPane; import static javax.swing.JOptionPane.NO_OPTION; import static javax.swing.JOptionPane.PLAIN_MESSAGE; import static javax.swing.JOptionPane.YES_NO_CANCEL_OPTION; import static javax.swing.JOptionPane.YES_OPTION; import javax.swing.JPanel; /** * This is the graphical user interface of the game. * @author Ioannis Maliouris * @author Konstantinos Nikopoulos */ public class Gui extends javax.swing.JFrame { /** * Creates new form Gui */ public Gui() { initComponents(); locale=Locale.getDefault(); if(locale.getLanguage().equals("el")){ message.setText("Επέλεξε το παιχνίδι ντόμινο που θες:"); hungarianButton.setText("Ουγγρικό Ντόμινο"); cardinalButton.setText("Όλα 7"); soloChosenDomino.setText("Επιλεγμένο ντόμινο"); soloLineLabel.setText("Σειρά ντόμινο"); soloStartButton.setText("Έναρξη"); soloHint.setText("ΒΟΗΘΕΙΑ"); soloBack.setText("Πίσω"); hungarianStartButton.setText("ΕΝΑΡΞΗ ΝΕΟΥ ΓΥΡΟΥ"); labelDominoDeck.setText("Σετ Ντόμινο:"); cardGetDomino.setText("Πάρε ντόμινο"); } } /** * This method is called from within the constructor to initialize the form. * WARNING: Do NOT modify this code. The content of this method is always * regenerated by the Form Editor. */ @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { soloFrame = new javax.swing.JFrame(); linePanel = new javax.swing.JPanel(); queue1 = new javax.swing.JPanel(); queue2 = new javax.swing.JPanel(); queue3 = new javax.swing.JPanel(); queue4 = new javax.swing.JPanel(); soloHint = new javax.swing.JButton(); soloDominoLine = new javax.swing.JPanel(); soloDominoDisplay = new javax.swing.JPanel(); bigDomino = new javax.swing.JLabel(); soloChosenDomino = new javax.swing.JLabel(); line1 = new javax.swing.JButton(); line2 = new javax.swing.JButton(); line3 = new javax.swing.JButton(); line4 = new javax.swing.JButton(); soloLineLabel = new javax.swing.JLabel(); soloStartButton = new javax.swing.JButton(); soloBack = new javax.swing.JLabel(); soloIcon = new javax.swing.JLabel(); hungarianFrame = new javax.swing.JFrame(); labelDominoDeck = new javax.swing.JLabel(); labelDominoDeck.setVisible(false); cardGetDomino = new javax.swing.JButton(); cardGetDomino.setVisible(false); dominoDeck = new javax.swing.JLabel(); dominoDeck.setVisible(false); hungPlayer1 = new javax.swing.JPanel(); hungPlayer2 = new javax.swing.JPanel(); hungPlayer3 = new javax.swing.JPanel(); hungPlayer4 = new javax.swing.JPanel(); hungarianDominoLine = new javax.swing.JPanel(); hungarianStartButton = new javax.swing.JButton(); hungarianBackButton = new javax.swing.JLabel(); hungBackround = new javax.swing.JLabel(); exit = new javax.swing.JButton(); buttonPanel = new javax.swing.JPanel(); soloButton = new javax.swing.JButton(); hungarianButton = new javax.swing.JButton(); cardinalButton = new javax.swing.JButton(); infoHung = new javax.swing.JLabel(); infoCard = new javax.swing.JLabel(); infoSolo = new javax.swing.JLabel(); message = new javax.swing.JLabel(); whitePanel = new javax.swing.JPanel(); icon = new javax.swing.JLabel(); soloFrame.setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE); soloFrame.setTitle("Solo1"); soloFrame.setMinimumSize(new java.awt.Dimension(1047, 578)); soloFrame.setPreferredSize(new java.awt.Dimension(1047, 578)); soloFrame.setResizable(false); soloFrame.setSize(390,362); soloFrame.getContentPane().setLayout(null); linePanel.setBackground(new java.awt.Color(0,0,0,0)); linePanel.setMinimumSize(new java.awt.Dimension(195, 275)); queue1.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(0, 0, 0))); queue1.setLayout(new java.awt.FlowLayout(java.awt.FlowLayout.LEFT)); queue2.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(0, 0, 0))); queue2.setLayout(new java.awt.FlowLayout(java.awt.FlowLayout.LEFT)); queue3.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(0, 0, 0))); queue3.setLayout(new java.awt.FlowLayout(java.awt.FlowLayout.LEFT)); queue4.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(0, 0, 0))); queue4.setLayout(new java.awt.FlowLayout(java.awt.FlowLayout.LEFT)); soloHint.setText("HINT"); soloHint.setCursor(new java.awt.Cursor(java.awt.Cursor.HAND_CURSOR)); soloHint.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { soloHintActionPerformed(evt); } }); javax.swing.GroupLayout linePanelLayout = new javax.swing.GroupLayout(linePanel); linePanel.setLayout(linePanelLayout); linePanelLayout.setHorizontalGroup( linePanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(queue1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(queue2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(queue3, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(queue4, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addGroup(linePanelLayout.createSequentialGroup() .addGap(0, 0, Short.MAX_VALUE) .addComponent(soloHint, javax.swing.GroupLayout.PREFERRED_SIZE, 195, javax.swing.GroupLayout.PREFERRED_SIZE)) ); linePanelLayout.setVerticalGroup( linePanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(linePanelLayout.createSequentialGroup() .addComponent(queue1, javax.swing.GroupLayout.PREFERRED_SIZE, 49, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(queue2, javax.swing.GroupLayout.PREFERRED_SIZE, 54, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(7, 7, 7) .addComponent(queue3, javax.swing.GroupLayout.PREFERRED_SIZE, 49, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(queue4, javax.swing.GroupLayout.PREFERRED_SIZE, 52, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(soloHint, javax.swing.GroupLayout.PREFERRED_SIZE, 46, javax.swing.GroupLayout.PREFERRED_SIZE)) ); soloFrame.getContentPane().add(linePanel); linePanel.setBounds(100, 70, 195, 275); soloDominoLine.setBackground(new java.awt.Color(0,0,0,0)); soloDominoLine.setVerifyInputWhenFocusTarget(false); soloFrame.getContentPane().add(soloDominoLine); soloDominoLine.setBounds(0, 490, 1050, 50); soloDominoDisplay.setBackground(new java.awt.Color(0,0,0,0)); soloChosenDomino.setFont(new java.awt.Font("Tahoma", 1, 18)); // NOI18N soloChosenDomino.setHorizontalAlignment(javax.swing.SwingConstants.CENTER); soloChosenDomino.setText("The Domino you chose:"); javax.swing.GroupLayout soloDominoDisplayLayout = new javax.swing.GroupLayout(soloDominoDisplay); soloDominoDisplay.setLayout(soloDominoDisplayLayout); soloDominoDisplayLayout.setHorizontalGroup( soloDominoDisplayLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(soloDominoDisplayLayout.createSequentialGroup() .addGap(34, 34, 34) .addGroup(soloDominoDisplayLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING) .addComponent(bigDomino, javax.swing.GroupLayout.PREFERRED_SIZE, 205, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(soloChosenDomino, javax.swing.GroupLayout.PREFERRED_SIZE, 213, javax.swing.GroupLayout.PREFERRED_SIZE)) .addContainerGap(44, Short.MAX_VALUE)) ); soloDominoDisplayLayout.setVerticalGroup( soloDominoDisplayLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(soloDominoDisplayLayout.createSequentialGroup() .addContainerGap(39, Short.MAX_VALUE) .addComponent(soloChosenDomino, javax.swing.GroupLayout.PREFERRED_SIZE, 36, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(bigDomino, javax.swing.GroupLayout.PREFERRED_SIZE, 98, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(60, 60, 60)) ); soloFrame.getContentPane().add(soloDominoDisplay); soloDominoDisplay.setBounds(680, 60, 291, 244); line1.setIcon(new javax.swing.ImageIcon("pictures/hand.png")); line1.setCursor(new java.awt.Cursor(java.awt.Cursor.HAND_CURSOR)); line1.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { line1ActionPerformed(evt); } }); soloFrame.getContentPane().add(line1); line1.setBounds(300, 80, 36, 36); line2.setIcon(new javax.swing.ImageIcon("pictures/hand.png")); line2.setCursor(new java.awt.Cursor(java.awt.Cursor.HAND_CURSOR)); line2.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { line2ActionPerformed(evt); } }); soloFrame.getContentPane().add(line2); line2.setBounds(300, 140, 36, 37); line3.setIcon(new javax.swing.ImageIcon("pictures/hand.png")); line3.setCursor(new java.awt.Cursor(java.awt.Cursor.HAND_CURSOR)); line3.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { line3ActionPerformed(evt); } }); soloFrame.getContentPane().add(line3); line3.setBounds(300, 190, 36, 39); line4.setIcon(new javax.swing.ImageIcon("pictures/hand.png")); line4.setCursor(new java.awt.Cursor(java.awt.Cursor.HAND_CURSOR)); line4.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { line4ActionPerformed(evt); } }); soloFrame.getContentPane().add(line4); line4.setBounds(300, 250, 36, 39); soloLineLabel.setBackground(new java.awt.Color(255, 255, 255)); soloLineLabel.setFont(new java.awt.Font("Tahoma", 1, 18)); // NOI18N soloLineLabel.setText("Domino Line:"); soloFrame.getContentPane().add(soloLineLabel); soloLineLabel.setBounds(460, 450, 120, 36); soloStartButton.setFont(new java.awt.Font("Tahoma", 1, 18)); // NOI18N soloStartButton.setText("Start"); soloStartButton.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { soloStartButtonActionPerformed(evt); } }); soloFrame.getContentPane().add(soloStartButton); soloStartButton.setBounds(450, 200, 120, 49); soloBack.setIcon(new javax.swing.ImageIcon("pictures/backArrow.png")); soloBack.setText("back"); soloBack.setCursor(new java.awt.Cursor(java.awt.Cursor.HAND_CURSOR)); soloBack.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER); soloBack.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseClicked(java.awt.event.MouseEvent evt) { soloBackMouseClicked(evt); } }); soloFrame.getContentPane().add(soloBack); soloBack.setBounds(30, 20, 70, 33); soloIcon.setIcon(new javax.swing.ImageIcon("pictures/soloTable.png")); soloFrame.getContentPane().add(soloIcon); soloIcon.setBounds(0, 0, 1050, 580); hungarianFrame.setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE); hungarianFrame.setCursor(new java.awt.Cursor(java.awt.Cursor.DEFAULT_CURSOR)); hungarianFrame.setMinimumSize(new java.awt.Dimension(1332, 533)); hungarianFrame.setName("Hungarian Mode"); // NOI18N hungarianFrame.setPreferredSize(new java.awt.Dimension(1332, 533)); hungarianFrame.setResizable(false); hungarianFrame.getContentPane().setLayout(null); labelDominoDeck.setFont(new java.awt.Font("Tahoma", 1, 14)); // NOI18N labelDominoDeck.setHorizontalAlignment(javax.swing.SwingConstants.CENTER); labelDominoDeck.setText("Domino Deck:"); hungarianFrame.getContentPane().add(labelDominoDeck); labelDominoDeck.setBounds(100, 400, 110, 30); cardGetDomino.setText("get Domino"); cardGetDomino.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { cardGetDominoActionPerformed(evt); } }); hungarianFrame.getContentPane().add(cardGetDomino); cardGetDomino.setBounds(860, 360, 100, 23); dominoDeck.setFont(new java.awt.Font("Tahoma", 1, 18)); // NOI18N dominoDeck.setHorizontalAlignment(javax.swing.SwingConstants.CENTER); hungarianFrame.getContentPane().add(dominoDeck); dominoDeck.setBounds(120, 430, 70, 70); hungPlayer1.setBackground(new java.awt.Color(0,0,0,0)); hungPlayer1.setCursor(new java.awt.Cursor(java.awt.Cursor.DEFAULT_CURSOR)); hungPlayer1.setLayout(new java.awt.FlowLayout(java.awt.FlowLayout.CENTER, 5, 10)); hungarianFrame.getContentPane().add(hungPlayer1); hungPlayer1.setBounds(360, 420, 608, 70); hungPlayer2.setBackground(new java.awt.Color(0,0,0,0)); hungarianFrame.getContentPane().add(hungPlayer2); hungPlayer2.setBounds(353, 11, 608, 56); hungPlayer3.setBackground(new java.awt.Color(0,0,0,0)); hungarianFrame.getContentPane().add(hungPlayer3); hungPlayer3.setBounds(1276, 75, 46, 359); hungPlayer4.setBackground(new java.awt.Color(0,0,0,0)); hungarianFrame.getContentPane().add(hungPlayer4); hungPlayer4.setBounds(10, 75, 47, 359); hungarianDominoLine.setBackground(new java.awt.Color(0,0,0,0)); hungarianFrame.getContentPane().add(hungarianDominoLine); hungarianDominoLine.setBounds(58, 244, 1210, 50); hungarianStartButton.setText("START NEW ROUND"); hungarianStartButton.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { hungarianStartButtonActionPerformed(evt); } }); hungarianFrame.getContentPane().add(hungarianStartButton); hungarianStartButton.setBounds(575, 190, 160, 36); hungarianBackButton.setIcon(new javax.swing.ImageIcon("pictures/hungBackArrow.png")); hungarianBackButton.setText("back"); hungarianBackButton.setCursor(new java.awt.Cursor(java.awt.Cursor.HAND_CURSOR)); hungarianBackButton.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseClicked(java.awt.event.MouseEvent evt) { hungarianBackButtonMouseClicked(evt); } }); hungarianFrame.getContentPane().add(hungarianBackButton); hungarianBackButton.setBounds(20, 20, 70, 30); hungBackround.setIcon(new javax.swing.ImageIcon("pictures/hungarianTable.png")); hungBackround.setMinimumSize(new java.awt.Dimension(1330, 530)); hungBackround.setPreferredSize(new java.awt.Dimension(1330, 530)); hungarianFrame.getContentPane().add(hungBackround); hungBackround.setBounds(0, 0, 1330, 530); setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE); setTitle("Domino Games"); setMinimumSize(new java.awt.Dimension(430, 381)); setName("Domino Games"); // NOI18N setUndecorated(true); setSize(430,381); getContentPane().setLayout(null); exit.setBackground(new java.awt.Color(0, 0, 0)); exit.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N exit.setForeground(new java.awt.Color(255, 255, 255)); exit.setText("X"); exit.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { exitActionPerformed(evt); } }); getContentPane().add(exit); exit.setBounds(370, 10, 40, 40); buttonPanel.setBackground(new java.awt.Color(0,0,0,0)); buttonPanel.setCursor(new java.awt.Cursor(java.awt.Cursor.DEFAULT_CURSOR)); soloButton.setBackground(new java.awt.Color(0, 0, 0)); soloButton.setForeground(new java.awt.Color(255, 255, 255)); soloButton.setText("Solo1"); soloButton.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { soloButtonActionPerformed(evt); } }); hungarianButton.setBackground(new java.awt.Color(0, 0, 0)); hungarianButton.setForeground(new java.awt.Color(255, 255, 255)); hungarianButton.setText("Hungarian Mode"); hungarianButton.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { hungarianButtonActionPerformed(evt); } }); cardinalButton.setBackground(new java.awt.Color(0, 0, 0)); cardinalButton.setForeground(new java.awt.Color(255, 255, 255)); cardinalButton.setText("Cardinal"); cardinalButton.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { cardinalButtonActionPerformed(evt); } }); infoHung.setIcon(new ImageIcon("pictures/info.png")); infoHung.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseClicked(java.awt.event.MouseEvent evt) { infoHungMouseClicked(evt); } }); infoCard.setIcon(new ImageIcon("pictures/info.png")); infoCard.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseClicked(java.awt.event.MouseEvent evt) { infoCardMouseClicked(evt); } }); infoSolo.setIcon(new ImageIcon("pictures/info.png")); infoSolo.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseClicked(java.awt.event.MouseEvent evt) { infoSoloMouseClicked(evt); } }); javax.swing.GroupLayout buttonPanelLayout = new javax.swing.GroupLayout(buttonPanel); buttonPanel.setLayout(buttonPanelLayout); buttonPanelLayout.setHorizontalGroup( buttonPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(buttonPanelLayout.createSequentialGroup() .addContainerGap() .addGroup(buttonPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false) .addComponent(soloButton, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(hungarianButton, javax.swing.GroupLayout.DEFAULT_SIZE, 121, Short.MAX_VALUE) .addComponent(cardinalButton, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(buttonPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(infoHung, javax.swing.GroupLayout.DEFAULT_SIZE, 25, Short.MAX_VALUE) .addComponent(infoSolo, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, 25, Short.MAX_VALUE) .addComponent(infoCard, javax.swing.GroupLayout.DEFAULT_SIZE, 25, Short.MAX_VALUE)) .addContainerGap()) ); buttonPanelLayout.setVerticalGroup( buttonPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(buttonPanelLayout.createSequentialGroup() .addGroup(buttonPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING) .addComponent(soloButton, javax.swing.GroupLayout.PREFERRED_SIZE, 31, javax.swing.GroupLayout.PREFERRED_SIZE) .addGroup(buttonPanelLayout.createSequentialGroup() .addContainerGap() .addComponent(infoSolo, javax.swing.GroupLayout.PREFERRED_SIZE, 25, javax.swing.GroupLayout.PREFERRED_SIZE))) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(buttonPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING) .addComponent(hungarianButton, javax.swing.GroupLayout.PREFERRED_SIZE, 32, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(infoHung, javax.swing.GroupLayout.PREFERRED_SIZE, 25, javax.swing.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addGroup(buttonPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(cardinalButton, javax.swing.GroupLayout.PREFERRED_SIZE, 32, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(infoCard, javax.swing.GroupLayout.PREFERRED_SIZE, 25, javax.swing.GroupLayout.PREFERRED_SIZE)) .addContainerGap()) ); getContentPane().add(buttonPanel); buttonPanel.setBounds(140, 140, 170, 110); message.setFont(new java.awt.Font("Tahoma", 1, 14)); // NOI18N message.setHorizontalAlignment(javax.swing.SwingConstants.CENTER); message.setText("Choose the domino game you want to play:"); getContentPane().add(message); message.setBounds(50, 10, 302, 51); whitePanel.setBackground(new java.awt.Color(255, 255, 255)); whitePanel.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(0, 0, 0))); icon.setIcon(new javax.swing.ImageIcon("pictures/domino.jpg")); javax.swing.GroupLayout whitePanelLayout = new javax.swing.GroupLayout(whitePanel); whitePanel.setLayout(whitePanelLayout); whitePanelLayout.setHorizontalGroup( whitePanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, whitePanelLayout.createSequentialGroup() .addGap(0, 190, Short.MAX_VALUE) .addComponent(icon, javax.swing.GroupLayout.PREFERRED_SIZE, 238, javax.swing.GroupLayout.PREFERRED_SIZE)) ); whitePanelLayout.setVerticalGroup( whitePanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, whitePanelLayout.createSequentialGroup() .addGap(0, 177, Short.MAX_VALUE) .addComponent(icon, javax.swing.GroupLayout.PREFERRED_SIZE, 201, javax.swing.GroupLayout.PREFERRED_SIZE)) ); getContentPane().add(whitePanel); whitePanel.setBounds(0, 0, 430, 380); getAccessibleContext().setAccessibleName(""); pack(); }// </editor-fold>//GEN-END:initComponents /** * Starts a new Hungarian frame for Cardinal game. * @param evt */ private void cardinalButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cardinalButtonActionPerformed cardinalGame=new Cardinal(1); startHungarianGame(cardinalGame); }//GEN-LAST:event_cardinalButtonActionPerformed /** * Starts a new Hungarian frame for Hungarian game. * @param evt */ private void hungarianButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_hungarianButtonActionPerformed startHungarianGame(hungarianGame); }//GEN-LAST:event_hungarianButtonActionPerformed /** * Starts a new Solo frame. * @param evt */ private void soloButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_soloButtonActionPerformed startSoloGame(); }//GEN-LAST:event_soloButtonActionPerformed /** * Terminates the whole program. * @param evt */ private void exitActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_exitActionPerformed dispose(); }//GEN-LAST:event_exitActionPerformed /** * Gives info for the Solo game. * @param evt */ private void infoSoloMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_infoSoloMouseClicked if(locale.getLanguage().equals("el")){ JOptionPane.showMessageDialog(this,"Το παιχνίδι αυτό αποτελείται από έναν παίκτη." +"\nΣτο solo1 το σετ από τα ντόμινο αφού ανακατευχθεί," + "\nχωρίζεται σε 4 γραμμές. Ο Παίκτης μπορεί να δει" + "\nόλα τα ντόμινο αλλά μπορεί να χρησιμοποιήσει" + "\nμόνο τα τελευταία από κάθε γραμμή. Αν κανένα ντόμινο" + "\nδεν μπορεί να μπει στην σειρά ντόμινο τότε το " + "\nπαιχνίδι τελειώνει και ο Παίκτης χάνει. Νικάει" + "\nμόνο όταν όλες οι γραμμές είναι άδειες και δεν" + "\nυπάρχει ντόμινο που μπορεί να τοποθετεί στην σειρά."); } else{ JOptionPane.showMessageDialog(this,"Solo1 is a domino game which is playable by one player. In solo1 the set of \n" + "dominos after being suffled it is divided in 4 lines. Player can see every\n" + "domino but he can use only the last of each of the 4 lines. If none of these\n" + "dominos fit on the domino line then the game is over and the player loses. He\n" + "wins only when all lines are empty and no domino is left to be played."); } }//GEN-LAST:event_infoSoloMouseClicked /** * Gives info for the Hungarian game. * @param evt */ private void infoHungMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_infoHungMouseClicked if(locale.getCountry().equals("GR")){ JOptionPane.showMessageDialog(this,"Το ουγγρικό ντόμινο παίζεται από 2 έως 4 παίκτες. Τα ντόμινο\n" + "αφού ανακατευχθούν δίνονται σε κάθε πάικτη.Ο παίκτης με το\n" + "μεγαλύτερο διπλό ντόμινο ξεκινάει να παίζει. Σταματάει να\n" + "παίζει όταν δεν μπορεί να τοποθετήσει άλλα ντόμινο στην\n" + "σειρά. Ο επόμενος παίκτης είναι ο διπλανός του. Όταν ένας\n" + "παίκτης έχει μείνει χωρίς ντόμινο στο χέρι, ο γύρος \n" + "σταματάει και παίρνει τόσους πόντους όσους έχει κάθε παίκτης\n" + "στα χέρια του. Αυτό σημαίνει ότι παίρνει το άθροισμα από \n" + "κάθε αριθμό που οι άλλοι παίκτες έχουν στα ντόμινό τους. \n" + "Επιπρόσθετα αν κανένας δεν μπορεί να βάλει κάποιο ντόμινο\n" + "στην σειρά τότε ο γύρος σταματάει και ο παίκτης με τους\n" + "λιγότερους πόντους στα χέρια του νικάει τον γύρο και παίρνει\n" + "όσους πόντους έχουν οι άλλοι παίκτες συν τους δικούς του.\n" + "Το παιχνίδι σταματάει όταν κάποιος παίκτης φτάσεις τους 100\n" + "πόντους"); } else{ JOptionPane.showMessageDialog(this,"Hungarian game is a game played by dominos. It consists of 2 to 4 players.\n" + " Shuffled dominos are handed out to players. The player with the biggest\n" + "double domino starts the round. He stops playing when he cant put other \n" + "dominos in the domino line. Then the player next to him has the turn to play.\n" + "When one player is being left without dominos the round stops and he gains\n" + "as points as every other player has in his hands. This means that he gains\n" + "the sum of every number the other players have in their dominos. In addition\n" + "if no one has any domino tile to fit the round stops and the player with the \n" + "least points on his hand wins the round and gains every point that the other \n" + "players have plus his own points. The game stops when one player reaches 100\n" + "points."); } }//GEN-LAST:event_infoHungMouseClicked /** * Gives info for the Cardinal game. * @param evt */ private void infoCardMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_infoCardMouseClicked // TODO add your handling code here: if(locale.getCountry().equals("GR")){ JOptionPane.showMessageDialog(this,"Το παιχνίδι Όλα 7 παίζεται από 2 έως 4 παίκτες. Τα ντόμινο\n" + "αφού ανακατευχθούν δίνονται σε κάθε πάικτη.Ο παίκτης με το\n" + "μεγαλύτερο διπλό ντόμινο ξεκινάει να παίζει. Σταματάει να\n" + "παίζει όταν δεν μπορεί να τοποθετήσει άλλα ντόμινο στην\n" + "σειρά. Για να τοποθετήσει ένα ντόμινο στη σειρά πρέπει το \n" + "άθροισμα από τις δύο πλευρές των ντόμινο να είναι 7. Υπάρχουν\n" + "ντόμινο μπαλαντέρ που μπορούν να τοποθετηθούν παντού. Μπαλαντέρ\n" + "θεωρούνται τα ντόμινο που το άθροισμα των 2 πλευρών τους είναι\n" + "ίσο με το 7 ή με το 0.Ο επόμενος παίκτης είναι ο διπλανός του. \n" + "Ο παίκτης μπορεί να πάρει ένα ντόμινο από το σετ όσο ακόμα μπορεί\n" + "να παίξει κάποιο ντόμινο αλλιώς τραβάει ντόμινο μέχρι να μπορεί\n" + "να παίξει. Όταν έναςπαίκτης έχει μείνει χωρίς ντόμινο στο χέρι, ο γύρος \n" + "σταματάει και παίρνει τόσους πόντους όσους έχει κάθε παίκτης\n" + "στα χέρια του. Αυτό σημαίνει ότι παίρνει το άθροισμα από \n" + "κάθε αριθμό που οι άλλοι παίκτες έχουν στα ντόμινό τους. \n" + "Επιπρόσθετα αν κανένας δεν μπορεί να βάλει κάποιο ντόμινο\n" + "στην σειρά τότε ο γύρος σταματάει και ο παίκτης με τους\n" + "λιγότερους πόντους στα χέρια του νικάει τον γύρο και παίρνει\n" + "όσους πόντους έχουν οι άλλοι παίκτες συν τους δικούς του.\n" + "Το παιχνίδι σταματάει όταν κάποιος παίκτης φτάσεις τους 100\n" + "πόντους"); } else{ JOptionPane.showMessageDialog(this,"Cardinal game is a game played by dominos. It consists of 2 to 4 players.\n" + "Shuffled dominos are handed out to players. The player with the biggest\n" + "double domino starts the round. He stops playing when he cant put other \n" + "dominos in the domino line. In order to put a domino in the domino line the\n" + "sum of the 2 sides of the dominos must be 7. There are cardinal dominos that \n" + "can be put everywhere. Cardinal dominos are the dominos which the sum of \n" + "their sides is 7 or 0.Then the player next to him has the turn to play. A \n" + "player can take one domino from the deck when he can still play, otherwise when he cant\n" + "he takes dominos from the deck until he can play .When one player is being left \n" + "without dominos the round stops and he gains as points as every other player\n" + "has in his hands. This means that he gains the sum of every number the other\n" + "players have in their dominos. In addition if no one has any domino tile to \n" + "fit the round stops and the player with the least points on his hand wins the \n" + "round and gains every point that the other players have plus his own points. \n" + "The game stops when one player reaches 100 points."); } }//GEN-LAST:event_infoCardMouseClicked /** * After being pressed, it starts the Solo game. * @param evt */ private void soloStartButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_soloStartButtonActionPerformed // TODO add your handling code here: soloGame.setRandomLines(); soloHint.setVisible(true); line1.setVisible(true); line2.setVisible(true); line3.setVisible(true); line4.setVisible(true); updateSoloFrame(); soloStartButton.setVisible(false); soloFrame.revalidate(); soloFrame.repaint(); }//GEN-LAST:event_soloStartButtonActionPerformed /** * Selects a domino from the 4th line. * @param evt */ private void line4ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_line4ActionPerformed lineActionPerformed(4); }//GEN-LAST:event_line4ActionPerformed /** * Selects a domino from the 3rd line. * @param evt */ private void line3ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_line3ActionPerformed lineActionPerformed(3); }//GEN-LAST:event_line3ActionPerformed /** * Selects a domino from the 2nd line. * @param evt */ private void line2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_line2ActionPerformed lineActionPerformed(2); }//GEN-LAST:event_line2ActionPerformed /** * Selects a domino from the 1st line. * @param evt */ private void line1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_line1ActionPerformed lineActionPerformed(1); }//GEN-LAST:event_line1ActionPerformed /** * Makes red the dominos that can be played. * @param evt */ private void soloHintActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_soloHintActionPerformed for(int i=0;i<4;i++){ Domino domino; javax.swing.JLabel label=(javax.swing.JLabel)panels[i].getComponent(panels[i].getComponentCount()-1); domino=soloGame.getDomino(soloGame.getLine(i+1)); if(soloGame.fitsOnDominoLine(domino)){ label.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(255, 0, 0))); } } }//GEN-LAST:event_soloHintActionPerformed /** * Disposes the Solo frame and goes back to the first frame. * @param evt */ private void soloBackMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_soloBackMouseClicked soloFrame.dispose(); domino=null; setVisible(true); }//GEN-LAST:event_soloBackMouseClicked /** * Starts a new round for the Hungarian or the Cardinal game on the Hungarian * frame. * @param evt */ private void hungarianStartButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_hungarianStartButtonActionPerformed //JOptionPane.showMessageDialog(hungarianFrame,"Its Player"+hungarianGame.getCurrentPlayer()+"'s turn"); if(locale.getLanguage().equals("el")){ JOptionPane.showMessageDialog(hungarianFrame,"Νέος γύρος ξεκινάει"); } else{ JOptionPane.showMessageDialog(hungarianFrame,"New round starts"); } updateHungarianGame(game); hungarianStartButton.setVisible(false); hungarianDominoLine.setVisible(true); }//GEN-LAST:event_hungarianStartButtonActionPerformed /** * Disposes the Hungarian frame and goes back to the first frame. * @param evt */ private void hungarianBackButtonMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_hungarianBackButtonMouseClicked hungarianFrame.dispose(); domino=null; setVisible(true); }//GEN-LAST:event_hungarianBackButtonMouseClicked /** * On a cardinal game takes a domino from the domino set * @param evt */ private void cardGetDominoActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cardGetDominoActionPerformed cardinalGame.getDomino(); updateHungarianFrame(game); cardGetDomino.setVisible(false); }//GEN-LAST:event_cardGetDominoActionPerformed /** * Selects a domino from the line given. * @param numberOfLine the line from which the domino will be taken. */ private void lineActionPerformed(int numberOfLine){ line=soloGame.getLine(numberOfLine); if(!line.isEmpty()){ domino=soloGame.getDomino(line); updateSoloFrame(); updateDominoLine(soloGame); } } /** * Sets visible the Solo frame. */ private void startSoloGame(){ setVisible(false); soloFrame.setLocationRelativeTo(null); panels=new JPanel[4]; panels[0]=queue1; panels[1]=queue2; panels[2]=queue3; panels[3]=queue4; soloHint.setVisible(false); line1.setVisible(false); line2.setVisible(false); line3.setVisible(false); line4.setVisible(false); soloStartButton.setVisible(true); soloGame=new Solo1(); soloGame.setLines(); updateSoloFrame(); updateDominoLine(soloGame); soloFrame.setVisible(true); } /** * Sets visible the Hungarian frame, after the player selects the number * of players to play the game. * @param game Cardinal or Hungarian game. */ private void startHungarianGame(HungarianMode game){ hungPlayer3.setVisible(false); hungPlayer4.setVisible(false); Integer possibilities[]={2,3,4}; String message; String numberOfPlayers; if(locale.getLanguage().equals("el")){ message="Επέλεξε τον αριθμό παικτών"; numberOfPlayers="Παίκτες"; } else{ message="Choose the number of players"; numberOfPlayers="Players"; } Integer players=(Integer) JOptionPane.showInputDialog( this, message, numberOfPlayers, JOptionPane.PLAIN_MESSAGE, null, possibilities, possibilities[0]);; if(players!=null){ setVisible(false); if(game instanceof Cardinal){ cardinalGame=new Cardinal(players); game=cardinalGame; this.game=game; dominoDeck.setVisible(true); labelDominoDeck.setVisible(true); } else{ hungarianGame=new HungarianMode(players); game=hungarianGame; this.game=game; } panels=new JPanel[players]; panels[0]=hungPlayer1; panels[1]=hungPlayer2; if(players==3){ panels[2]=hungPlayer3; hungPlayer3.setVisible(true); } else if(players==4){ panels[2]=hungPlayer3; panels[3]=hungPlayer4; hungPlayer3.setVisible(true); hungPlayer4.setVisible(true); } hungarianFrame.setLocationRelativeTo(null); startNewRound(game); hungarianFrame.setVisible(true); } else{ setVisible(true); } } /** * Starts a new round for the Cardinal or the Hungarian game. * @param game Cardinal or Hungarian game. */ private void startNewRound(HungarianMode game){ hungarianStartButton.setVisible(true); hungarianDominoLine.setVisible(false); game.newRound(); updateHungarianFrame(game); } /** * Tries to put the selected domino on the right of the domino line. * @param game Solo,Hungarian or Cardinal game */ private void rightArrowMouseClicked(Game game) { arrowMouseClicked("left",game); } /** * Tries to put the selected domino on the left of the domino line. * @param game Solo,Hungarian or Cardinal game */ private void leftArrowMouseClicked(Game game) { arrowMouseClicked("right",game); } /** * When it's player's turn. When he clicks a domino, this domino goes a * little higher than the others in order to show to the player which domino * he has selected. * @param domino * @param label */ private void dominoClicked(Domino domino,JLabel label){ if(game.getCurrentPlayer()==1){ hungarianFrame.revalidate(); hungarianFrame.repaint(); this.domino=domino; this.domino=domino; int x=label.getX(); int y=label.getY(); label.setLocation(x,y-10); } } /** * Tries to put a domino on the left or on the right of the domino line * depending on the direction given. * @param direction specifies where the domino will be put * @param game Solo game, Hungarian game or Cardinal game. */ private void arrowMouseClicked(String direction,Game game){ if(domino!=null){ if(game instanceof Solo1){ if(!line.isEmpty()){ domino=soloGame.getDomino(line); if(soloGame.addDomino(line,direction)){ domino=null; } //domino=soloGame.getDomino(line); updateSoloFrame(); updateDominoLine(soloGame); if(!soloGame.solutionExists()){ if(soloGame.playerWon()){ if(locale.getLanguage().equals("el")){ gameIsOver(soloGame,"Κέρδισες",soloFrame); } else{ gameIsOver(soloGame,"won",soloFrame); } } else{ if(locale.getLanguage().equals("el")){ gameIsOver(soloGame,"Έχασες",soloFrame); } else{ gameIsOver(soloGame,"lost",soloFrame); } } } } } else if(game instanceof Cardinal){ if(cardinalGame.getCurrentPlayer()==1){ if(cardinalGame.addDomino(domino,direction)){ domino=null; } } else{ updateHungarianGame(cardinalGame); } if(!cardinalGame.playerCanPlay()){ if(!cardinalGame.playerHasDominos()){ updateHungarianGame(cardinalGame); } if(!cardinalGame.getDominos()){ updateHungarianGame(cardinalGame); } else{ cardGetDomino.setVisible(false); } } updateHungarianFrame(cardinalGame); updateDominoLine(cardinalGame); } else if(game instanceof HungarianMode){ if(hungarianGame.getCurrentPlayer()==1){ if(hungarianGame.addDomino(domino,direction)){ domino=null; } } else{ updateHungarianGame(hungarianGame); } if(!hungarianGame.playerCanPlay()){ updateHungarianGame(hungarianGame); } updateHungarianFrame(hungarianGame); updateDominoLine(hungarianGame); } } } /** * This method pops a window when a game is over and asks the player if he * wants to play again or not. If he presses yes a new game starts. If he * presses no he goes back to the first frame. If he presses cancel nothing * happens and he can decide what he will do. * @param game Solo game,Hungarian game or Cardinal game * @param wonOrLost it is needed for the Solo game * @param frame Solo frame or Hungarian frame. */ private void gameIsOver(Game game,String wonOrLost,JFrame frame){ if(game instanceof Solo1){ Object options[]=new Object[3]; String message; String sentence; if(locale.getLanguage().equals("el")){ options[0]="Ναι"; options[1]="Όχι, πάνε πίσω στο μενού"; options[2]="Ακύρωση"; message=wonOrLost+".\nΘες να παίξεις ξανά; "; sentence="Το παιχνίδι τελείωσε"; } else{ options[0]="Yes"; options[1]="No, go back to menu"; options[2]="Cancel"; message="You "+wonOrLost+ ", \ndo you want to play again?"; sentence="Game is over"; } int option=JOptionPane.showOptionDialog( frame, message, sentence, YES_NO_CANCEL_OPTION, PLAIN_MESSAGE, null, options, options[0]); if(option==YES_OPTION){ frame.dispose(); startSoloGame(); } if(option==NO_OPTION){ frame.dispose(); setVisible(true); } } else if(game instanceof HungarianMode){ Object options[]=new Object[3]; String message; String sentence; if(locale.getLanguage().equals("el")){ options[0]="Ναι"; options[1]="Όχι, πάνε πίσω στο μενού"; options[2]="Ακύρωση"; message="Ο Παίκτης"+this.game.getCurrentPlayer()+" κέρδισε το παιχνίδι"; sentence="Το παιχνίδι τελείωσε"; } else{ options[0]="Yes"; options[1]="No, go back to menu"; options[2]="Cancel"; message="Player"+this.game.getCurrentPlayer()+" won the game"; sentence="Game is over"; } int option=JOptionPane.showOptionDialog( frame, message, sentence, YES_NO_CANCEL_OPTION, PLAIN_MESSAGE, null, options, options[0]); if(option==YES_OPTION){ frame.dispose(); startHungarianGame(this.game); } if(option==NO_OPTION){ frame.dispose(); setVisible(true); } } } /** * Updates the Solo frame */ private void updateSoloFrame(){ //DominoSet dominoSet=soloGame.getDominoSet(); //ArrayList<javax.swing.JLabel> labels=new ArrayList<>(); for(int i=0;i<4;i++){ panels[i].removeAll(); ArrayList<Domino> line=soloGame.getLine(i+1); for(int j=0;j<line.size();j++){ Domino domino=line.get(j); JLabel label=new JLabel(); label.setIcon(new ImageIcon("pictures/dominosVertical/domino"+domino.getLeft()+domino.getRight()+".png")); panels[i].add(label); } if(domino!=null){ bigDomino.setIcon(new ImageIcon("pictures/bigDominos/domino"+domino.getLeft()+domino.getRight()+".png")); } else{ bigDomino.setIcon(null); } panels[i].revalidate(); panels[i].repaint(); } soloFrame.revalidate(); soloFrame.repaint(); } /** * Updates the Hungarian frame. * @param game Hungarian or Cardinal game. */ private void updateHungarianFrame(HungarianMode game){ if(game instanceof Cardinal){ Integer size=cardinalGame.getSetSize(); dominoDeck.setText(size.toString()); } for(int i=0;i<panels.length;i++){ panels[i].removeAll(); ArrayList<Domino> dominosOfPlayer=game.getDominosOfPlayer(i+1); for(int j=0;j<dominosOfPlayer.size();j++){ Domino domino=dominosOfPlayer.get(j); JLabel label=new JLabel(); if(i==0){ label.setIcon(new ImageIcon("pictures/dominosVertical/domino"+domino.getLeft()+domino.getRight()+".png")); label.setCursor(new java.awt.Cursor(java.awt.Cursor.HAND_CURSOR)); label.addMouseListener(new MouseAdapter() { public void mouseClicked(MouseEvent evt) { dominoClicked(domino,label); } }); } else{ label.setIcon(new ImageIcon("pictures/dominosVertical/dominoback.png")); } //label.setIcon(new ImageIcon("pictures/dominosVertical/domino00.png")); panels[i].add(label); } //panels[i].revalidate(); //panels[i].repaint(); } updateDominoLine(game); hungarianFrame.revalidate(); hungarianFrame.repaint(); } /** * Checks if the game is finished. If not, it shows which player's turn it * is * @param game Hungarian or Cardinal game. */ private void updateHungarianGame(HungarianMode game){ updateHungarianFrame(game); if(!game.solutionExists()){ showPointsOfPlayer(game); if(!game.gameIsOver()){ startNewRound(game); } else{ gameIsOver(game,"",hungarianFrame); dominoDeck.setVisible(false); labelDominoDeck.setVisible(false); } } else{ if(game.getCurrentPlayer()!=1){ if(locale.getLanguage().equals("el")){ JOptionPane.showMessageDialog(hungarianFrame,"Είναι η σειρά" +" του Παίκτη"+game.getCurrentPlayer()); } else{ JOptionPane.showMessageDialog(hungarianFrame,"Its Player" +game.getCurrentPlayer()+"'s turn"); } Timer myTimer=new Timer(); TimerTask task=new TimerTask() { public void run() { game.bot(); updateHungarianGame(game); myTimer.cancel(); } }; myTimer.schedule(task, 100); } else{ if(game instanceof Cardinal){ if(cardinalGame.getSetSize()>2){ cardGetDomino.setVisible(true); } } if(locale.getLanguage().equals("el")){ JOptionPane.showMessageDialog(hungarianFrame,"Είναι η σειρά σου"); } else{ JOptionPane.showMessageDialog(hungarianFrame,"Its your turn"); } hungarianFrame.revalidate(); hungarianFrame.repaint(); } } } /** * Updates the domino line of every frame. * @param game Solo,Hungarian or Cardinal game. */ private void updateDominoLine(Game game){ ArrayList<Domino> line=game.getDominoLine(); JPanel panel; if(game instanceof Solo1){ panel=soloDominoLine; } else{ panel=hungarianDominoLine; } panel.removeAll(); javax.swing.JLabel rightArrow=new javax.swing.JLabel(); rightArrow.setIcon(new javax.swing.ImageIcon("pictures/dominosHorizontal/rightArrow.png")); rightArrow.setCursor(new java.awt.Cursor(java.awt.Cursor.HAND_CURSOR)); rightArrow.addMouseListener(new MouseAdapter() { public void mouseClicked(MouseEvent evt) { rightArrowMouseClicked(game); } }); panel.add(rightArrow); for(int i=0;i<line.size();i++){ Domino domino=line.get(i); javax.swing.JLabel label=new javax.swing.JLabel(); if(game instanceof Cardinal){ label.setIcon(new ImageIcon("pictures/dominosCardinal/domino"+domino.getLeft()+domino.getRight()+".png")); } else{ label.setIcon(new ImageIcon("pictures/dominosHorizontal/domino"+domino.getLeft()+domino.getRight()+".png")); } panel.add(label); } javax.swing.JLabel leftArrow = new javax.swing.JLabel(); leftArrow.setIcon(new ImageIcon("pictures/dominosHorizontal/leftArrow.png")); leftArrow.setCursor(new java.awt.Cursor(java.awt.Cursor.HAND_CURSOR)); leftArrow.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseClicked(java.awt.event.MouseEvent evt) { leftArrowMouseClicked(game); } }); panel.add(leftArrow); panel.revalidate(); panel.repaint(); } /** * Shows the players' points of the Hungarian or Cardinal game. * @param game Hungarian or Cardinal game. */ private void showPointsOfPlayer(HungarianMode game){ if(locale.getLanguage().equals("el")){ JOptionPane.showMessageDialog(hungarianFrame,"Ο Παίκτης"+game.playerWhoWonTheRound()+" κέρδισε τον γύρο"); } else{ JOptionPane.showMessageDialog(hungarianFrame,"Player"+game.playerWhoWonTheRound()+"won the round"); } if(game.getPlayers()==2){ if(locale.getLanguage().equals("el")){ JOptionPane.showMessageDialog(hungarianFrame,"Ο Παίκτης1 έχει: "+game.pointsOfPlayer(1)+"πόντους\n" + "Ο Παίκτης2 έχει: "+game.pointsOfPlayer(2)+"πόντους"); } else{ JOptionPane.showMessageDialog(hungarianFrame,"Player1 has: "+game.pointsOfPlayer(1)+"points\n" + "Player2 has: "+game.pointsOfPlayer(2)+"points"); } } else if(game.getPlayers()==3){ if(locale.getLanguage().equals("el")){ JOptionPane.showMessageDialog(hungarianFrame,"Ο Παίκτης1 έχει: "+game.pointsOfPlayer(1)+"πόντους\n" + "Ο Παίκτης2 έχει: "+game.pointsOfPlayer(2)+"πόντους\n" + "Ο Παίκτης3 έχει: "+game.pointsOfPlayer(3)+"πόντους"); } else{ JOptionPane.showMessageDialog(hungarianFrame,"Player1 has: "+game.pointsOfPlayer(1)+"points\n" + "Player2 has: "+game.pointsOfPlayer(2)+"points\n" + "Player3 has: "+game.pointsOfPlayer(3)+"points"); } } else{ if(locale.getLanguage().equals("el")){ JOptionPane.showMessageDialog(hungarianFrame,"Ο Παίκτης1 έχει: "+game.pointsOfPlayer(1)+"πόντους\n" + "Ο Παίκτης2 έχει: "+game.pointsOfPlayer(2)+"πόντους\n" + "Ο Παίκτης3 έχει: "+game.pointsOfPlayer(3)+"πόντους\n" + "Ο Παίκτης4 έχει: "+game.pointsOfPlayer(4)+"πόντους"); } else{ JOptionPane.showMessageDialog(hungarianFrame,"Player1 has: "+game.pointsOfPlayer(1)+"points\n" + "Player2 has: "+game.pointsOfPlayer(2)+"points\n" + "Player3 has: "+game.pointsOfPlayer(3)+"points\n" + "Player4 has: "+game.pointsOfPlayer(4)+"points"); } } } /** * @param args the command line arguments */ public static void main(String args[]) { /* Set the Nimbus look and feel */ //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) "> /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel. * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html */ try { for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) { if ("Nimbus".equals(info.getName())) { javax.swing.UIManager.setLookAndFeel(info.getClassName()); break; } } } catch (ClassNotFoundException ex) { java.util.logging.Logger.getLogger(Gui.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (InstantiationException ex) { java.util.logging.Logger.getLogger(Gui.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (IllegalAccessException ex) { java.util.logging.Logger.getLogger(Gui.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (javax.swing.UnsupportedLookAndFeelException ex) { java.util.logging.Logger.getLogger(Gui.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } //</editor-fold> //</editor-fold> /* Create and display the form */ java.awt.EventQueue.invokeLater(new Runnable() { @Override public void run() { Gui gui=new Gui(); gui.setLocationRelativeTo(null); gui.setVisible(true); } }); } // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JLabel bigDomino; private javax.swing.JPanel buttonPanel; private javax.swing.JButton cardGetDomino; private javax.swing.JButton cardinalButton; private javax.swing.JLabel dominoDeck; private javax.swing.JButton exit; private javax.swing.JLabel hungBackround; private javax.swing.JPanel hungPlayer1; private javax.swing.JPanel hungPlayer2; private javax.swing.JPanel hungPlayer3; private javax.swing.JPanel hungPlayer4; private javax.swing.JLabel hungarianBackButton; private javax.swing.JButton hungarianButton; private javax.swing.JPanel hungarianDominoLine; private javax.swing.JFrame hungarianFrame; private javax.swing.JButton hungarianStartButton; private javax.swing.JLabel icon; private javax.swing.JLabel infoCard; private javax.swing.JLabel infoHung; private javax.swing.JLabel infoSolo; private javax.swing.JLabel labelDominoDeck; private javax.swing.JButton line1; private javax.swing.JButton line2; private javax.swing.JButton line3; private javax.swing.JButton line4; private javax.swing.JPanel linePanel; private javax.swing.JLabel message; private javax.swing.JPanel queue1; private javax.swing.JPanel queue2; private javax.swing.JPanel queue3; private javax.swing.JPanel queue4; private javax.swing.JLabel soloBack; private javax.swing.JButton soloButton; private javax.swing.JLabel soloChosenDomino; private javax.swing.JPanel soloDominoDisplay; private javax.swing.JPanel soloDominoLine; private javax.swing.JFrame soloFrame; private javax.swing.JButton soloHint; private javax.swing.JLabel soloIcon; private javax.swing.JLabel soloLineLabel; private javax.swing.JButton soloStartButton; private javax.swing.JPanel whitePanel; // End of variables declaration//GEN-END:variables Locale locale; private Solo1 soloGame; private HungarianMode hungarianGame; private ArrayList<Domino> line; private Domino domino; private HungarianMode game; private Cardinal cardinalGame; javax.swing.JPanel panels[]; }
maliouris/Domino-game
src/javaproject/Gui.java
913
package api; import javax.swing.*; import java.io.BufferedReader; import java.io.FileReader; import java.io.IOException; import java.io.Serializable; import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; /** * Η κλάση αναπαριστά έναν χρήστη με 2 υποκλάσεις, τον Customer {@link api.Customer} * και τον Provider {@link api.Provider}. * Η κλάση είναι εφοδιασμένη με πεδία τα οποία αντιστοιχούν στα στοιχεία ενός χρήστη, καθώς και με βοηθητικές μεθόδους * όπως setters, getters και μεθόδους για την προσθήκη χρηστών, αυθεντικοποίση χρηστών καθώς και αφηρημένες * μεθόδους για τις κλάσεις που την κληρονομούν (Customer & Provider). */ public abstract class User implements Serializable { public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } private String username; private String password; private String name; private String surname; private static HashMap<String, String> users = new HashMap<>(); private static HashSet<String> temp_usernames = new HashSet<>(); private static ArrayList<User> allUsers = new ArrayList<>(); // ArrayList me olous tous Users provider h customers /** * Constructor της User. * @param name Το πρώτο (μικρό) όνομα ενός χρήστη. * @param surname Το επίθετο ενός χρήστη. * @param username Το username ενός χρήστη. * @param password Ο κωδικός πρόσβασης ενός χρήστη. */ public User(String name, String surname, String username, String password) { this.name = name; this.surname = surname; this.username = username; this.password = password; } public String getName() { return this.name; } /** * Μέθοδος που προσθέτει έναν χρήστη στην λίστα λιστών. * @param username Το username του χρήστη * @param password Ο κωδικός του χρήστη */ public static void addUser(String username, String password) { if (!users.containsKey(username)) { users.put(username, password); temp_usernames.add(username); } } /** * Μέθοδος που γεμίζει την λίστα με όλους τους χρήστες βάση ενός αρχείου. */ public static void fillAllUsers() { String line=""; try(BufferedReader myReader = new BufferedReader(new FileReader("Files/users.txt"))) { while((line=myReader.readLine())!=null) { if(line.split(" ")[4].equals("Πάροχος")) { allUsers.add(new Provider(line.split(" ")[2],line.split(" ")[3],line.split(" ")[0],line.split(" ")[1])); } else { allUsers.add(new Customer(line.split(" ")[2],line.split(" ")[3],line.split(" ")[0],line.split(" ")[1])); } } } catch (IOException e) { e.printStackTrace(); } } /** * Μέθοδος που ελέγχει αν ένας χρήστης υπάρχει ήδη (το username είναι πιασμένο). * @param username Το username που να ελεγχθεί. * @return Αν υπάρχει ήδη χρήστης με αυτό το username. */ public static boolean checkIfUserAlreadyExists(String username) { return users.containsKey(username); } /** * Μέθοδος που αυθεντικοποιεί έναν χρήστη. * @param username Το username προς έλεγχο. * @param password Το password προς έλεγχο. * @return Αν υπάρχει χρήστης με αυτόν τον συνδιασμό ονόματος/επιθέτου. */ public static boolean authenticateUser(String username, String password) { return users.containsKey(username) && users.get(username).equals(password); } /** Μέθοδος που βρίσκει έναν συγκεκριμένο user βάση ενός συνδιασμού username: password. @param username Όνομα χρήστη προς έλεγχο. @param password Κωδικός χρήστη προς έλεγχο. @return Αντικέιμενο τύπου User αν υπάρχει User με τον συνδιασμό username: password ,αλλιώς null. */ public static User findUserForLogin(String username, String password) { for(int i=0;i<allUsers.size();i++) { if(allUsers.get(i).getUsername().equals(username) && allUsers.get(i).getPassword().equals(password)) { return allUsers.get(i); } } return null; } public static ArrayList<User> getAllUsers() {return allUsers;} public abstract Object[][] setDataForTable(); public abstract void editAction(int selectedRow, JTable table); public abstract void deleteAction(int selectedRow,JTable table); public abstract double countAverageReviews(); }
StylianosBairamis/oop-myreviews-project
src/api/User.java
914
package unipi.fotistsiou.geographer.controller; import jakarta.validation.Valid; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.validation.BindingResult; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.ModelAttribute; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.PostMapping; import unipi.fotistsiou.geographer.entity.User; import unipi.fotistsiou.geographer.service.UserService; import java.util.Optional; @Controller public class RegisterController { private final UserService userService; @Autowired public RegisterController ( UserService userService ){ this.userService = userService; } @GetMapping("/register/student") public String getRegisterForm(Model model) { User user = new User(); model.addAttribute("user", user); return "register_student"; } @PostMapping("/register/{role}") public String registerUser( @PathVariable String role, @Valid @ModelAttribute("user") User user, BindingResult result, Model model ){ Optional<User> optionalUser = userService.findOneByEmail(user.getEmail()); if (optionalUser.isPresent()) { result.rejectValue("email", "error.email", "Υπάρχει ήδη ένας λογαριασμός εγγεγραμμένος με αυτό το email. Δοκιμάστε με άλλο λογαριασμό email."); } if (result.hasErrors()) { model.addAttribute("user", user); if (role.equals("ROLE_STUDENT")) { return "register_student"; } return "404"; } userService.saveUser(user, role); return "redirect:/login?success_register"; } }
fotistsiou/msc_informatics
4th_semester/plhrofotikh_sthn_ekpaideush/exams_exercise/Geographer/src/main/java/unipi/fotistsiou/geographer/controller/RegisterController.java
915
package gr.aueb.cf.ch5; /** * Παραστάσεις floating point. */ public class FloatingExpressionsApp { public static void main(String[] args) { int intNum = 10; float floatNum = 0.1F; double doubleNum1 = 12.5D; double doubleNum2 = 2D; float floatResult = 0.0F; double doubleResult = 0.0; // Αν υπάρχει ένας float οι μικρότερου μεγέθους τύποι // μετατρέπονται σε float. floatResult = floatNum + intNum; // Αν υπάρχει έστω και ένας double, // τα intNum και floatNum μετατρέπονται σε double doubleResult = doubleNum1 + floatNum * intNum; System.out.printf("flotResult = %f", floatResult); System.out.printf("doubleResult = %f", doubleResult); } }
a8anassis/cf4
src/gr/aueb/cf/ch5/FloatingExpressionsApp.java
916
package org.mockserver.integration.server; import com.google.common.base.Charsets; import com.google.common.net.HttpHeaders; import com.google.common.net.MediaType; import com.google.common.util.concurrent.Uninterruptibles; import org.apache.commons.io.IOUtils; import org.junit.Before; import org.junit.Test; import org.mockserver.client.netty.NettyHttpClient; import org.mockserver.client.netty.SocketConnectionException; import org.mockserver.client.server.MockServerClient; import org.mockserver.echo.http.EchoServer; import org.mockserver.integration.callback.StaticTestExpectationCallback; import org.mockserver.matchers.MatchType; import org.mockserver.matchers.TimeToLive; import org.mockserver.model.*; import org.mockserver.socket.PortFactory; import org.mockserver.socket.SSLFactory; import org.mockserver.streams.IOStreamUtils; import org.mockserver.verify.VerificationTimes; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import javax.net.ssl.SSLSocket; import java.io.IOException; import java.io.OutputStream; import java.net.Socket; import java.net.SocketException; import java.util.*; import java.util.concurrent.*; import static org.hamcrest.Matchers.containsString; import static org.hamcrest.Matchers.lessThan; import static org.hamcrest.core.AnyOf.anyOf; import static org.hamcrest.core.Is.is; import static org.hamcrest.core.StringStartsWith.startsWith; import static org.hamcrest.number.OrderingComparison.greaterThan; import static org.junit.Assert.*; import static org.mockserver.matchers.Times.exactly; import static org.mockserver.matchers.Times.once; import static org.mockserver.model.BinaryBody.binary; import static org.mockserver.model.ConnectionOptions.connectionOptions; import static org.mockserver.model.Cookie.cookie; import static org.mockserver.model.Header.header; import static org.mockserver.model.HttpCallback.callback; import static org.mockserver.model.HttpForward.forward; import static org.mockserver.model.HttpRequest.request; import static org.mockserver.model.HttpResponse.notFoundResponse; import static org.mockserver.model.HttpResponse.response; import static org.mockserver.model.JsonBody.json; import static org.mockserver.model.JsonSchemaBody.jsonSchema; import static org.mockserver.model.NottableString.not; import static org.mockserver.model.NottableString.string; import static org.mockserver.model.OutboundHttpRequest.outboundRequest; import static org.mockserver.model.Parameter.param; import static org.mockserver.model.ParameterBody.params; import static org.mockserver.model.StringBody.exact; import static org.mockserver.model.XPathBody.xpath; /** * @author jamesdbloom */ public abstract class AbstractClientServerIntegrationTest { public static final String TEXT_PLAIN = MediaType.create("text", "plain").toString(); protected static MockServerClient mockServerClient; protected static String servletContext = ""; private final Logger logger = LoggerFactory.getLogger(this.getClass()); protected List<String> headersToIgnore = Arrays.asList( "server", "expires", "date", "host", "connection", "user-agent", "content-length", "accept-encoding", "transfer-encoding" ); private NettyHttpClient httpClient = new NettyHttpClient(); public abstract int getMockServerPort(); public abstract int getMockServerSecurePort(); public abstract int getTestServerPort(); protected String calculatePath(String path) { return "/" + path; } @Before public void resetServer() { mockServerClient.reset(); } @Test public void shouldForwardRequestInHTTP() { // when mockServerClient .when( request() .withPath(calculatePath("echo")) ) .forward( forward() .withHost("127.0.0.1") .withPort(getTestServerPort()) ); // then // - in http assertEquals( response() .withStatusCode(HttpStatusCode.OK_200.code()) .withHeaders( header("x-test", "test_headers_and_body"), header(HttpHeaders.CONTENT_TYPE, TEXT_PLAIN) ) .withBody("an_example_body_http"), makeRequest( request() .withPath(calculatePath("echo")) .withMethod("POST") .withHeaders( header("x-test", "test_headers_and_body") ) .withBody("an_example_body_http"), headersToIgnore) ); // - in https assertEquals( response() .withStatusCode(HttpStatusCode.OK_200.code()) .withHeaders( header("x-test", "test_headers_and_body"), header(HttpHeaders.CONTENT_TYPE, TEXT_PLAIN) ) .withBody("an_example_body_https"), makeRequest( request() .withSecure(true) .withPath(calculatePath("echo")) .withMethod("POST") .withHeaders( header("x-test", "test_headers_and_body") ) .withBody("an_example_body_https"), headersToIgnore) ); } @Test public void shouldForwardRequestInHTTPS() { int testServerHttpsPort = PortFactory.findFreePort(); EchoServer secureEchoServer = new EchoServer(testServerHttpsPort, true); try { // when mockServerClient .when( request() .withPath(calculatePath("echo")) ) .forward( forward() .withHost("127.0.0.1") .withPort(testServerHttpsPort) .withScheme(HttpForward.Scheme.HTTPS) ); // then // - in http assertEquals( response() .withStatusCode(HttpStatusCode.OK_200.code()) .withHeaders( header("x-test", "test_headers_and_body"), header(HttpHeaders.CONTENT_TYPE, TEXT_PLAIN) ) .withBody("an_example_body_http"), makeRequest( request() .withPath(calculatePath("echo")) .withMethod("POST") .withHeaders( header("x-test", "test_headers_and_body") ) .withBody("an_example_body_http"), headersToIgnore) ); // - in https assertEquals( response() .withStatusCode(HttpStatusCode.OK_200.code()) .withHeaders( header("x-test", "test_headers_and_body"), header(HttpHeaders.CONTENT_TYPE, TEXT_PLAIN) ) .withBody("an_example_body_https"), makeRequest( request() .withSecure(true) .withPath(calculatePath("echo")) .withMethod("POST") .withHeaders( header("x-test", "test_headers_and_body") ) .withBody("an_example_body_https"), headersToIgnore) ); } finally { secureEchoServer.stop(); } } @Test public void shouldAllowSimultaneousForwardAndResponseExpectations() { // when mockServerClient .when( request() .withPath(calculatePath("echo")), once() ) .forward( forward() .withHost("127.0.0.1") .withPort(getTestServerPort()) ); mockServerClient .when( request() .withPath(calculatePath("test_headers_and_body")), once() ) .respond( response() .withBody("some_body") ); // then // - forward assertEquals( response() .withStatusCode(HttpStatusCode.OK_200.code()) .withHeaders( header("x-test", "test_headers_and_body"), header(HttpHeaders.CONTENT_TYPE, TEXT_PLAIN) ) .withBody("an_example_body"), makeRequest( request() .withPath(calculatePath("echo")) .withMethod("POST") .withHeaders( header("x-test", "test_headers_and_body") ) .withBody("an_example_body"), headersToIgnore) ); // - respond assertEquals( response() .withHeader(HttpHeaders.CONTENT_TYPE, TEXT_PLAIN) .withStatusCode(HttpStatusCode.OK_200.code()) .withBody("some_body"), makeRequest( request() .withPath(calculatePath("test_headers_and_body")), headersToIgnore) ); // - no response or forward assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()), makeRequest( request() .withPath(calculatePath("test_headers_and_body")), headersToIgnore) ); } @Test public void shouldCallbackToSpecifiedClassWithPrecannedResponse() { // when mockServerClient .when( request() .withPath(calculatePath("callback")) ) .callback( callback() .withCallbackClass("org.mockserver.integration.callback.PrecannedTestExpectationCallback") ); // then // - in http assertEquals( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withHeaders( header("x-callback", "test_callback_header"), header(HttpHeaders.CONTENT_TYPE, TEXT_PLAIN) ) .withBody("a_callback_response"), makeRequest( request() .withPath(calculatePath("callback")) .withMethod("POST") .withHeaders( header("x-test", "test_headers_and_body") ) .withBody("an_example_body_http"), headersToIgnore ) ); // - in https assertEquals( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withHeaders( header("x-callback", "test_callback_header"), header(HttpHeaders.CONTENT_TYPE, TEXT_PLAIN) ) .withBody("a_callback_response"), makeRequest( request() .withSecure(true) .withPath(calculatePath("callback")) .withMethod("POST") .withHeaders( header("x-test", "test_headers_and_body") ) .withBody("an_example_body_https"), headersToIgnore ) ); } @Test public void shouldReturnResponseWithOnlyBody() { // when mockServerClient.when(request()).respond(response().withBody("some_body")); // then // - in http assertEquals( response() .withHeader(HttpHeaders.CONTENT_TYPE, TEXT_PLAIN) .withStatusCode(HttpStatusCode.OK_200.code()) .withBody("some_body"), makeRequest( request() .withPath(calculatePath("")), headersToIgnore) ); // - in https assertEquals( response() .withHeader(HttpHeaders.CONTENT_TYPE, TEXT_PLAIN) .withStatusCode(HttpStatusCode.OK_200.code()) .withBody("some_body"), makeRequest( request() .withSecure(true) .withPath(calculatePath("")), headersToIgnore) ); } @Test public void shouldReturnResponseForRequestInSsl() { // when mockServerClient.when(request().withSecure(true)).respond(response().withBody("some_body")); // then // - in http assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()), makeRequest( request() .withPath(calculatePath("")), headersToIgnore) ); // - in https assertEquals( response() .withHeader(HttpHeaders.CONTENT_TYPE, TEXT_PLAIN) .withStatusCode(HttpStatusCode.OK_200.code()) .withBody("some_body"), makeRequest( request() .withSecure(true) .withPath(calculatePath("")), headersToIgnore) ); } @Test public void shouldReturnResponseForRequestNotInSsl() { // when mockServerClient.when(request().withSecure(false)).respond(response().withBody("some_body")); // then // - in http assertEquals( response() .withHeader(HttpHeaders.CONTENT_TYPE, TEXT_PLAIN) .withStatusCode(HttpStatusCode.OK_200.code()) .withBody("some_body"), makeRequest( request() .withPath(calculatePath("")), headersToIgnore) ); // - in https assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()), makeRequest( request() .withSecure(true) .withPath(calculatePath("")), headersToIgnore) ); } @Test public void shouldReturnMatchRequestWithBodyInUTF16() { // when String body = "我说中国话"; mockServerClient.when(request().withBody(body, Charsets.UTF_16)).respond(response().withBody(body, Charsets.UTF_8)); // then // - in http assertEquals( response() .withHeader(HttpHeaders.CONTENT_TYPE, MediaType.create("text", "plain").withCharset(Charsets.UTF_8).toString()) .withStatusCode(HttpStatusCode.OK_200.code()) .withBody(body), makeRequest( request() .withPath(calculatePath("")) .withBody(body, Charsets.UTF_16), headersToIgnore) ); // - in https assertEquals( response() .withHeader(HttpHeaders.CONTENT_TYPE, MediaType.create("text", "plain").withCharset(Charsets.UTF_8).toString()) .withStatusCode(HttpStatusCode.OK_200.code()) .withBody(body), makeRequest( request() .withSecure(true) .withPath(calculatePath("")) .withBody(body, Charsets.UTF_16), headersToIgnore) ); } @Test public void shouldReturnMatchRequestWithBodyInUTF16WithContentTypeHeader() { // when String body = "我说中国话"; mockServerClient .when( request() .withHeader(HttpHeaders.CONTENT_TYPE, MediaType.create("text", "plain").withCharset(Charsets.UTF_8).toString()) .withBody(body) ) .respond( response() .withBody(body, Charsets.UTF_8) ); // then // - in http assertEquals( response() .withHeader(HttpHeaders.CONTENT_TYPE, MediaType.create("text", "plain").withCharset(Charsets.UTF_8).toString()) .withStatusCode(HttpStatusCode.OK_200.code()) .withBody(body), makeRequest( request() .withHeader(HttpHeaders.CONTENT_TYPE, MediaType.create("text", "plain").withCharset(Charsets.UTF_8).toString()) .withPath(calculatePath("")) .withBody(body), headersToIgnore) ); // - in https assertEquals( response() .withHeader(HttpHeaders.CONTENT_TYPE, MediaType.create("text", "plain").withCharset(Charsets.UTF_8).toString()) .withStatusCode(HttpStatusCode.OK_200.code()) .withBody(body), makeRequest( request() .withHeader(HttpHeaders.CONTENT_TYPE, MediaType.create("text", "plain").withCharset(Charsets.UTF_8).toString()) .withSecure(true) .withPath(calculatePath("")) .withBody(body), headersToIgnore) ); } @Test public void shouldReturnResponseWithBodyInUTF8() { // when String body = "我说中国话"; mockServerClient.when(request()).respond(response().withBody(body, Charsets.UTF_16)); // then // - in http assertEquals( response() .withHeader(HttpHeaders.CONTENT_TYPE, MediaType.create("text", "plain").withCharset(Charsets.UTF_16).toString()) .withStatusCode(HttpStatusCode.OK_200.code()) .withBody(body), makeRequest( request() .withPath(calculatePath("")), headersToIgnore) ); // - in https assertEquals( response() .withHeader(HttpHeaders.CONTENT_TYPE, MediaType.create("text", "plain").withCharset(Charsets.UTF_16).toString()) .withStatusCode(HttpStatusCode.OK_200.code()) .withBody(body), makeRequest( request() .withSecure(true) .withPath(calculatePath("")), headersToIgnore) ); } @Test public void shouldReturnResponseWithBodyInUTF16WithContentTypeHeader() { // when String body = "我说中国话"; mockServerClient .when( request() ) .respond( response() .withHeader(HttpHeaders.CONTENT_TYPE, MediaType.create("text", "plain").withCharset(Charsets.UTF_8).toString()) .withBody(body) ); // then // - in http assertEquals( response() .withHeader(HttpHeaders.CONTENT_TYPE, MediaType.create("text", "plain").withCharset(Charsets.UTF_8).toString()) .withStatusCode(HttpStatusCode.OK_200.code()) .withBody(body), makeRequest( request() .withPath(calculatePath("")), headersToIgnore) ); // - in https assertEquals( response() .withHeader(HttpHeaders.CONTENT_TYPE, MediaType.create("text", "plain").withCharset(Charsets.UTF_8).toString()) .withStatusCode(HttpStatusCode.OK_200.code()) .withBody(body), makeRequest( request() .withSecure(true) .withPath(calculatePath("")), headersToIgnore) ); } @Test public void shouldReturnResponseWithOnlyStatusCode() { // when mockServerClient .when( request() .withMethod("POST") .withPath(calculatePath("some_path")) ) .respond( response() .withStatusCode(200) ); // then // - in http assertEquals( response() .withStatusCode(HttpStatusCode.OK_200.code()), makeRequest( request() .withPath(calculatePath("some_path")) .withMethod("POST"), headersToIgnore) ); // - in https assertEquals( response() .withStatusCode(HttpStatusCode.OK_200.code()), makeRequest( request() .withSecure(true) .withPath(calculatePath("some_path")) .withMethod("POST"), headersToIgnore) ); } @Test public void shouldVerifyReceivedRequests() { // when mockServerClient .when( request() .withPath(calculatePath("some_path")), exactly(2) ) .respond( response() .withBody("some_body") ); // then // - in http assertEquals( response() .withHeader(HttpHeaders.CONTENT_TYPE, TEXT_PLAIN) .withStatusCode(HttpStatusCode.OK_200.code()) .withBody("some_body"), makeRequest( request() .withPath(calculatePath("some_path")), headersToIgnore) ); mockServerClient.verify(request() .withPath(calculatePath("some_path"))); mockServerClient.verify(request() .withPath(calculatePath("some_path")), VerificationTimes.exactly(1)); // - in https assertEquals( response() .withHeader(HttpHeaders.CONTENT_TYPE, TEXT_PLAIN) .withStatusCode(HttpStatusCode.OK_200.code()) .withBody("some_body"), makeRequest( request() .withSecure(true) .withPath(calculatePath("some_path")), headersToIgnore) ); mockServerClient.verify(request().withPath(calculatePath("some_path")), VerificationTimes.atLeast(1)); mockServerClient.verify(request().withPath(calculatePath("some_path")), VerificationTimes.exactly(2)); } @Test public void shouldVerifyReceivedRequestInSsl() { // when mockServerClient .when( request() .withPath(calculatePath("some.*path")), exactly(2) ) .respond( response() .withBody("some_body") ); // then // - in http assertEquals( response() .withHeader(HttpHeaders.CONTENT_TYPE, TEXT_PLAIN) .withStatusCode(HttpStatusCode.OK_200.code()) .withBody("some_body"), makeRequest( request() .withPath(calculatePath("some_path")), headersToIgnore) ); mockServerClient.verify(request() .withPath(calculatePath("some_path")) .withSecure(false)); mockServerClient.verify(request() .withPath(calculatePath("some_path")) .withSecure(false), VerificationTimes.exactly(1)); // - in https assertEquals( response() .withHeader(HttpHeaders.CONTENT_TYPE, TEXT_PLAIN) .withStatusCode(HttpStatusCode.OK_200.code()) .withBody("some_body"), makeRequest( request() .withPath(calculatePath("some_secure_path")) .withSecure(true), headersToIgnore) ); mockServerClient.verify(request() .withPath(calculatePath("some_secure_path")) .withSecure(true)); mockServerClient.verify(request() .withPath(calculatePath("some_secure_path")) .withSecure(true), VerificationTimes.exactly(1)); } @Test public void shouldVerifyReceivedRequestsWithNoBody() { // when mockServerClient.when(request().withPath(calculatePath("some_path")), exactly(2)).respond(response()); // then // - in http assertEquals( response() .withStatusCode(HttpStatusCode.OK_200.code()), makeRequest( request() .withPath(calculatePath("some_path")), headersToIgnore) ); mockServerClient.verify(request() .withPath(calculatePath("some_path"))); mockServerClient.verify(request() .withPath(calculatePath("some_path")), VerificationTimes.exactly(1)); } @Test public void shouldVerifyNotEnoughRequestsReceived() { // when mockServerClient.when(request().withPath(calculatePath("some_path")), exactly(2)).respond(response().withBody("some_body")); // then assertEquals( response() .withHeader(HttpHeaders.CONTENT_TYPE, TEXT_PLAIN) .withStatusCode(HttpStatusCode.OK_200.code()) .withBody("some_body"), makeRequest( request() .withPath(calculatePath("some_path")), headersToIgnore) ); try { mockServerClient.verify(request() .withPath(calculatePath("some_path")), VerificationTimes.atLeast(2)); fail(); } catch (AssertionError ae) { assertThat(ae.getMessage(), startsWith("Request not found at least 2 times, expected:<{" + System.getProperty("line.separator") + " \"path\" : \"" + calculatePath("some_path") + "\"" + System.getProperty("line.separator") + "}> but was:<{" + System.getProperty("line.separator") + " \"method\" : \"GET\"," + System.getProperty("line.separator") + " \"path\" : \"" + calculatePath("some_path") + "\"," + System.getProperty("line.separator"))); } } @Test public void shouldVerifyTooManyRequestsReceived() { // when mockServerClient.when(request().withPath(calculatePath("some_path")), exactly(2)).respond(response().withBody("some_body")); // then assertEquals( response() .withHeader(HttpHeaders.CONTENT_TYPE, TEXT_PLAIN) .withStatusCode(HttpStatusCode.OK_200.code()) .withBody("some_body"), makeRequest( request() .withPath(calculatePath("some_path")), headersToIgnore) ); try { mockServerClient.verify(request() .withPath(calculatePath("some_path")), VerificationTimes.exactly(0)); fail(); } catch (AssertionError ae) { assertThat(ae.getMessage(), startsWith("Request not found exactly 0 times, expected:<{" + System.getProperty("line.separator") + " \"path\" : \"" + calculatePath("some_path") + "\"" + System.getProperty("line.separator") + "}> but was:<{" + System.getProperty("line.separator") + " \"method\" : \"GET\"," + System.getProperty("line.separator") + " \"path\" : \"" + calculatePath("some_path") + "\"," + System.getProperty("line.separator"))); } } @Test public void shouldVerifyNoMatchingRequestsReceived() { // when mockServerClient.when(request().withPath(calculatePath("some_path")), exactly(2)).respond(response().withBody("some_body")); // then assertEquals( response() .withHeader(HttpHeaders.CONTENT_TYPE, TEXT_PLAIN) .withStatusCode(HttpStatusCode.OK_200.code()) .withBody("some_body"), makeRequest( request() .withPath(calculatePath("some_path")), headersToIgnore) ); try { mockServerClient.verify(request() .withPath(calculatePath("some_other_path")), VerificationTimes.exactly(2)); fail(); } catch (AssertionError ae) { assertThat(ae.getMessage(), startsWith("Request not found exactly 2 times, expected:<{" + System.getProperty("line.separator") + " \"path\" : \"" + calculatePath("some_other_path") + "\"" + System.getProperty("line.separator") + "}> but was:<{" + System.getProperty("line.separator") + " \"method\" : \"GET\"," + System.getProperty("line.separator") + " \"path\" : \"" + calculatePath("some_path") + "\"," + System.getProperty("line.separator"))); } } @Test public void shouldVerifyNoMatchingRequestsReceivedInSsl() { // when mockServerClient.when(request().withPath(calculatePath("some.*path")), exactly(2)).respond(response().withBody("some_body")); // then // - in http assertEquals( response() .withHeader(HttpHeaders.CONTENT_TYPE, TEXT_PLAIN) .withStatusCode(HttpStatusCode.OK_200.code()) .withBody("some_body"), makeRequest( request() .withPath(calculatePath("some_path")), headersToIgnore) ); try { mockServerClient.verify( request() .withPath(calculatePath("some_path")) .withSecure(true), VerificationTimes.atLeast(1) ); fail(); } catch (AssertionError ae) { assertThat(ae.getMessage(), startsWith("Request not found at least once, expected:<{" + System.getProperty("line.separator") + " \"path\" : \"" + calculatePath("some_path") + "\"," + System.getProperty("line.separator") + " \"secure\" : true" + System.getProperty("line.separator") + "}> but was:<{" + System.getProperty("line.separator") + " \"method\" : \"GET\"," + System.getProperty("line.separator") + " \"path\" : \"" + calculatePath("some_path") + "\"," + System.getProperty("line.separator"))); } // - in https assertEquals( response() .withHeader(HttpHeaders.CONTENT_TYPE, TEXT_PLAIN) .withStatusCode(HttpStatusCode.OK_200.code()) .withBody("some_body"), makeRequest( request() .withPath(calculatePath("some_secure_path")) .withSecure(true), headersToIgnore) ); try { mockServerClient.verify( request() .withPath(calculatePath("some_secure_path")) .withSecure(false), VerificationTimes.atLeast(1) ); fail(); } catch (AssertionError ae) { assertThat(ae.getMessage(), startsWith("Request not found at least once, expected:<{" + System.getProperty("line.separator") + " \"path\" : \"" + calculatePath("some_secure_path") + "\"," + System.getProperty("line.separator") + " \"secure\" : false" + System.getProperty("line.separator") + "}> but was:<[ {" + System.getProperty("line.separator") + " \"method\" : \"GET\"," + System.getProperty("line.separator") + " \"path\" : \"" + calculatePath("some_path") + "\"," + System.getProperty("line.separator"))); } } @Test public void shouldVerifySequenceOfRequestsReceived() { // when mockServerClient.when(request().withPath(calculatePath("some_path.*")), exactly(6)).respond(response().withBody("some_body")); // then // - in http assertEquals( response("some_body").withHeader(HttpHeaders.CONTENT_TYPE, TEXT_PLAIN), makeRequest( request().withPath(calculatePath("some_path_one")), headersToIgnore) ); assertEquals( response("some_body").withHeader(HttpHeaders.CONTENT_TYPE, TEXT_PLAIN), makeRequest( request().withPath(calculatePath("some_path_two")), headersToIgnore) ); assertEquals( response("some_body").withHeader(HttpHeaders.CONTENT_TYPE, TEXT_PLAIN), makeRequest( request().withPath(calculatePath("some_path_three")), headersToIgnore) ); mockServerClient.verify(request(calculatePath("some_path_one")), request(calculatePath("some_path_three"))); mockServerClient.verify(request(calculatePath("some_path_one")), request(calculatePath("some_path_two"))); mockServerClient.verify(request(calculatePath("some_path_one")), request(calculatePath("some_path_two")), request(calculatePath("some_path_three"))); // - in https assertEquals( response("some_body").withHeader(HttpHeaders.CONTENT_TYPE, TEXT_PLAIN), makeRequest( request().withSecure(true) .withPath(calculatePath("some_path_one")), headersToIgnore) ); assertEquals( response("some_body").withHeader(HttpHeaders.CONTENT_TYPE, TEXT_PLAIN), makeRequest( request().withSecure(true) .withPath(calculatePath("some_path_two")), headersToIgnore) ); assertEquals( response("some_body").withHeader(HttpHeaders.CONTENT_TYPE, TEXT_PLAIN), makeRequest( request().withSecure(true) .withPath(calculatePath("some_path_three")), headersToIgnore) ); mockServerClient.verify(request(calculatePath("some_path_one")), request(calculatePath("some_path_three"))); mockServerClient.verify(request(calculatePath("some_path_one")), request(calculatePath("some_path_two"))); mockServerClient.verify(request(calculatePath("some_path_one")), request(calculatePath("some_path_two")), request(calculatePath("some_path_three"))); } @Test public void shouldVerifySequenceOfRequestsReceivedIncludingThoseNotMatchingAnException() { // when mockServerClient.when(request().withPath(calculatePath("some_path.*")), exactly(4)).respond(response().withBody("some_body")); // then // - in http assertEquals( response("some_body").withHeader(HttpHeaders.CONTENT_TYPE, TEXT_PLAIN), makeRequest( request().withPath(calculatePath("some_path_one")), headersToIgnore) ); assertEquals( notFoundResponse(), makeRequest( request().withPath(calculatePath("not_found")), headersToIgnore) ); assertEquals( response("some_body").withHeader(HttpHeaders.CONTENT_TYPE, TEXT_PLAIN), makeRequest( request().withPath(calculatePath("some_path_three")), headersToIgnore) ); mockServerClient.verify(request(calculatePath("some_path_one")), request(calculatePath("some_path_three"))); mockServerClient.verify(request(calculatePath("some_path_one")), request(calculatePath("not_found"))); mockServerClient.verify(request(calculatePath("some_path_one")), request(calculatePath("not_found")), request(calculatePath("some_path_three"))); // - in https assertEquals( response("some_body").withHeader(HttpHeaders.CONTENT_TYPE, TEXT_PLAIN), makeRequest( request().withSecure(true) .withPath(calculatePath("some_path_one")), headersToIgnore) ); assertEquals( notFoundResponse(), makeRequest( request().withSecure(true) .withPath(calculatePath("not_found")), headersToIgnore) ); assertEquals( response("some_body").withHeader(HttpHeaders.CONTENT_TYPE, TEXT_PLAIN), makeRequest( request().withSecure(true) .withPath(calculatePath("some_path_three")), headersToIgnore) ); mockServerClient.verify(request(calculatePath("some_path_one")), request(calculatePath("some_path_three"))); mockServerClient.verify(request(calculatePath("some_path_one")), request(calculatePath("not_found"))); mockServerClient.verify(request(calculatePath("some_path_one")), request(calculatePath("not_found")), request(calculatePath("some_path_three"))); } @Test public void shouldVerifySequenceOfRequestsNotReceived() { // when mockServerClient.when(request().withPath(calculatePath("some_path.*")), exactly(6)).respond(response().withBody("some_body")); // then // - in http assertEquals( response("some_body").withHeader(HttpHeaders.CONTENT_TYPE, TEXT_PLAIN), makeRequest( request().withPath(calculatePath("some_path_one")), headersToIgnore) ); assertEquals( response("some_body").withHeader(HttpHeaders.CONTENT_TYPE, TEXT_PLAIN), makeRequest( request().withPath(calculatePath("some_path_two")), headersToIgnore) ); assertEquals( response("some_body").withHeader(HttpHeaders.CONTENT_TYPE, TEXT_PLAIN), makeRequest( request().withPath(calculatePath("some_path_three")), headersToIgnore) ); try { mockServerClient.verify(request(calculatePath("some_path_two")), request(calculatePath("some_path_one"))); fail(); } catch (AssertionError ae) { assertThat(ae.getMessage(), startsWith("Request sequence not found, expected:<[ {" + System.getProperty("line.separator") + " \"path\" : \"" + calculatePath("some_path_two") + "\"" + System.getProperty("line.separator") + "}, {" + System.getProperty("line.separator") + " \"path\" : \"" + calculatePath("some_path_one") + "\"" + System.getProperty("line.separator") + "} ]> but was:<[ {" + System.getProperty("line.separator") + " \"method\" : \"GET\"," + System.getProperty("line.separator") + " \"path\" : \"" + calculatePath("some_path_one") + "\"," + System.getProperty("line.separator"))); } try { mockServerClient.verify(request(calculatePath("some_path_three")), request(calculatePath("some_path_two"))); fail(); } catch (AssertionError ae) { assertThat(ae.getMessage(), startsWith("Request sequence not found, expected:<[ {" + System.getProperty("line.separator") + " \"path\" : \"" + calculatePath("some_path_three") + "\"" + System.getProperty("line.separator") + "}, {" + System.getProperty("line.separator") + " \"path\" : \"" + calculatePath("some_path_two") + "\"" + System.getProperty("line.separator") + "} ]> but was:<[ {" + System.getProperty("line.separator") + " \"method\" : \"GET\"," + System.getProperty("line.separator") + " \"path\" : \"" + calculatePath("some_path_one") + "\"," + System.getProperty("line.separator"))); } try { mockServerClient.verify(request(calculatePath("some_path_four"))); fail(); } catch (AssertionError ae) { assertThat(ae.getMessage(), startsWith("Request sequence not found, expected:<[ {" + System.getProperty("line.separator") + " \"path\" : \"" + calculatePath("some_path_four") + "\"" + System.getProperty("line.separator") + "} ]> but was:<[ {" + System.getProperty("line.separator") + " \"method\" : \"GET\"," + System.getProperty("line.separator") + " \"path\" : \"" + calculatePath("some_path_one") + "\"," + System.getProperty("line.separator"))); } } @Test public void shouldReturnResponseByMatchingPath() { // when mockServerClient .when( request() .withPath(calculatePath("some_path1")) ) .respond( response() .withBody("some_body1") ); mockServerClient .when( request() .withPath(calculatePath("some_path2")) ) .respond( response() .withBody("some_body2") ); // then // - in http assertEquals( response() .withHeader(HttpHeaders.CONTENT_TYPE, TEXT_PLAIN) .withStatusCode(HttpStatusCode.OK_200.code()) .withBody("some_body2"), makeRequest( request() .withPath(calculatePath("some_path2")), headersToIgnore) ); assertEquals( response() .withHeader(HttpHeaders.CONTENT_TYPE, TEXT_PLAIN) .withStatusCode(HttpStatusCode.OK_200.code()) .withBody("some_body1"), makeRequest( request() .withPath(calculatePath("some_path1")), headersToIgnore) ); // - in https assertEquals( response() .withHeader(HttpHeaders.CONTENT_TYPE, TEXT_PLAIN) .withStatusCode(HttpStatusCode.OK_200.code()) .withBody("some_body2"), makeRequest( request() .withSecure(true) .withPath(calculatePath("some_path2")), headersToIgnore) ); assertEquals( response() .withHeader(HttpHeaders.CONTENT_TYPE, TEXT_PLAIN) .withStatusCode(HttpStatusCode.OK_200.code()) .withBody("some_body1"), makeRequest( request() .withSecure(true) .withPath(calculatePath("some_path1")), headersToIgnore) ); } @Test public void shouldReturnResponseByMatchingPathExactTimes() { // when mockServerClient .when( request() .withPath(calculatePath("some_path")), exactly(2) ) .respond( response() .withBody("some_body") ); // then // - in http assertEquals( response() .withHeader(HttpHeaders.CONTENT_TYPE, TEXT_PLAIN) .withStatusCode(HttpStatusCode.OK_200.code()) .withBody("some_body"), makeRequest( request() .withPath(calculatePath("some_path")), headersToIgnore) ); // - in https assertEquals( response() .withHeader(HttpHeaders.CONTENT_TYPE, TEXT_PLAIN) .withStatusCode(HttpStatusCode.OK_200.code()) .withBody("some_body"), makeRequest( request() .withSecure(true) .withPath(calculatePath("some_path")), headersToIgnore) ); // - in http assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()), makeRequest( request() .withPath(calculatePath("some_path")), headersToIgnore) ); // - in https assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()), makeRequest( request() .withSecure(true) .withPath(calculatePath("some_path")), headersToIgnore) ); } @Test public void shouldReturnResponseWhenTimeToLiveHasNotExpired() { // when mockServerClient .when( request().withPath(calculatePath("some_path")), exactly(2), TimeToLive.exactly(TimeUnit.HOURS, 1L) ) .respond( response().withBody("some_body") ); // then // - in http assertEquals( response() .withHeader(HttpHeaders.CONTENT_TYPE, TEXT_PLAIN) .withStatusCode(HttpStatusCode.OK_200.code()) .withBody("some_body"), makeRequest( request() .withPath(calculatePath("some_path")), headersToIgnore) ); // - in https assertEquals( response() .withHeader(HttpHeaders.CONTENT_TYPE, TEXT_PLAIN) .withStatusCode(HttpStatusCode.OK_200.code()) .withBody("some_body"), makeRequest( request() .withSecure(true) .withPath(calculatePath("some_path")), headersToIgnore) ); // - in http assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()), makeRequest( request() .withPath(calculatePath("some_path")), headersToIgnore) ); // - in https assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()), makeRequest( request() .withSecure(true) .withPath(calculatePath("some_path")), headersToIgnore) ); } @Test public void shouldReturnResponseByMatchingBodyWithXPath() { // when mockServerClient.when(request().withBody(xpath("/bookstore/book[price>30]/price")), exactly(2)).respond(response().withBody("some_body")); // then // - in http assertEquals( response() .withHeader(HttpHeaders.CONTENT_TYPE, TEXT_PLAIN) .withStatusCode(HttpStatusCode.OK_200.code()) .withBody("some_body"), makeRequest( request() .withPath(calculatePath("some_path")) .withMethod("POST") .withBody(new StringBody("" + "<?xml version=\"1.0\" encoding=\"ISO-8859-1\"?>" + System.getProperty("line.separator") + "<bookstore>" + System.getProperty("line.separator") + " <book category=\"COOKING\">" + System.getProperty("line.separator") + " <title lang=\"en\">Everyday Italian</title>" + System.getProperty("line.separator") + " <author>Giada De Laurentiis</author>" + System.getProperty("line.separator") + " <year>2005</year>" + System.getProperty("line.separator") + " <price>30.00</price>" + System.getProperty("line.separator") + " </book>" + System.getProperty("line.separator") + " <book category=\"CHILDREN\">" + System.getProperty("line.separator") + " <title lang=\"en\">Harry Potter</title>" + System.getProperty("line.separator") + " <author>J K. Rowling</author>" + System.getProperty("line.separator") + " <year>2005</year>" + System.getProperty("line.separator") + " <price>29.99</price>" + System.getProperty("line.separator") + " </book>" + System.getProperty("line.separator") + " <book category=\"WEB\">" + System.getProperty("line.separator") + " <title lang=\"en\">Learning XML</title>" + System.getProperty("line.separator") + " <author>Erik T. Ray</author>" + System.getProperty("line.separator") + " <year>2003</year>" + System.getProperty("line.separator") + " <price>31.95</price>" + System.getProperty("line.separator") + " </book>" + System.getProperty("line.separator") + "</bookstore>")), headersToIgnore) ); // - in https assertEquals( response() .withHeader(HttpHeaders.CONTENT_TYPE, TEXT_PLAIN) .withStatusCode(HttpStatusCode.OK_200.code()) .withBody("some_body"), makeRequest( request() .withSecure(true) .withPath(calculatePath("some_path")) .withMethod("POST") .withBody(new StringBody("" + "<?xml version=\"1.0\" encoding=\"ISO-8859-1\"?>" + System.getProperty("line.separator") + "<bookstore>" + System.getProperty("line.separator") + " <book category=\"COOKING\">" + System.getProperty("line.separator") + " <title lang=\"en\">Everyday Italian</title>" + System.getProperty("line.separator") + " <author>Giada De Laurentiis</author>" + System.getProperty("line.separator") + " <year>2005</year>" + System.getProperty("line.separator") + " <price>30.00</price>" + System.getProperty("line.separator") + " </book>" + System.getProperty("line.separator") + " <book category=\"CHILDREN\">" + System.getProperty("line.separator") + " <title lang=\"en\">Harry Potter</title>" + System.getProperty("line.separator") + " <author>J K. Rowling</author>" + System.getProperty("line.separator") + " <year>2005</year>" + System.getProperty("line.separator") + " <price>29.99</price>" + System.getProperty("line.separator") + " </book>" + System.getProperty("line.separator") + " <book category=\"WEB\">" + System.getProperty("line.separator") + " <title lang=\"en\">Learning XML</title>" + System.getProperty("line.separator") + " <author>Erik T. Ray</author>" + System.getProperty("line.separator") + " <year>2003</year>" + System.getProperty("line.separator") + " <price>31.95</price>" + System.getProperty("line.separator") + " </book>" + System.getProperty("line.separator") + "</bookstore>")), headersToIgnore) ); } @Test public void shouldReturnResponseByMatchingBodyWithJson() { // when mockServerClient .when( request() .withBody(json("{" + System.getProperty("line.separator") + " \"id\": 1," + System.getProperty("line.separator") + " \"name\": \"A green door\"," + System.getProperty("line.separator") + " \"price\": 12.50," + System.getProperty("line.separator") + " \"tags\": [\"home\", \"green\"]" + System.getProperty("line.separator") + "}")), exactly(2) ) .respond( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body") ); // then // - in http assertEquals( response() .withHeader(HttpHeaders.CONTENT_TYPE, TEXT_PLAIN) .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body"), makeRequest( request() .withPath(calculatePath("some_path")) .withMethod("POST") .withBody("{" + System.getProperty("line.separator") + " \"id\": 1," + System.getProperty("line.separator") + " \"extra ignored field\": \"some value\"," + System.getProperty("line.separator") + " \"name\": \"A green door\"," + System.getProperty("line.separator") + " \"price\": 12.50," + System.getProperty("line.separator") + " \"tags\": [\"home\", \"green\"]" + System.getProperty("line.separator") + "}"), headersToIgnore) ); // - in https assertEquals( response() .withHeader(HttpHeaders.CONTENT_TYPE, TEXT_PLAIN) .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body"), makeRequest( request() .withSecure(true) .withPath(calculatePath("some_path")) .withMethod("POST") .withBody("{" + System.getProperty("line.separator") + " \"id\": 1," + System.getProperty("line.separator") + " \"extra ignored array\": [\"one\", \"two\"]," + System.getProperty("line.separator") + " \"name\": \"A green door\"," + System.getProperty("line.separator") + " \"price\": 12.50," + System.getProperty("line.separator") + " \"tags\": [\"home\", \"green\"]" + System.getProperty("line.separator") + "}"), headersToIgnore) ); } @Test public void shouldReturnResponseByMatchingBodyWithJsonWithCharsetUTF8() { // when mockServerClient .when( request() .withBody(json("{" + System.getProperty("line.separator") + " \"ταυτότητα\": 1," + System.getProperty("line.separator") + " \"όνομα\": \"μια πράσινη πόρτα\"," + System.getProperty("line.separator") + " \"τιμή\": 12.50," + System.getProperty("line.separator") + " \"ετικέτες\": [\"σπίτι\", \"πράσινος\"]" + System.getProperty("line.separator") + "}", Charsets.UTF_16, MatchType.ONLY_MATCHING_FIELDS)), exactly(2) ) .respond( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body") ); // then // - in http assertEquals( response() .withHeader(HttpHeaders.CONTENT_TYPE, TEXT_PLAIN) .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body"), makeRequest( request() .withPath(calculatePath("some_path")) .withMethod("POST") .withBody(json("{" + System.getProperty("line.separator") + " \"ταυτότητα\": 1," + System.getProperty("line.separator") + " \"επιπλέον αγνοούνται τομέα\": \"κάποια αξία\"," + System.getProperty("line.separator") + " \"όνομα\": \"μια πράσινη πόρτα\"," + System.getProperty("line.separator") + " \"τιμή\": 12.50," + System.getProperty("line.separator") + " \"ετικέτες\": [\"σπίτι\", \"πράσινος\"]" + System.getProperty("line.separator") + "}", Charsets.UTF_16, MatchType.ONLY_MATCHING_FIELDS)), headersToIgnore) ); // - in https assertEquals( response() .withHeader(HttpHeaders.CONTENT_TYPE, TEXT_PLAIN) .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body"), makeRequest( request() .withSecure(true) .withPath(calculatePath("some_path")) .withMethod("POST") .withBody(json("{" + System.getProperty("line.separator") + " \"ταυτότητα\": 1," + System.getProperty("line.separator") + " \"επιπλέον αγνοούνται σειρά\": [\"ένας\", \"δυο\"]," + System.getProperty("line.separator") + " \"όνομα\": \"μια πράσινη πόρτα\"," + System.getProperty("line.separator") + " \"τιμή\": 12.50," + System.getProperty("line.separator") + " \"ετικέτες\": [\"σπίτι\", \"πράσινος\"]" + System.getProperty("line.separator") + "}", Charsets.UTF_16, MatchType.ONLY_MATCHING_FIELDS)), headersToIgnore) ); } @Test public void shouldReturnResponseByMatchingBodyWithJsonWithContentTypeHeader() { // when mockServerClient .when( request() .withBody(json("{" + System.getProperty("line.separator") + " \"ταυτότητα\": 1," + System.getProperty("line.separator") + " \"όνομα\": \"μια πράσινη πόρτα\"," + System.getProperty("line.separator") + " \"τιμή\": 12.50," + System.getProperty("line.separator") + " \"ετικέτες\": [\"σπίτι\", \"πράσινος\"]" + System.getProperty("line.separator") + "}", Charsets.UTF_16, MatchType.ONLY_MATCHING_FIELDS)), exactly(2) ) .respond( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body") ); // then // - in http assertEquals( response() .withHeader(HttpHeaders.CONTENT_TYPE, TEXT_PLAIN) .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body"), makeRequest( request() .withHeader(HttpHeaders.CONTENT_TYPE, MediaType.create("text", "plain").withCharset(Charsets.UTF_16).toString()) .withPath(calculatePath("some_path")) .withMethod("POST") .withBody(json("{" + System.getProperty("line.separator") + " \"ταυτότητα\": 1," + System.getProperty("line.separator") + " \"επιπλέον αγνοούνται τομέα\": \"κάποια αξία\"," + System.getProperty("line.separator") + " \"όνομα\": \"μια πράσινη πόρτα\"," + System.getProperty("line.separator") + " \"τιμή\": 12.50," + System.getProperty("line.separator") + " \"ετικέτες\": [\"σπίτι\", \"πράσινος\"]" + System.getProperty("line.separator") + "}")), headersToIgnore) ); // - in https assertEquals( response() .withHeader(HttpHeaders.CONTENT_TYPE, TEXT_PLAIN) .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body"), makeRequest( request() .withSecure(true) .withHeader(HttpHeaders.CONTENT_TYPE, MediaType.create("text", "plain").withCharset(Charsets.UTF_16).toString()) .withPath(calculatePath("some_path")) .withMethod("POST") .withBody(json("{" + System.getProperty("line.separator") + " \"ταυτότητα\": 1," + System.getProperty("line.separator") + " \"επιπλέον αγνοούνται σειρά\": [\"ένας\", \"δυο\"]," + System.getProperty("line.separator") + " \"όνομα\": \"μια πράσινη πόρτα\"," + System.getProperty("line.separator") + " \"τιμή\": 12.50," + System.getProperty("line.separator") + " \"ετικέτες\": [\"σπίτι\", \"πράσινος\"]" + System.getProperty("line.separator") + "}")), headersToIgnore) ); } @Test public void shouldReturnResponseByMatchingBodyWithJsonWithMatchType() { // when mockServerClient .when( request() .withBody(json("{" + System.getProperty("line.separator") + " \"id\": 1," + System.getProperty("line.separator") + " \"name\": \"A green door\"," + System.getProperty("line.separator") + " \"price\": 12.50," + System.getProperty("line.separator") + " \"tags\": [\"home\", \"green\"]" + System.getProperty("line.separator") + "}", MatchType.ONLY_MATCHING_FIELDS)), exactly(2) ) .respond( response() .withBody("some_body") ); // then // - in http assertEquals( response() .withBody("some_body").withHeader(HttpHeaders.CONTENT_TYPE, TEXT_PLAIN), makeRequest( request() .withPath(calculatePath("some_path")) .withMethod("POST") .withBody("{" + System.getProperty("line.separator") + " \"id\": 1," + System.getProperty("line.separator") + " \"extra field\": \"some value\"," + System.getProperty("line.separator") + " \"name\": \"A green door\"," + System.getProperty("line.separator") + " \"price\": 12.50," + System.getProperty("line.separator") + " \"tags\": [\"home\", \"green\"]" + System.getProperty("line.separator") + "}"), headersToIgnore) ); // - in https assertEquals( response() .withBody("some_body").withHeader(HttpHeaders.CONTENT_TYPE, TEXT_PLAIN), makeRequest( request() .withSecure(true) .withPath(calculatePath("some_path")) .withMethod("POST") .withBody("{" + System.getProperty("line.separator") + " \"id\": 1," + System.getProperty("line.separator") + " \"extra field\": \"some value\"," + System.getProperty("line.separator") + " \"name\": \"A green door\"," + System.getProperty("line.separator") + " \"price\": 12.50," + System.getProperty("line.separator") + " \"tags\": [\"home\", \"green\"]" + System.getProperty("line.separator") + "}"), headersToIgnore) ); } @Test public void shouldReturnResponseByMatchingBodyWithJsonSchema() { // when mockServerClient.when(request().withBody(jsonSchema("{" + System.getProperty("line.separator") + " \"$schema\": \"http://json-schema.org/draft-04/schema#\"," + System.getProperty("line.separator") + " \"title\": \"Product\"," + System.getProperty("line.separator") + " \"description\": \"A product from Acme's catalog\"," + System.getProperty("line.separator") + " \"type\": \"object\"," + System.getProperty("line.separator") + " \"properties\": {" + System.getProperty("line.separator") + " \"id\": {" + System.getProperty("line.separator") + " \"description\": \"The unique identifier for a product\"," + System.getProperty("line.separator") + " \"type\": \"integer\"" + System.getProperty("line.separator") + " }," + System.getProperty("line.separator") + " \"name\": {" + System.getProperty("line.separator") + " \"description\": \"Name of the product\"," + System.getProperty("line.separator") + " \"type\": \"string\"" + System.getProperty("line.separator") + " }," + System.getProperty("line.separator") + " \"price\": {" + System.getProperty("line.separator") + " \"type\": \"number\"," + System.getProperty("line.separator") + " \"minimum\": 0," + System.getProperty("line.separator") + " \"exclusiveMinimum\": true" + System.getProperty("line.separator") + " }," + System.getProperty("line.separator") + " \"tags\": {" + System.getProperty("line.separator") + " \"type\": \"array\"," + System.getProperty("line.separator") + " \"items\": {" + System.getProperty("line.separator") + " \"type\": \"string\"" + System.getProperty("line.separator") + " }," + System.getProperty("line.separator") + " \"minItems\": 1," + System.getProperty("line.separator") + " \"uniqueItems\": true" + System.getProperty("line.separator") + " }" + System.getProperty("line.separator") + " }," + System.getProperty("line.separator") + " \"required\": [\"id\", \"name\", \"price\"]" + System.getProperty("line.separator") + "}")), exactly(2)).respond(response().withBody("some_body")); // then // - in http assertEquals( response() .withHeader(HttpHeaders.CONTENT_TYPE, TEXT_PLAIN) .withStatusCode(HttpStatusCode.OK_200.code()) .withBody("some_body"), makeRequest( request() .withPath(calculatePath("some_path")) .withMethod("POST") .withBody("{" + System.getProperty("line.separator") + " \"id\": 1," + System.getProperty("line.separator") + " \"name\": \"A green door\"," + System.getProperty("line.separator") + " \"price\": 12.50," + System.getProperty("line.separator") + " \"tags\": [\"home\", \"green\"]" + System.getProperty("line.separator") + "}"), headersToIgnore) ); // - in https assertEquals( response() .withHeader(HttpHeaders.CONTENT_TYPE, TEXT_PLAIN) .withStatusCode(HttpStatusCode.OK_200.code()) .withBody("some_body"), makeRequest( request() .withSecure(true) .withPath(calculatePath("some_path")) .withMethod("POST") .withBody("{" + System.getProperty("line.separator") + " \"id\": 1," + System.getProperty("line.separator") + " \"name\": \"A green door\"," + System.getProperty("line.separator") + " \"price\": 12.50," + System.getProperty("line.separator") + " \"tags\": [\"home\", \"green\"]" + System.getProperty("line.separator") + "}"), headersToIgnore) ); } @Test public void shouldReturnPDFResponseByMatchingPath() throws IOException { // when byte[] pdfBytes = IOUtils.toByteArray(getClass().getClassLoader().getResourceAsStream("test.pdf")); mockServerClient .when( request() .withPath(calculatePath("ws/rest/user/[0-9]+/document/[0-9]+\\.pdf")) ) .respond( response() .withStatusCode(HttpStatusCode.OK_200.code()) .withHeaders( header(HttpHeaders.CONTENT_TYPE, MediaType.PDF.toString()), header(HttpHeaders.CONTENT_DISPOSITION, "form-data; name=\"test.pdf\"; filename=\"test.pdf\""), header(HttpHeaders.CACHE_CONTROL, "must-revalidate, post-check=0, pre-check=0") ) .withBody(binary(pdfBytes)) ); // then // - in http assertEquals( response() .withStatusCode(HttpStatusCode.OK_200.code()) .withHeaders( header(HttpHeaders.CONTENT_DISPOSITION, "form-data; name=\"test.pdf\"; filename=\"test.pdf\""), header(HttpHeaders.CACHE_CONTROL, "must-revalidate, post-check=0, pre-check=0"), header(HttpHeaders.CONTENT_TYPE, MediaType.PDF.toString()) ) .withBody(binary(pdfBytes)), makeRequest( request() .withPath(calculatePath("ws/rest/user/1/document/2.pdf")) .withMethod("GET"), headersToIgnore) ); // - in https assertEquals( response() .withStatusCode(HttpStatusCode.OK_200.code()) .withHeaders( header(HttpHeaders.CONTENT_DISPOSITION, "form-data; name=\"test.pdf\"; filename=\"test.pdf\""), header(HttpHeaders.CACHE_CONTROL, "must-revalidate, post-check=0, pre-check=0"), header(HttpHeaders.CONTENT_TYPE, MediaType.PDF.toString()) ) .withBody(binary(pdfBytes)), makeRequest( request() .withSecure(true) .withPath(calculatePath("ws/rest/user/1/document/2.pdf")) .withMethod("GET"), headersToIgnore) ); } @Test public void shouldReturnPNGResponseByMatchingPath() throws IOException { // when byte[] pngBytes = IOUtils.toByteArray(getClass().getClassLoader().getResourceAsStream("test.png")); mockServerClient .when( request() .withPath(calculatePath("ws/rest/user/[0-9]+/icon/[0-9]+\\.png")) ) .respond( response() .withStatusCode(HttpStatusCode.OK_200.code()) .withHeaders( header(HttpHeaders.CONTENT_TYPE, MediaType.PNG.toString()), header(HttpHeaders.CONTENT_DISPOSITION, "form-data; name=\"test.png\"; filename=\"test.png\"") ) .withBody(binary(pngBytes)) ); // then // - in http assertEquals( response() .withStatusCode(HttpStatusCode.OK_200.code()) .withHeaders( header(HttpHeaders.CONTENT_DISPOSITION, "form-data; name=\"test.png\"; filename=\"test.png\""), header(HttpHeaders.CONTENT_TYPE, MediaType.PNG.toString()) ) .withBody(binary(pngBytes)), makeRequest( request() .withPath(calculatePath("ws/rest/user/1/icon/1.png")) .withMethod("GET"), headersToIgnore) ); // - in https assertEquals( response() .withStatusCode(HttpStatusCode.OK_200.code()) .withHeaders( header(HttpHeaders.CONTENT_DISPOSITION, "form-data; name=\"test.png\"; filename=\"test.png\""), header(HttpHeaders.CONTENT_TYPE, MediaType.PNG.toString()) ) .withBody(binary(pngBytes)), makeRequest( request() .withSecure(true) .withPath(calculatePath("ws/rest/user/1/icon/1.png")) .withMethod("GET"), headersToIgnore) ); } @Test public void shouldReturnPDFResponseByMatchingBinaryPDFBody() throws IOException { // when byte[] pdfBytes = IOUtils.toByteArray(getClass().getClassLoader().getResourceAsStream("test.pdf")); mockServerClient .when( request().withBody(binary(pdfBytes)) ) .respond( response() .withStatusCode(HttpStatusCode.OK_200.code()) .withHeaders( header(HttpHeaders.CONTENT_TYPE, MediaType.PDF.toString()), header(HttpHeaders.CONTENT_DISPOSITION, "form-data; name=\"test.pdf\"; filename=\"test.pdf\""), header(HttpHeaders.CACHE_CONTROL, "must-revalidate, post-check=0, pre-check=0") ) .withBody(binary(pdfBytes)) ); // then // - in http assertEquals( response() .withStatusCode(HttpStatusCode.OK_200.code()) .withHeaders( header(HttpHeaders.CONTENT_DISPOSITION, "form-data; name=\"test.pdf\"; filename=\"test.pdf\""), header(HttpHeaders.CACHE_CONTROL, "must-revalidate, post-check=0, pre-check=0"), header(HttpHeaders.CONTENT_TYPE, MediaType.PDF.toString()) ) .withBody(binary(pdfBytes)), makeRequest( request() .withPath(calculatePath("ws/rest/user/1/document/2.pdf")) .withBody(binary(pdfBytes)) .withMethod("POST"), headersToIgnore) ); // - in https assertEquals( response() .withStatusCode(HttpStatusCode.OK_200.code()) .withHeaders( header(HttpHeaders.CONTENT_DISPOSITION, "form-data; name=\"test.pdf\"; filename=\"test.pdf\""), header(HttpHeaders.CACHE_CONTROL, "must-revalidate, post-check=0, pre-check=0"), header(HttpHeaders.CONTENT_TYPE, MediaType.PDF.toString()) ) .withBody(binary(pdfBytes)), makeRequest( request() .withSecure(true) .withPath(calculatePath("ws/rest/user/1/document/2.pdf")) .withBody(binary(pdfBytes)) .withMethod("POST"), headersToIgnore) ); } @Test public void shouldReturnPNGResponseByMatchingBinaryPNGBody() throws IOException { // when byte[] pngBytes = IOUtils.toByteArray(getClass().getClassLoader().getResourceAsStream("test.png")); mockServerClient .when( request().withBody(binary(pngBytes)) ) .respond( response() .withStatusCode(HttpStatusCode.OK_200.code()) .withHeaders( header(HttpHeaders.CONTENT_TYPE, MediaType.PNG.toString()), header(HttpHeaders.CONTENT_DISPOSITION, "form-data; name=\"test.png\"; filename=\"test.png\"") ) .withBody(binary(pngBytes)) ); // then // - in http assertEquals( response() .withStatusCode(HttpStatusCode.OK_200.code()) .withHeaders( header(HttpHeaders.CONTENT_DISPOSITION, "form-data; name=\"test.png\"; filename=\"test.png\""), header(HttpHeaders.CONTENT_TYPE, MediaType.PNG.toString()) ) .withBody(binary(pngBytes)), makeRequest( request() .withPath(calculatePath("ws/rest/user/1/icon/1.png")) .withBody(binary(pngBytes)) .withMethod("POST"), headersToIgnore) ); // - in https assertEquals( response() .withStatusCode(HttpStatusCode.OK_200.code()) .withHeaders( header(HttpHeaders.CONTENT_DISPOSITION, "form-data; name=\"test.png\"; filename=\"test.png\""), header(HttpHeaders.CONTENT_TYPE, MediaType.PNG.toString()) ) .withBody(binary(pngBytes)), makeRequest( request() .withSecure(true) .withPath(calculatePath("ws/rest/user/1/icon/1.png")) .withBody(binary(pngBytes)) .withMethod("POST"), headersToIgnore) ); } @Test public void shouldReturnResponseForExpectationWithDelay() { // when mockServerClient .when( request() .withPath(calculatePath("some_path1")) ) .respond( response() .withBody("some_body1") .withDelay(new Delay(TimeUnit.MILLISECONDS, 10)) ); mockServerClient .when( request() .withPath(calculatePath("some_path2")) ) .respond( response() .withBody("some_body2") .withDelay(new Delay(TimeUnit.MILLISECONDS, 20)) ); // then // - in http assertEquals( response() .withHeader(HttpHeaders.CONTENT_TYPE, TEXT_PLAIN) .withStatusCode(HttpStatusCode.OK_200.code()) .withBody("some_body2"), makeRequest( request() .withPath(calculatePath("some_path2")), headersToIgnore) ); assertEquals( response() .withHeader(HttpHeaders.CONTENT_TYPE, TEXT_PLAIN) .withStatusCode(HttpStatusCode.OK_200.code()) .withBody("some_body1"), makeRequest( request() .withPath(calculatePath("some_path1")), headersToIgnore) ); // - in https assertEquals( response() .withHeader(HttpHeaders.CONTENT_TYPE, TEXT_PLAIN) .withStatusCode(HttpStatusCode.OK_200.code()) .withBody("some_body2"), makeRequest( request() .withSecure(true) .withPath(calculatePath("some_path2")), headersToIgnore) ); assertEquals( response() .withHeader(HttpHeaders.CONTENT_TYPE, TEXT_PLAIN) .withStatusCode(HttpStatusCode.OK_200.code()) .withBody("some_body1"), makeRequest( request() .withSecure(true) .withPath(calculatePath("some_path1")), headersToIgnore) ); } @Test public void shouldReturnResponseByMatchingPathAndMethod() { // when mockServerClient .when( request() .withMethod("GET") .withPath(calculatePath("some_pathRequest")) ) .respond( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body_response") ); // then // - in http assertEquals( response() .withHeader(HttpHeaders.CONTENT_TYPE, TEXT_PLAIN) .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body_response"), makeRequest( request() .withMethod("GET") .withPath(calculatePath("some_pathRequest")) .withQueryStringParameters( param("queryStringParameterOneName", "queryStringParameterOneValue"), param("queryStringParameterTwoName", "queryStringParameterTwoValue") ) .withHeaders(header("headerNameRequest", "headerValueRequest")) .withCookies(cookie("cookieNameRequest", "cookieValueRequest")), headersToIgnore) ); // - in https assertEquals( response() .withHeader(HttpHeaders.CONTENT_TYPE, TEXT_PLAIN) .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body_response"), makeRequest( request() .withMethod("GET") .withSecure(true) .withPath(calculatePath("some_pathRequest")) .withQueryStringParameters( param("queryStringParameterOneName", "queryStringParameterOneValue"), param("queryStringParameterTwoName", "queryStringParameterTwoValue") ) .withHeaders(header("headerNameRequest", "headerValueRequest")) .withCookies(cookie("cookieNameRequest", "cookieValueRequest")), headersToIgnore) ); } @Test public void shouldReturnResponseByNotMatchingPathWithNotOperator() { // when mockServerClient .when( request() .withPath(not(calculatePath("some_path"))) ) .respond( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body_response") ); // then // - in http assertEquals( response() .withHeader(HttpHeaders.CONTENT_TYPE, TEXT_PLAIN) .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body_response"), makeRequest( request() .withPath(calculatePath("some_other_path")), headersToIgnore) ); // - in https assertEquals( response() .withHeader(HttpHeaders.CONTENT_TYPE, TEXT_PLAIN) .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body_response"), makeRequest( request() .withPath(calculatePath("some_other_path")), headersToIgnore) ); } @Test public void shouldReturnResponseByNotMatchingMethodWithNotOperator() { // when mockServerClient .when( request() .withMethod(not("GET")) ) .respond( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body_response") ); // then // - in http assertEquals( response() .withHeader(HttpHeaders.CONTENT_TYPE, TEXT_PLAIN) .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body_response"), makeRequest( request() .withMethod("POST"), headersToIgnore) ); // - in https assertEquals( response() .withHeader(HttpHeaders.CONTENT_TYPE, TEXT_PLAIN) .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body_response"), makeRequest( request() .withMethod("POST"), headersToIgnore) ); } @Test public void shouldReturnResponseByMatchingPathAndMethodAndBody() { // when mockServerClient .when( request() .withMethod("POST") .withPath(calculatePath("some_pathRequest")) .withBody("some_bodyRequest") ) .respond( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body_response") .withHeaders(header("headerNameResponse", "headerValueResponse")) ); // then // - in http assertEquals( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body_response") .withHeaders( header("headerNameResponse", "headerValueResponse"), header(HttpHeaders.CONTENT_TYPE, TEXT_PLAIN) ), makeRequest( request() .withMethod("POST") .withPath(calculatePath("some_pathRequest")) .withQueryStringParameters( param("queryStringParameterOneName", "queryStringParameterOneValue"), param("queryStringParameterTwoName", "queryStringParameterTwoValue") ) .withBody("some_bodyRequest") .withHeaders(header("headerNameRequest", "headerValueRequest")) .withCookies(cookie("cookieNameRequest", "cookieValueRequest")), headersToIgnore) ); // - in https assertEquals( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body_response") .withHeaders( header("headerNameResponse", "headerValueResponse"), header(HttpHeaders.CONTENT_TYPE, TEXT_PLAIN) ), makeRequest( request() .withMethod("POST") .withSecure(true) .withPath(calculatePath("some_pathRequest")) .withQueryStringParameters( param("queryStringParameterOneName", "queryStringParameterOneValue"), param("queryStringParameterTwoName", "queryStringParameterTwoValue") ) .withBody("some_bodyRequest") .withHeaders(header("headerNameRequest", "headerValueRequest")) .withCookies(cookie("cookieNameRequest", "cookieValueRequest")), headersToIgnore) ); } @Test public void shouldReturnResponseByMatchingPathAndMethodAndQueryStringParameters() { // when mockServerClient .when( request() .withMethod("GET") .withPath(calculatePath("some_pathRequest")) .withQueryStringParameters( param("queryStringParameterOneName", "queryStringParameterOneValue"), param("queryStringParameterTwoName", "queryStringParameterTwoValue") ) ) .respond( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body_response") .withCookies(cookie("cookieNameResponse", "cookieValueResponse")) ); // then // - in http assertEquals( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body_response") .withCookies(cookie("cookieNameResponse", "cookieValueResponse")) .withHeaders( header("Set-Cookie", "cookieNameResponse=cookieValueResponse"), header(HttpHeaders.CONTENT_TYPE, TEXT_PLAIN) ), makeRequest( request() .withMethod("GET") .withPath(calculatePath("some_pathRequest")) .withQueryStringParameters( param("queryStringParameterOneName", "queryStringParameterOneValue"), param("queryStringParameterTwoName", "queryStringParameterTwoValue") ) .withHeaders(header("headerNameRequest", "headerValueRequest")) .withCookies(cookie("cookieNameRequest", "cookieValueRequest")), headersToIgnore) ); // - in https assertEquals( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body_response") .withCookies(cookie("cookieNameResponse", "cookieValueResponse")) .withHeaders( header("Set-Cookie", "cookieNameResponse=cookieValueResponse"), header(HttpHeaders.CONTENT_TYPE, TEXT_PLAIN) ), makeRequest( request() .withMethod("GET") .withSecure(true) .withPath(calculatePath("some_pathRequest")) .withQueryStringParameters( param("queryStringParameterOneName", "queryStringParameterOneValue"), param("queryStringParameterTwoName", "queryStringParameterTwoValue") ) .withHeaders(header("headerNameRequest", "headerValueRequest")) .withCookies(cookie("cookieNameRequest", "cookieValueRequest")), headersToIgnore) ); } @Test public void shouldReturnResponseByMatchingPathAndMethodAndHeaders() { // when mockServerClient .when( request() .withMethod("GET") .withPath(calculatePath("some_pathRequest")) .withHeaders( header("requestHeaderNameOne", "requestHeaderValueOne_One", "requestHeaderValueOne_Two"), header("requestHeaderNameTwo", "requestHeaderValueTwo") ) ) .respond( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body_response") .withCookies(cookie("cookieNameResponse", "cookieValueResponse")) ); // then // - in http assertEquals( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body_response") .withCookies(cookie("cookieNameResponse", "cookieValueResponse")) .withHeaders( header("Set-Cookie", "cookieNameResponse=cookieValueResponse"), header(HttpHeaders.CONTENT_TYPE, TEXT_PLAIN) ), makeRequest( request() .withMethod("GET") .withPath(calculatePath("some_pathRequest")) .withHeaders( header("requestHeaderNameOne", "requestHeaderValueOne_One", "requestHeaderValueOne_Two"), header("requestHeaderNameTwo", "requestHeaderValueTwo") ) .withCookies(cookie("cookieNameRequest", "cookieValueRequest")), headersToIgnore) ); // - in https assertEquals( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body_response") .withCookies(cookie("cookieNameResponse", "cookieValueResponse")) .withHeaders( header("Set-Cookie", "cookieNameResponse=cookieValueResponse"), header(HttpHeaders.CONTENT_TYPE, TEXT_PLAIN) ), makeRequest( request() .withMethod("GET") .withSecure(true) .withPath(calculatePath("some_pathRequest")) .withHeaders( header("requestHeaderNameOne", "requestHeaderValueOne_One", "requestHeaderValueOne_Two"), header("requestHeaderNameTwo", "requestHeaderValueTwo") ) .withCookies(cookie("cookieNameRequest", "cookieValueRequest")), headersToIgnore) ); } @Test public void shouldReturnResponseByMatchingPathAndMethodAndCookies() { // when mockServerClient .when( request() .withMethod("GET") .withPath(calculatePath("some_pathRequest")) .withCookies( cookie("requestCookieNameOne", "requestCookieValueOne"), cookie("requestCookieNameTwo", "requestCookieValueTwo") ) ) .respond( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body_response") .withCookies( cookie("responseCookieNameOne", "responseCookieValueOne"), cookie("responseCookieNameTwo", "responseCookieValueTwo") ) ); // then // - in http - cookie objects assertEquals( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body_response") .withCookies( cookie("responseCookieNameOne", "responseCookieValueOne"), cookie("responseCookieNameTwo", "responseCookieValueTwo") ) .withHeaders( header("Set-Cookie", "responseCookieNameOne=responseCookieValueOne", "responseCookieNameTwo=responseCookieValueTwo"), header(HttpHeaders.CONTENT_TYPE, TEXT_PLAIN) ), makeRequest( request() .withMethod("GET") .withPath(calculatePath("some_pathRequest")) .withHeaders( header("headerNameRequest", "headerValueRequest"), header(HttpHeaders.CONTENT_TYPE, TEXT_PLAIN) ) .withCookies( cookie("requestCookieNameOne", "requestCookieValueOne"), cookie("requestCookieNameTwo", "requestCookieValueTwo") ), headersToIgnore) ); // - in http - cookie header assertEquals( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body_response") .withCookies( cookie("responseCookieNameOne", "responseCookieValueOne"), cookie("responseCookieNameTwo", "responseCookieValueTwo") ) .withHeaders( header("Set-Cookie", "responseCookieNameOne=responseCookieValueOne", "responseCookieNameTwo=responseCookieValueTwo"), header(HttpHeaders.CONTENT_TYPE, TEXT_PLAIN) ), makeRequest( request() .withMethod("GET") .withPath(calculatePath("some_pathRequest")) .withHeaders( header("headerNameRequest", "headerValueRequest"), header("Cookie", "requestCookieNameOne=requestCookieValueOne; requestCookieNameTwo=requestCookieValueTwo") ), headersToIgnore) ); // - in https - cookie objects assertEquals( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body_response") .withCookies( cookie("responseCookieNameOne", "responseCookieValueOne"), cookie("responseCookieNameTwo", "responseCookieValueTwo") ) .withHeaders( header("Set-Cookie", "responseCookieNameOne=responseCookieValueOne", "responseCookieNameTwo=responseCookieValueTwo"), header(HttpHeaders.CONTENT_TYPE, TEXT_PLAIN) ), makeRequest( request() .withMethod("GET") .withSecure(true) .withPath(calculatePath("some_pathRequest")) .withHeaders( header("headerNameRequest", "headerValueRequest") ) .withCookies( cookie("requestCookieNameOne", "requestCookieValueOne"), cookie("requestCookieNameTwo", "requestCookieValueTwo") ), headersToIgnore) ); // - in https - cookie header assertEquals( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body_response") .withCookies( cookie("responseCookieNameOne", "responseCookieValueOne"), cookie("responseCookieNameTwo", "responseCookieValueTwo") ) .withHeaders( header("Set-Cookie", "responseCookieNameOne=responseCookieValueOne", "responseCookieNameTwo=responseCookieValueTwo"), header(HttpHeaders.CONTENT_TYPE, TEXT_PLAIN) ), makeRequest( request() .withMethod("GET") .withSecure(true) .withPath(calculatePath("some_pathRequest")) .withHeaders( header("headerNameRequest", "headerValueRequest"), header("Cookie", "requestCookieNameOne=requestCookieValueOne; requestCookieNameTwo=requestCookieValueTwo") ), headersToIgnore) ); } @Test public void shouldReturnResponseByMatchingPathAndMethodAndQueryStringParametersAndBodyParameters() { // when mockServerClient .when( request() .withMethod("POST") .withPath(calculatePath("some_pathRequest")) .withQueryStringParameters( param("queryStringParameterOneName", "queryStringParameterOneValueOne", "queryStringParameterOneValueTwo"), param("queryStringParameterTwoName", "queryStringParameterTwoValue") ) .withBody(params(param("bodyParameterName", "bodyParameterValue"))) ) .respond( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body") ); // then // - in http - url query string assertEquals( response() .withHeader(HttpHeaders.CONTENT_TYPE, TEXT_PLAIN) .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body"), makeRequest( request() .withMethod("POST") .withPath(calculatePath("some_pathRequest")) .withQueryStringParameters( param("queryStringParameterOneName", "queryStringParameterOneValueOne", "queryStringParameterOneValueTwo"), param("queryStringParameterTwoName", "queryStringParameterTwoValue") ) .withBody(params(param("bodyParameterName", "bodyParameterValue"))), headersToIgnore) ); // - in https - query string parameter objects assertEquals( response() .withHeader(HttpHeaders.CONTENT_TYPE, TEXT_PLAIN) .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body"), makeRequest( request() .withSecure(true) .withMethod("POST") .withPath(calculatePath("some_pathRequest")) .withQueryStringParameters( param("queryStringParameterOneName", "queryStringParameterOneValueOne", "queryStringParameterOneValueTwo"), param("queryStringParameterTwoName", "queryStringParameterTwoValue") ) .withBody(params(param("bodyParameterName", "bodyParameterValue"))), headersToIgnore) ); } @Test public void shouldReturnResponseByMatchingPathAndMethodAndQueryStringParametersAndBody() { // when mockServerClient .when( request() .withMethod("POST") .withPath(calculatePath("some_pathRequest")) .withQueryStringParameters( param("queryStringParameterOneName", "queryStringParameterOneValueOne", "queryStringParameterOneValueTwo"), param("queryStringParameterTwoName", "queryStringParameterTwoValue") ) .withBody("some_bodyRequest") ) .respond( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body_response") .withHeaders(header("headerNameResponse", "headerValueResponse")) .withCookies(cookie("cookieNameResponse", "cookieValueResponse")) ); // then // - in http - url query string assertEquals( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body_response") .withCookies(cookie("cookieNameResponse", "cookieValueResponse")) .withHeaders( header("headerNameResponse", "headerValueResponse"), header("Set-Cookie", "cookieNameResponse=cookieValueResponse"), header(HttpHeaders.CONTENT_TYPE, TEXT_PLAIN) ), makeRequest( request() .withMethod("POST") .withPath(calculatePath("some_pathRequest")) .withQueryStringParameters( param("queryStringParameterOneName", "queryStringParameterOneValueOne", "queryStringParameterOneValueTwo"), param("queryStringParameterTwoName", "queryStringParameterTwoValue") ) .withBody("some_bodyRequest") .withHeaders(header("headerNameRequest", "headerValueRequest")) .withCookies(cookie("cookieNameRequest", "cookieValueRequest")), headersToIgnore) ); // - in http - query string parameter objects assertEquals( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body_response") .withCookies(cookie("cookieNameResponse", "cookieValueResponse")) .withHeaders( header("headerNameResponse", "headerValueResponse"), header("Set-Cookie", "cookieNameResponse=cookieValueResponse"), header(HttpHeaders.CONTENT_TYPE, TEXT_PLAIN) ), makeRequest( request() .withMethod("POST") .withPath(calculatePath("some_pathRequest")) .withQueryStringParameters( param("queryStringParameterOneName", "queryStringParameterOneValueOne", "queryStringParameterOneValueTwo"), param("queryStringParameterTwoName", "queryStringParameterTwoValue") ) .withBody("some_bodyRequest") .withHeaders(header("headerNameRequest", "headerValueRequest")) .withCookies(cookie("cookieNameRequest", "cookieValueRequest")), headersToIgnore) ); // - in https - url string and query string parameter objects assertEquals( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body_response") .withCookies(cookie("cookieNameResponse", "cookieValueResponse")) .withHeaders( header("headerNameResponse", "headerValueResponse"), header("Set-Cookie", "cookieNameResponse=cookieValueResponse"), header(HttpHeaders.CONTENT_TYPE, TEXT_PLAIN) ), makeRequest( request() .withMethod("POST") .withPath(calculatePath("some_pathRequest")) .withQueryStringParameters( param("queryStringParameterOneName", "queryStringParameterOneValueOne", "queryStringParameterOneValueTwo"), param("queryStringParameterTwoName", "queryStringParameterTwoValue") ) .withBody("some_bodyRequest") .withHeaders(header("headerNameRequest", "headerValueRequest")) .withCookies(cookie("cookieNameRequest", "cookieValueRequest")), headersToIgnore) ); } @Test public void shouldReturnResponseByMatchingPathAndMethodAndBodyParameters() { // when mockServerClient .when( request() .withMethod("POST") .withPath(calculatePath("some_pathRequest")) .withBody(params( param("bodyParameterOneName", "Parameter One Value One", "Parameter One Value Two"), param("bodyParameterTwoName", "Parameter Two") )) ) .respond( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body_response") .withHeaders(header("headerNameResponse", "headerValueResponse")) .withCookies(cookie("cookieNameResponse", "cookieValueResponse")) ); // then // - in http - body string assertEquals( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body_response") .withCookies(cookie("cookieNameResponse", "cookieValueResponse")) .withHeaders( header("headerNameResponse", "headerValueResponse"), header("Set-Cookie", "cookieNameResponse=cookieValueResponse"), header(HttpHeaders.CONTENT_TYPE, TEXT_PLAIN) ), makeRequest( request() .withMethod("POST") .withPath(calculatePath("some_pathRequest")) .withBody(new StringBody("bodyParameterOneName=Parameter+One+Value+One" + "&bodyParameterOneName=Parameter+One+Value+Two" + "&bodyParameterTwoName=Parameter+Two")) .withHeaders(header("headerNameRequest", "headerValueRequest")) .withCookies(cookie("cookieNameRequest", "cookieValueRequest")), headersToIgnore) ); // - in http - body parameter objects assertEquals( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body_response") .withCookies(cookie("cookieNameResponse", "cookieValueResponse")) .withHeaders( header("headerNameResponse", "headerValueResponse"), header("Set-Cookie", "cookieNameResponse=cookieValueResponse"), header(HttpHeaders.CONTENT_TYPE, TEXT_PLAIN) ), makeRequest( request() .withMethod("POST") .withPath(calculatePath("some_pathRequest")) .withBody(params( param("bodyParameterOneName", "Parameter One Value One", "Parameter One Value Two"), param("bodyParameterTwoName", "Parameter Two") )) .withHeaders(header("headerNameRequest", "headerValueRequest")) .withCookies(cookie("cookieNameRequest", "cookieValueRequest")), headersToIgnore) ); // - in https - url string and query string parameter objects assertEquals( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body_response") .withCookies(cookie("cookieNameResponse", "cookieValueResponse")) .withHeaders( header("headerNameResponse", "headerValueResponse"), header("Set-Cookie", "cookieNameResponse=cookieValueResponse"), header(HttpHeaders.CONTENT_TYPE, TEXT_PLAIN) ), makeRequest( request() .withMethod("POST") .withPath(calculatePath("some_pathRequest")) .withBody(params( param("bodyParameterOneName", "Parameter One Value One", "Parameter One Value Two"), param("bodyParameterTwoName", "Parameter Two") )) .withHeaders(header("headerNameRequest", "headerValueRequest")) .withCookies(cookie("cookieNameRequest", "cookieValueRequest")), headersToIgnore) ); } @Test public void shouldReturnResponseByMatchingPathAndMethodAndParametersAndHeadersAndCookies() { // when mockServerClient .when( request() .withMethod("PUT") .withPath(calculatePath("some_pathRequest")) .withBody(new StringBody("bodyParameterOneName=Parameter+One+Value+One" + "&bodyParameterOneName=Parameter+One+Value+Two" + "&bodyParameterTwoName=Parameter+Two")) .withHeaders(header("headerNameRequest", "headerValueRequest")) .withCookies(cookie("cookieNameRequest", "cookieValueRequest")) ) .respond( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body_response") .withHeaders(header("headerNameResponse", "headerValueResponse")) .withCookies(cookie("cookieNameResponse", "cookieValueResponse")) ); // then // - in http - body string assertEquals( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body_response") .withCookies(cookie("cookieNameResponse", "cookieValueResponse")) .withHeaders( header("headerNameResponse", "headerValueResponse"), header("Set-Cookie", "cookieNameResponse=cookieValueResponse"), header(HttpHeaders.CONTENT_TYPE, TEXT_PLAIN) ), makeRequest( request() .withMethod("PUT") .withPath(calculatePath("some_pathRequest")) .withBody(new StringBody("bodyParameterOneName=Parameter+One+Value+One" + "&bodyParameterOneName=Parameter+One+Value+Two" + "&bodyParameterTwoName=Parameter+Two")) .withHeaders( header("headerNameRequest", "headerValueRequest"), header("Cookie", "cookieNameRequest=cookieValueRequest") ), headersToIgnore) ); // - in http - body parameter objects assertEquals( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body_response") .withCookies(cookie("cookieNameResponse", "cookieValueResponse")) .withHeaders( header("headerNameResponse", "headerValueResponse"), header("Set-Cookie", "cookieNameResponse=cookieValueResponse"), header(HttpHeaders.CONTENT_TYPE, TEXT_PLAIN) ), makeRequest( request() .withMethod("PUT") .withPath(calculatePath("some_pathRequest")) .withBody(params( param("bodyParameterOneName", "Parameter One Value One", "Parameter One Value Two"), param("bodyParameterTwoName", "Parameter Two") )) .withHeaders(header("headerNameRequest", "headerValueRequest")) .withCookies(cookie("cookieNameRequest", "cookieValueRequest")), headersToIgnore) ); } @Test public void shouldReturnResponseByNotMatchingBodyParameterWithNotOperatorForNameAndValue() { // when mockServerClient .when( request() .withMethod("POST") .withPath(calculatePath("some_pathRequest")) .withBody(params( param(not("bodyParameterOneName"), not("Parameter One Value One"), not("Parameter One Value Two")), param("bodyParameterTwoName", "Parameter Two") )) ) .respond( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body_response") ); // then // wrong query string parameter name assertEquals( response() .withHeader(HttpHeaders.CONTENT_TYPE, TEXT_PLAIN) .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body_response"), makeRequest( request() .withMethod("POST") .withPath(calculatePath("some_pathRequest")) .withBody(params( param("OTHERBodyParameterOneName", "Parameter One Value One", "Parameter One Value Two"), param("bodyParameterTwoName", "Parameter Two") )) .withHeaders(header("headerNameRequest", "headerValueRequest")) .withCookies(cookie("cookieNameRequest", "cookieValueRequest")), headersToIgnore) ); // wrong query string parameter name assertEquals( response() .withHeader(HttpHeaders.CONTENT_TYPE, TEXT_PLAIN) .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body_response"), makeRequest( request() .withMethod("POST") .withPath(calculatePath("some_pathRequest")) .withBody(new StringBody("OTHERBodyParameterOneName=Parameter+One+Value+One" + "&OTHERBodyParameterOneName=Parameter+One+Value+Two" + "&bodyParameterTwoName=Parameter+Two")) .withHeaders(header("headerNameRequest", "headerValueRequest")) .withCookies(cookie("cookieNameRequest", "cookieValueRequest")), headersToIgnore) ); // wrong query string parameter value assertEquals( response() .withHeader(HttpHeaders.CONTENT_TYPE, TEXT_PLAIN) .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body_response"), makeRequest( request() .withMethod("POST") .withPath(calculatePath("some_pathRequest")) .withBody(params( param("bodyParameterOneName", "OTHER Parameter One Value One", "OTHER Parameter One Value Two"), param("bodyParameterTwoName", "Parameter Two") )) .withHeaders(header("headerNameRequest", "headerValueRequest")) .withCookies(cookie("cookieNameRequest", "cookieValueRequest")), headersToIgnore) ); // wrong query string parameter value assertEquals( response() .withHeader(HttpHeaders.CONTENT_TYPE, TEXT_PLAIN) .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body_response"), makeRequest( request() .withMethod("POST") .withPath(calculatePath("some_pathRequest")) .withBody(new StringBody("bodyParameterOneName=OTHER Parameter+One+Value+One" + "&bodyParameterOneName=OTHER Parameter+One+Value+Two" + "&bodyParameterTwoName=Parameter+Two")) .withHeaders(header("headerNameRequest", "headerValueRequest")) .withCookies(cookie("cookieNameRequest", "cookieValueRequest")), headersToIgnore) ); } @Test public void shouldReturnResponseByNotMatchingBodyParameterWithNotOperatorForName() { // when mockServerClient .when( request() .withMethod("POST") .withPath(calculatePath("some_pathRequest")) .withBody(params( param(not("bodyParameterOneName"), string("Parameter One Value One"), string("Parameter One Value Two")), param("bodyParameterTwoName", "Parameter Two") )) ) .respond( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body_response") ); // then // wrong query string parameter name assertEquals( response() .withHeader(HttpHeaders.CONTENT_TYPE, TEXT_PLAIN) .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body_response"), makeRequest( request() .withMethod("POST") .withPath(calculatePath("some_pathRequest")) .withBody(params( param("OTHERBodyParameterOneName", "Parameter One Value One", "Parameter One Value Two"), param("bodyParameterTwoName", "Parameter Two") )) .withHeaders(header("headerNameRequest", "headerValueRequest")) .withCookies(cookie("cookieNameRequest", "cookieValueRequest")), headersToIgnore) ); // wrong query string parameter name assertEquals( response() .withHeader(HttpHeaders.CONTENT_TYPE, TEXT_PLAIN) .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body_response"), makeRequest( request() .withMethod("POST") .withPath(calculatePath("some_pathRequest")) .withBody(new StringBody("OTHERBodyParameterOneName=Parameter+One+Value+One" + "&OTHERBodyParameterOneName=Parameter+One+Value+Two" + "&bodyParameterTwoName=Parameter+Two")) .withHeaders(header("headerNameRequest", "headerValueRequest")) .withCookies(cookie("cookieNameRequest", "cookieValueRequest")), headersToIgnore) ); } @Test public void shouldReturnResponseByNotMatchingBodyParameterWithNotOperatorForValue() { // when mockServerClient .when( request() .withMethod("POST") .withPath(calculatePath("some_pathRequest")) .withBody(params( param(string("bodyParameterOneName"), not("Parameter One Value One"), not("Parameter One Value Two")), param("bodyParameterTwoName", "Parameter Two") )) ) .respond( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body_response") ); // then // wrong query string parameter value assertEquals( response() .withHeader(HttpHeaders.CONTENT_TYPE, TEXT_PLAIN) .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body_response"), makeRequest( request() .withMethod("POST") .withPath(calculatePath("some_pathRequest")) .withBody(params( param("bodyParameterOneName", "OTHER Parameter One Value One", "OTHER Parameter One Value Two"), param("bodyParameterTwoName", "Parameter Two") )) .withHeaders(header("headerNameRequest", "headerValueRequest")) .withCookies(cookie("cookieNameRequest", "cookieValueRequest")), headersToIgnore) ); // wrong query string parameter value assertEquals( response() .withHeader(HttpHeaders.CONTENT_TYPE, TEXT_PLAIN) .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body_response"), makeRequest( request() .withMethod("POST") .withPath(calculatePath("some_pathRequest")) .withBody(new StringBody("bodyParameterOneName=OTHER Parameter+One+Value+One" + "&bodyParameterOneName=OTHER Parameter+One+Value+Two" + "&bodyParameterTwoName=Parameter+Two")) .withHeaders(header("headerNameRequest", "headerValueRequest")) .withCookies(cookie("cookieNameRequest", "cookieValueRequest")), headersToIgnore) ); } @Test public void shouldReturnResponseByNotMatchingQueryStringParameterWithNotOperatorForNameAndValue() { // when mockServerClient .when( request() .withMethod("POST") .withPath(calculatePath("some_pathRequest")) .withQueryStringParameters( param(not("queryStringParameterOneName"), not("Parameter One Value One"), not("Parameter One Value Two")), param("queryStringParameterTwoName", "Parameter Two") ) ) .respond( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body_response") ); // then // wrong query string parameter name assertEquals( response() .withHeader(HttpHeaders.CONTENT_TYPE, TEXT_PLAIN) .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body_response"), makeRequest( request() .withMethod("POST") .withPath(calculatePath("some_pathRequest")) .withQueryStringParameters( param("OTHERQueryStringParameterOneName", "Parameter One Value One", "Parameter One Value Two"), param("queryStringParameterTwoName", "Parameter Two") ), headersToIgnore) ); // wrong query string parameter value assertEquals( response() .withHeader(HttpHeaders.CONTENT_TYPE, TEXT_PLAIN) .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body_response"), makeRequest( request() .withMethod("POST") .withPath(calculatePath("some_pathRequest")) .withQueryStringParameters( param("queryStringParameterOneName", "OTHER Parameter One Value One", "OTHER Parameter One Value Two"), param("queryStringParameterTwoName", "Parameter Two") ), headersToIgnore) ); } @Test public void shouldReturnResponseByNotMatchingQueryStringParameterWithNotOperatorForName() { // when mockServerClient .when( request() .withMethod("POST") .withPath(calculatePath("some_pathRequest")) .withQueryStringParameters( param(not("queryStringParameterOneName"), string("Parameter One Value One"), string("Parameter One Value Two")), param("queryStringParameterTwoName", "Parameter Two") ) ) .respond( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body_response") ); // then // wrong query string parameter name assertEquals( response() .withHeader(HttpHeaders.CONTENT_TYPE, TEXT_PLAIN) .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body_response"), makeRequest( request() .withMethod("POST") .withPath(calculatePath("some_pathRequest")) .withQueryStringParameters( param("OTHERQueryStringParameterOneName", "Parameter One Value One", "Parameter One Value Two"), param("queryStringParameterTwoName", "Parameter Two") ), headersToIgnore) ); } @Test public void shouldReturnResponseByNotMatchingQueryStringParameterWithNotOperatorForValue() { // when mockServerClient .when( request() .withMethod("POST") .withPath(calculatePath("some_pathRequest")) .withQueryStringParameters( param(string("queryStringParameterOneName"), not("Parameter One Value One"), not("Parameter One Value Two")), param("queryStringParameterTwoName", "Parameter Two") ) ) .respond( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body_response") ); // then // wrong query string parameter value assertEquals( response() .withHeader(HttpHeaders.CONTENT_TYPE, TEXT_PLAIN) .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body_response"), makeRequest( request() .withMethod("POST") .withPath(calculatePath("some_pathRequest")) .withQueryStringParameters( param("queryStringParameterOneName", "OTHER Parameter One Value One", "OTHER Parameter One Value Two"), param("queryStringParameterTwoName", "Parameter Two") ), headersToIgnore) ); } @Test public void shouldReturnResponseByNotMatchingCookieWithNotOperatorForNameAndValue() { // when mockServerClient .when( request() .withMethod("GET") .withPath(calculatePath("some_pathRequest")) .withCookies( cookie(not("requestCookieNameOne"), not("requestCookieValueOne")), cookie("requestCookieNameTwo", "requestCookieValueTwo") ) ) .respond( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body_response") ); // then // wrong query string cookie name assertEquals( response() .withHeader(HttpHeaders.CONTENT_TYPE, TEXT_PLAIN) .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body_response"), makeRequest( request() .withMethod("GET") .withPath(calculatePath("some_pathRequest")) .withCookies( cookie("OTHERrequestCookieNameOne", "requestCookieValueOne"), cookie("requestCookieNameTwo", "requestCookieValueTwo") ), headersToIgnore) ); // wrong query string cookie value assertEquals( response() .withHeader(HttpHeaders.CONTENT_TYPE, TEXT_PLAIN) .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body_response"), makeRequest( request() .withMethod("GET") .withPath(calculatePath("some_pathRequest")) .withCookies( cookie("requestCookieNameOne", "OTHERrequestCookieValueOne"), cookie("requestCookieNameTwo", "requestCookieValueTwo") ), headersToIgnore) ); } @Test public void shouldReturnResponseByNotMatchingCookieWithNotOperatorForName() { // when mockServerClient .when( request() .withMethod("GET") .withPath(calculatePath("some_pathRequest")) .withCookies( cookie(not("requestCookieNameOne"), string("requestCookieValueOne")), cookie("requestCookieNameTwo", "requestCookieValueTwo") ) ) .respond( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body_response") ); // then // wrong query string cookie name assertEquals( response() .withHeader(HttpHeaders.CONTENT_TYPE, TEXT_PLAIN) .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body_response"), makeRequest( request() .withMethod("GET") .withPath(calculatePath("some_pathRequest")) .withCookies( cookie("OTHERrequestCookieNameOne", "requestCookieValueOne"), cookie("requestCookieNameTwo", "requestCookieValueTwo") ), headersToIgnore) ); } @Test public void shouldReturnResponseByNotMatchingCookieWithNotOperatorForValue() { // when mockServerClient .when( request() .withMethod("GET") .withPath(calculatePath("some_pathRequest")) .withCookies( cookie(string("requestCookieNameOne"), not("requestCookieValueOne")), cookie("requestCookieNameTwo", "requestCookieValueTwo") ) ) .respond( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body_response") ); // then // wrong query string cookie value assertEquals( response() .withHeader(HttpHeaders.CONTENT_TYPE, TEXT_PLAIN) .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body_response"), makeRequest( request() .withMethod("GET") .withPath(calculatePath("some_pathRequest")) .withCookies( cookie("requestCookieNameOne", "OTHERrequestCookieValueOne"), cookie("requestCookieNameTwo", "requestCookieValueTwo") ), headersToIgnore) ); } @Test public void shouldReturnResponseByNotMatchingHeaderWithNotOperatorForNameAndValue() { // when mockServerClient .when( request() .withMethod("GET") .withPath(calculatePath("some_pathRequest")) .withHeaders( header(not("requestHeaderNameOne"), not("requestHeaderValueOne")), header("requestHeaderNameTwo", "requestHeaderValueTwo") ) ) .respond( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body_response") ); // then // wrong query string header name assertEquals( response() .withHeader(HttpHeaders.CONTENT_TYPE, TEXT_PLAIN) .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body_response"), makeRequest( request() .withMethod("GET") .withPath(calculatePath("some_pathRequest")) .withHeaders( header("OTHERrequestHeaderNameOne", "requestHeaderValueOne"), header("requestHeaderNameTwo", "requestHeaderValueTwo") ), headersToIgnore) ); // wrong query string header value assertEquals( response() .withHeader(HttpHeaders.CONTENT_TYPE, TEXT_PLAIN) .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body_response"), makeRequest( request() .withMethod("GET") .withPath(calculatePath("some_pathRequest")) .withHeaders( header("requestHeaderNameOne", "OTHERrequestHeaderValueOne"), header("requestHeaderNameTwo", "requestHeaderValueTwo") ), headersToIgnore) ); } @Test public void shouldReturnResponseByNotMatchingHeaderWithNotOperatorForName() { // when mockServerClient .when( request() .withMethod("GET") .withPath(calculatePath("some_pathRequest")) .withHeaders( header(not("requestHeaderNameOne"), string("requestHeaderValueOne")), header("requestHeaderNameTwo", "requestHeaderValueTwo") ) ) .respond( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body_response") ); // then // wrong query string header name assertEquals( response() .withHeader(HttpHeaders.CONTENT_TYPE, TEXT_PLAIN) .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body_response"), makeRequest( request() .withMethod("GET") .withPath(calculatePath("some_pathRequest")) .withHeaders( header("OTHERrequestHeaderNameOne", "requestHeaderValueOne"), header("requestHeaderNameTwo", "requestHeaderValueTwo") ), headersToIgnore) ); } @Test public void shouldReturnResponseByNotMatchingHeaderWithNotOperatorForValue() { // when mockServerClient .when( request() .withMethod("GET") .withPath(calculatePath("some_pathRequest")) .withHeaders( header(string("requestHeaderNameOne"), not("requestHeaderValueOne")), header("requestHeaderNameTwo", "requestHeaderValueTwo") ) ) .respond( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body_response") ); // then // wrong query string header value assertEquals( response() .withHeader(HttpHeaders.CONTENT_TYPE, TEXT_PLAIN) .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body_response"), makeRequest( request() .withMethod("GET") .withPath(calculatePath("some_pathRequest")) .withHeaders( header("requestHeaderNameOne", "OTHERrequestHeaderValueOne"), header("requestHeaderNameTwo", "requestHeaderValueTwo") ), headersToIgnore) ); } @Test public void shouldNotReturnResponseForWhenTimeToLiveExpired() { // when mockServerClient .when( request().withPath(calculatePath("some_path")), exactly(2), TimeToLive.exactly(TimeUnit.SECONDS, 5L) ) .respond( response().withBody("some_body").withDelay(TimeUnit.SECONDS, 5L) ); // then assertEquals( response() .withHeader(HttpHeaders.CONTENT_TYPE, TEXT_PLAIN) .withStatusCode(HttpStatusCode.OK_200.code()) .withBody("some_body"), makeRequest( request() .withPath(calculatePath("some_path")), headersToIgnore) ); // - in http assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()), makeRequest( request() .withPath(calculatePath("some_path")), headersToIgnore) ); // - in https assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()), makeRequest( request() .withSecure(true) .withPath(calculatePath("some_path")), headersToIgnore) ); } @Test public void shouldNotReturnResponseForNonMatchingBody() { // when mockServerClient .when( request() .withMethod("GET") .withPath(calculatePath("some_path")) .withQueryStringParameters( param("queryStringParameterOneName", "queryStringParameterOneValue"), param("queryStringParameterTwoName", "queryStringParameterTwoValue") ) .withBody(exact("some_body")) .withHeaders(header("headerName", "headerValue")) .withCookies(cookie("cookieName", "cookieValue")) ) .respond( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body") .withHeaders(header("headerName", "headerValue")) .withCookies(cookie("cookieName", "cookieValue")) ); // then // - in http assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()), makeRequest( request() .withMethod("GET") .withPath(calculatePath("some_path")) .withQueryStringParameters( param("queryStringParameterOneName", "queryStringParameterOneValue"), param("queryStringParameterTwoName", "queryStringParameterTwoValue") ) .withBody(exact("some_other_body")) .withHeaders(header("headerName", "headerValue")) .withCookies(cookie("cookieName", "cookieValue")), headersToIgnore) ); // - in https assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()), makeRequest( request() .withMethod("GET") .withSecure(true) .withPath(calculatePath("some_path")) .withQueryStringParameters( param("queryStringParameterOneName", "queryStringParameterOneValue"), param("queryStringParameterTwoName", "queryStringParameterTwoValue") ) .withBody(exact("some_other_body")) .withHeaders(header("headerName", "headerValue")) .withCookies(cookie("cookieName", "cookieValue")), headersToIgnore) ); } @Test public void shouldNotReturnResponseForMatchingBodyWithNotOperator() { // when mockServerClient .when( request() .withBody(Not.not(json("{" + System.getProperty("line.separator") + " \"id\": 1," + System.getProperty("line.separator") + " \"name\": \"A green door\"," + System.getProperty("line.separator") + " \"price\": 12.50," + System.getProperty("line.separator") + " \"tags\": [\"home\", \"green\"]" + System.getProperty("line.separator") + "}"))), exactly(2) ) .respond( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body") ); // then // - in http assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()), makeRequest( request() .withPath(calculatePath("some_path")) .withMethod("POST") .withBody("{" + System.getProperty("line.separator") + " \"id\": 1," + System.getProperty("line.separator") + " \"extra_ignored_field\": \"some value\"," + System.getProperty("line.separator") + " \"name\": \"A green door\"," + System.getProperty("line.separator") + " \"price\": 12.50," + System.getProperty("line.separator") + " \"tags\": [\"home\", \"green\"]" + System.getProperty("line.separator") + "}"), headersToIgnore) ); // - in https assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()), makeRequest( request() .withSecure(true) .withPath(calculatePath("some_path")) .withMethod("POST") .withBody("{" + System.getProperty("line.separator") + " \"id\": 1," + System.getProperty("line.separator") + " \"extra_ignored_array\": [\"one\", \"two\"]," + System.getProperty("line.separator") + " \"name\": \"A green door\"," + System.getProperty("line.separator") + " \"price\": 12.50," + System.getProperty("line.separator") + " \"tags\": [\"home\", \"green\"]" + System.getProperty("line.separator") + "}"), headersToIgnore) ); } @Test public void shouldNotReturnResponseForNonMatchingXPathBody() { // when mockServerClient.when(request().withBody(new XPathBody("/bookstore/book[price>35]/price")), exactly(2)).respond(response().withBody("some_body")); // then // - in http assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()), makeRequest( request() .withSecure(true) .withPath(calculatePath("some_path")) .withMethod("POST") .withBody(new StringBody("" + "<?xml version=\"1.0\" encoding=\"ISO-8859-1\"?>" + System.getProperty("line.separator") + "<bookstore>" + System.getProperty("line.separator") + " <book category=\"COOKING\">" + System.getProperty("line.separator") + " <title lang=\"en\">Everyday Italian</title>" + System.getProperty("line.separator") + " <author>Giada De Laurentiis</author>" + System.getProperty("line.separator") + " <year>2005</year>" + System.getProperty("line.separator") + " <price>30.00</price>" + System.getProperty("line.separator") + " </book>" + System.getProperty("line.separator") + " <book category=\"CHILDREN\">" + System.getProperty("line.separator") + " <title lang=\"en\">Harry Potter</title>" + System.getProperty("line.separator") + " <author>J K. Rowling</author>" + System.getProperty("line.separator") + " <year>2005</year>" + System.getProperty("line.separator") + " <price>29.99</price>" + System.getProperty("line.separator") + " </book>" + System.getProperty("line.separator") + " <book category=\"WEB\">" + System.getProperty("line.separator") + " <title lang=\"en\">Learning XML</title>" + System.getProperty("line.separator") + " <author>Erik T. Ray</author>" + System.getProperty("line.separator") + " <year>2003</year>" + System.getProperty("line.separator") + " <price>31.95</price>" + System.getProperty("line.separator") + " </book>" + System.getProperty("line.separator") + "</bookstore>")), headersToIgnore) ); // - in https assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()), makeRequest( request() .withSecure(true) .withPath(calculatePath("some_path")) .withMethod("POST") .withBody(new StringBody("" + "<?xml version=\"1.0\" encoding=\"ISO-8859-1\"?>" + System.getProperty("line.separator") + "<bookstore>" + System.getProperty("line.separator") + " <book category=\"COOKING\">" + System.getProperty("line.separator") + " <title lang=\"en\">Everyday Italian</title>" + System.getProperty("line.separator") + " <author>Giada De Laurentiis</author>" + System.getProperty("line.separator") + " <year>2005</year>" + System.getProperty("line.separator") + " <price>30.00</price>" + System.getProperty("line.separator") + " </book>" + System.getProperty("line.separator") + " <book category=\"CHILDREN\">" + System.getProperty("line.separator") + " <title lang=\"en\">Harry Potter</title>" + System.getProperty("line.separator") + " <author>J K. Rowling</author>" + System.getProperty("line.separator") + " <year>2005</year>" + System.getProperty("line.separator") + " <price>29.99</price>" + System.getProperty("line.separator") + " </book>" + System.getProperty("line.separator") + " <book category=\"WEB\">" + System.getProperty("line.separator") + " <title lang=\"en\">Learning XML</title>" + System.getProperty("line.separator") + " <author>Erik T. Ray</author>" + System.getProperty("line.separator") + " <year>2003</year>" + System.getProperty("line.separator") + " <price>31.95</price>" + System.getProperty("line.separator") + " </book>" + System.getProperty("line.separator") + "</bookstore>")), headersToIgnore) ); } @Test public void shouldNotReturnResponseForNonMatchingJsonBody() { // when mockServerClient.when(request().withBody(json("{" + System.getProperty("line.separator") + " \"id\": 1," + System.getProperty("line.separator") + " \"name\": \"A green door\"," + System.getProperty("line.separator") + " \"price\": 12.50," + System.getProperty("line.separator") + " \"tags\": [\"home\", \"green\"]" + System.getProperty("line.separator") + "}")), exactly(2)).respond(response().withBody("some_body")); // then // - in http assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()), makeRequest( request() .withPath(calculatePath("some_path")) .withMethod("POST") .withBody("{" + System.getProperty("line.separator") + " \"id\": 1," + System.getProperty("line.separator") + " \"name\": \"---- XXXX WRONG VALUE XXXX ----\"," + System.getProperty("line.separator") + " \"price\": 12.50," + System.getProperty("line.separator") + " \"tags\": [\"home\", \"green\"]" + System.getProperty("line.separator") + "}"), headersToIgnore) ); // - in https assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()), makeRequest( request() .withSecure(true) .withPath(calculatePath("some_path")) .withMethod("POST") .withBody("{" + System.getProperty("line.separator") + " \"id\": 1," + System.getProperty("line.separator") + " \"name\": \"---- XXXX WRONG VALUE XXXX ----\"," + System.getProperty("line.separator") + " \"price\": 12.50," + System.getProperty("line.separator") + " \"tags\": [\"home\", \"green\"]" + System.getProperty("line.separator") + "}"), headersToIgnore) ); } @Test public void shouldNotReturnResponseForNonMatchingJsonBodyWithMatchType() { // when mockServerClient .when( request() .withBody(json("{" + System.getProperty("line.separator") + " \"id\": 1," + System.getProperty("line.separator") + " \"name\": \"A green door\"," + System.getProperty("line.separator") + " \"price\": 12.50," + System.getProperty("line.separator") + " \"tags\": [\"home\", \"green\"]" + System.getProperty("line.separator") + "}", MatchType.STRICT)), exactly(2)) .respond( response() .withBody("some_body") ); // then // - in http assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()), makeRequest( request() .withPath(calculatePath("some_path")) .withMethod("POST") .withBody("{" + System.getProperty("line.separator") + " \"id\": 1," + System.getProperty("line.separator") + " \"extra field\": \"some value\"," + System.getProperty("line.separator") + " \"name\": \"A green door\"," + System.getProperty("line.separator") + " \"price\": 12.50," + System.getProperty("line.separator") + " \"tags\": [\"home\", \"green\"]" + System.getProperty("line.separator") + "}"), headersToIgnore) ); // - in https assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()), makeRequest( request() .withSecure(true) .withPath(calculatePath("some_path")) .withMethod("POST") .withBody("{" + System.getProperty("line.separator") + " \"id\": 1," + System.getProperty("line.separator") + " \"extra field\": \"some value\"," + System.getProperty("line.separator") + " \"name\": \"A green door\"," + System.getProperty("line.separator") + " \"price\": 12.50," + System.getProperty("line.separator") + " \"tags\": [\"home\", \"green\"]" + System.getProperty("line.separator") + "}"), headersToIgnore) ); } @Test public void shouldNotReturnResponseForNonMatchingJsonSchema() { // when mockServerClient.when(request().withBody(jsonSchema("{" + System.getProperty("line.separator") + " \"$schema\": \"http://json-schema.org/draft-04/schema#\"," + System.getProperty("line.separator") + " \"title\": \"Product\"," + System.getProperty("line.separator") + " \"description\": \"A product from Acme's catalog\"," + System.getProperty("line.separator") + " \"type\": \"object\"," + System.getProperty("line.separator") + " \"properties\": {" + System.getProperty("line.separator") + " \"id\": {" + System.getProperty("line.separator") + " \"description\": \"The unique identifier for a product\"," + System.getProperty("line.separator") + " \"type\": \"integer\"" + System.getProperty("line.separator") + " }," + System.getProperty("line.separator") + " \"name\": {" + System.getProperty("line.separator") + " \"description\": \"Name of the product\"," + System.getProperty("line.separator") + " \"type\": \"string\"" + System.getProperty("line.separator") + " }," + System.getProperty("line.separator") + " \"price\": {" + System.getProperty("line.separator") + " \"type\": \"number\"," + System.getProperty("line.separator") + " \"minimum\": 0," + System.getProperty("line.separator") + " \"exclusiveMinimum\": true" + System.getProperty("line.separator") + " }," + System.getProperty("line.separator") + " \"tags\": {" + System.getProperty("line.separator") + " \"type\": \"array\"," + System.getProperty("line.separator") + " \"items\": {" + System.getProperty("line.separator") + " \"type\": \"string\"" + System.getProperty("line.separator") + " }," + System.getProperty("line.separator") + " \"minItems\": 1," + System.getProperty("line.separator") + " \"uniqueItems\": true" + System.getProperty("line.separator") + " }" + System.getProperty("line.separator") + " }," + System.getProperty("line.separator") + " \"required\": [\"id\", \"name\", \"price\"]" + System.getProperty("line.separator") + "}")), exactly(2)).respond(response().withBody("some_body")); // then // - in http assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()), makeRequest( request() .withPath(calculatePath("some_path")) .withMethod("POST") .withBody("{" + System.getProperty("line.separator") + " \"id\": 1," + System.getProperty("line.separator") + " \"wrong field name\": \"A green door\"," + System.getProperty("line.separator") + " \"price\": 12.50," + System.getProperty("line.separator") + " \"tags\": [\"home\", \"green\"]" + System.getProperty("line.separator") + "}"), headersToIgnore) ); // - in https assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()), makeRequest( request() .withSecure(true) .withPath(calculatePath("some_path")) .withMethod("POST") .withBody("{" + System.getProperty("line.separator") + " \"id\": 1," + System.getProperty("line.separator") + " \"name\": \"A green door\"," + System.getProperty("line.separator") + " \"wrong field name\": 12.50," + System.getProperty("line.separator") + " \"tags\": [\"home\", \"green\"]" + System.getProperty("line.separator") + "}"), headersToIgnore) ); } @Test public void shouldNotReturnResponseForNonMatchingPath() { // when mockServerClient .when( request() .withMethod("GET") .withPath(calculatePath("some_path")) .withQueryStringParameters( param("queryStringParameterOneName", "queryStringParameterOneValue"), param("queryStringParameterTwoName", "queryStringParameterTwoValue") ) .withBody(exact("some_body")) .withHeaders(header("headerName", "headerValue")) .withCookies(cookie("cookieName", "cookieValue")) ) .respond( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body") .withHeaders(header("headerName", "headerValue")) .withCookies(cookie("cookieName", "cookieValue")) ); // then // - in http assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()), makeRequest( request() .withMethod("GET") .withPath(calculatePath("some_other_path")) .withQueryStringParameters( param("queryStringParameterOneName", "queryStringParameterOneValue"), param("queryStringParameterTwoName", "queryStringParameterTwoValue") ) .withBody(exact("some_body")) .withHeaders(header("headerName", "headerValue")) .withCookies(cookie("cookieName", "cookieValue")), headersToIgnore) ); // - in https assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()), makeRequest( request() .withMethod("GET") .withSecure(true) .withPath(calculatePath("some_other_path")) .withQueryStringParameters( param("queryStringParameterOneName", "queryStringParameterOneValue"), param("queryStringParameterTwoName", "queryStringParameterTwoValue") ) .withBody(exact("some_body")) .withHeaders(header("headerName", "headerValue")) .withCookies(cookie("cookieName", "cookieValue")), headersToIgnore) ); } @Test public void shouldNotReturnResponseForMatchingPathWithNotOperator() { // when mockServerClient .when( request() .withPath(not(calculatePath("some_path"))) ) .respond( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body_response") ); // then // - in http assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()), makeRequest( request() .withPath(calculatePath("some_path")), headersToIgnore) ); // - in https assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()), makeRequest( request() .withPath(calculatePath("some_path")), headersToIgnore) ); } @Test public void shouldNotReturnResponseForMatchingMethodWithNotOperator() { // when mockServerClient .when( request() .withMethod(not("GET")) ) .respond( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body_response") ); // then // - in http assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()), makeRequest( request() .withMethod("GET"), headersToIgnore) ); // - in https assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()), makeRequest( request() .withMethod("GET"), headersToIgnore) ); } @Test public void shouldNotReturnResponseForNonMatchingBodyParameterName() { // when mockServerClient .when( request() .withMethod("POST") .withPath(calculatePath("some_pathRequest")) .withBody(params( param("bodyParameterOneName", "Parameter One Value One", "Parameter One Value Two"), param("bodyParameterTwoName", "Parameter Two") )) ) .respond( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body_response") .withHeaders(header("headerNameResponse", "headerValueResponse")) .withCookies(cookie("cookieNameResponse", "cookieValueResponse")) ); // then // wrong query string parameter name assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()), makeRequest( request() .withMethod("POST") .withPath(calculatePath("some_pathRequest")) .withBody(params( param("OTHERBodyParameterOneName", "Parameter One Value One", "Parameter One Value Two"), param("bodyParameterTwoName", "Parameter Two") )) .withHeaders(header("headerNameRequest", "headerValueRequest")) .withCookies(cookie("cookieNameRequest", "cookieValueRequest")), headersToIgnore) ); // wrong query string parameter name assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()), makeRequest( request() .withMethod("POST") .withPath(calculatePath("some_pathRequest")) .withBody(new StringBody("OTHERBodyParameterOneName=Parameter+One+Value+One" + "&bodyParameterOneName=Parameter+One+Value+Two" + "&bodyParameterTwoName=Parameter+Two")) .withHeaders(header("headerNameRequest", "headerValueRequest")) .withCookies(cookie("cookieNameRequest", "cookieValueRequest")), headersToIgnore) ); } @Test public void shouldNotReturnResponseForMatchingBodyParameterWithNotOperator() { // when mockServerClient .when( request() .withMethod("POST") .withPath(calculatePath("some_pathRequest")) .withBody(params( param(not("bodyParameterOneName"), not("Parameter One Value One"), not("Parameter One Value Two")), param("bodyParameterTwoName", "Parameter Two") )) ) .respond( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body_response") ); // then // wrong query string parameter name assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()), makeRequest( request() .withMethod("POST") .withPath(calculatePath("some_pathRequest")) .withBody(params( param("bodyParameterOneName", "Parameter One Value One", "Parameter One Value Two"), param("bodyParameterTwoName", "Parameter Two") )) .withHeaders(header("headerNameRequest", "headerValueRequest")) .withCookies(cookie("cookieNameRequest", "cookieValueRequest")), headersToIgnore) ); // wrong query string parameter name assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()), makeRequest( request() .withMethod("POST") .withPath(calculatePath("some_pathRequest")) .withBody(new StringBody("bodyParameterOneName=Other Parameter+One+Value+One" + "&bodyParameterOneName=Parameter+One+Value+Two" + "&bodyParameterTwoName=Parameter+Two")) .withHeaders(header("headerNameRequest", "headerValueRequest")) .withCookies(cookie("cookieNameRequest", "cookieValueRequest")), headersToIgnore) ); } @Test public void shouldNotReturnResponseForNonMatchingBodyParameterValue() { // when mockServerClient .when( request() .withMethod("POST") .withPath(calculatePath("some_pathRequest")) .withBody(params( param("bodyParameterOneName", "Parameter One Value One", "Parameter One Value Two"), param("bodyParameterTwoName", "Parameter Two") )) ) .respond( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body_response") .withHeaders(header("headerNameResponse", "headerValueResponse")) .withCookies(cookie("cookieNameResponse", "cookieValueResponse")) ); // then // wrong body parameter value assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()), makeRequest( request() .withMethod("POST") .withPath(calculatePath("some_pathRequest")) .withBody(params( param("bodyParameterOneName", "Other Parameter One Value One", "Parameter One Value Two"), param("bodyParameterTwoName", "Parameter Two") )) .withHeaders(header("headerNameRequest", "headerValueRequest")) .withCookies(cookie("cookieNameRequest", "cookieValueRequest")), headersToIgnore) ); // wrong body parameter value assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()), makeRequest( request() .withMethod("POST") .withPath(calculatePath("some_pathRequest")) .withBody(new StringBody("bodyParameterOneName=Other Parameter+One+Value+One" + "&bodyParameterOneName=Parameter+One+Value+Two" + "&bodyParameterTwoName=Parameter+Two")) .withHeaders(header("headerNameRequest", "headerValueRequest")) .withCookies(cookie("cookieNameRequest", "cookieValueRequest")), headersToIgnore) ); } @Test public void shouldNotReturnResponseForNonMatchingQueryStringParameterName() { // when mockServerClient .when( request() .withMethod("POST") .withPath(calculatePath("some_pathRequest")) .withQueryStringParameters( param("queryStringParameterOneName", "queryStringParameterOneValueOne", "queryStringParameterOneValueTwo"), param("queryStringParameterTwoName", "queryStringParameterTwoValue") ) .withBody("some_bodyRequest") ) .respond( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body_response") .withHeaders(header("headerNameResponse", "headerValueResponse")) .withCookies(cookie("cookieNameResponse", "cookieValueResponse")) ); // then // wrong query string parameter name assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()), makeRequest( request() .withMethod("POST") .withPath(calculatePath("some_pathRequest")) .withQueryStringParameters( param("OTHERQueryStringParameterOneName", "queryStringParameterOneValueOne", "queryStringParameterOneValueTwo"), param("queryStringParameterTwoName", "queryStringParameterTwoValue") ) .withBody("some_bodyRequest") .withHeaders( header("headerNameRequest", "headerValueRequest") ) .withCookies(cookie("cookieNameRequest", "cookieValueRequest")), headersToIgnore) ); } @Test public void shouldNotReturnResponseForNonMatchingQueryStringParameterValue() { // when mockServerClient .when( request() .withMethod("POST") .withPath(calculatePath("some_pathRequest")) .withQueryStringParameters( param("queryStringParameterOneName", "queryStringParameterOneValueOne", "queryStringParameterOneValueTwo"), param("queryStringParameterTwoName", "queryStringParameterTwoValue") ) .withBody("some_bodyRequest") ) .respond( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body_response") .withHeaders(header("headerNameResponse", "headerValueResponse")) .withCookies(cookie("cookieNameResponse", "cookieValueResponse")) ); // then // wrong query string parameter value assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()), makeRequest( request() .withMethod("POST") .withPath(calculatePath("some_pathRequest")) .withQueryStringParameters( param("queryStringParameterOneName", "OTHERqueryStringParameterOneValueOne", "queryStringParameterOneValueTwo"), param("queryStringParameterTwoName", "queryStringParameterTwoValue") ) .withBody("some_bodyRequest") .withHeaders(header("headerNameRequest", "headerValueRequest")) .withCookies(cookie("cookieNameRequest", "cookieValueRequest")), headersToIgnore) ); } @Test public void shouldNotReturnResponseForMatchingQueryStringParameterWithNotOperator() { // when mockServerClient .when( request() .withMethod("POST") .withPath(calculatePath("some_pathRequest")) .withQueryStringParameters( param(not("queryStringParameterOneName"), not("Parameter One Value One"), not("Parameter One Value Two")), param("queryStringParameterTwoName", "Parameter Two") ) ) .respond( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body_response") ); // then // wrong query string parameter name assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()), makeRequest( request() .withMethod("POST") .withPath(calculatePath("some_pathRequest")) .withQueryStringParameters( param("queryStringParameterOneName", "Parameter One Value One", "Parameter One Value Two"), param("queryStringParameterTwoName", "Parameter Two") ), headersToIgnore) ); // wrong query string parameter name assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()), makeRequest( request() .withMethod("POST") .withPath(calculatePath("some_pathRequest")) .withQueryStringParameters( param("queryStringParameterOneName", "Parameter One Value One", "Parameter One Value Two"), param("queryStringParameterTwoName", "Parameter Two") ), headersToIgnore) ); } @Test public void shouldNotReturnResponseForNonMatchingCookieName() { // when mockServerClient .when( request() .withMethod("GET") .withPath(calculatePath("some_path")) .withQueryStringParameters( param("queryStringParameterOneName", "queryStringParameterOneValue"), param("queryStringParameterTwoName", "queryStringParameterTwoValue") ) .withBody(exact("some_body")) .withHeaders(header("headerName", "headerValue")) .withCookies(cookie("cookieName", "cookieValue")) ) .respond( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body") .withHeaders(header("headerName", "headerValue")) .withCookies(cookie("cookieName", "cookieValue")) ); // then // - in http assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()), makeRequest( request() .withMethod("GET") .withPath(calculatePath("some_path")) .withQueryStringParameters( param("queryStringParameterOneName", "queryStringParameterOneValue"), param("queryStringParameterTwoName", "queryStringParameterTwoValue") ) .withBody(exact("some_body")) .withHeaders(header("headerName", "headerValue")) .withCookies(cookie("cookieOtherName", "cookieValue")), headersToIgnore) ); // - in https assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()), makeRequest( request() .withMethod("GET") .withSecure(true) .withPath(calculatePath("some_path")) .withQueryStringParameters( param("queryStringParameterOneName", "queryStringParameterOneValue"), param("queryStringParameterTwoName", "queryStringParameterTwoValue") ) .withBody(exact("some_body")) .withHeaders(header("headerName", "headerValue")) .withCookies(cookie("cookieOtherName", "cookieValue")), headersToIgnore) ); } @Test public void shouldNotReturnResponseForNonMatchingCookieValue() { // when mockServerClient .when( request() .withMethod("GET") .withPath(calculatePath("some_path")) .withQueryStringParameters( param("queryStringParameterOneName", "queryStringParameterOneValue"), param("queryStringParameterTwoName", "queryStringParameterTwoValue") ) .withBody(exact("some_body")) .withHeaders(header("headerName", "headerValue")) .withCookies(cookie("cookieName", "cookieValue")) ) .respond( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body") .withHeaders(header("headerName", "headerValue")) .withCookies(cookie("cookieName", "cookieValue")) ); // then // - in http assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()), makeRequest( request() .withMethod("GET") .withPath(calculatePath("some_path")) .withQueryStringParameters( param("queryStringParameterOneName", "queryStringParameterOneValue"), param("queryStringParameterTwoName", "queryStringParameterTwoValue") ) .withBody(exact("some_body")) .withHeaders(header("headerName", "headerValue")) .withCookies(cookie("cookieName", "cookieOtherValue")), headersToIgnore) ); // - in https assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()), makeRequest( request() .withMethod("GET") .withSecure(true) .withPath(calculatePath("some_path")) .withQueryStringParameters( param("queryStringParameterOneName", "queryStringParameterOneValue"), param("queryStringParameterTwoName", "queryStringParameterTwoValue") ) .withBody(exact("some_body")) .withHeaders(header("headerName", "headerValue")) .withCookies(cookie("cookieName", "cookieOtherValue")), headersToIgnore) ); } @Test public void shouldNotReturnResponseForMatchingCookieWithNotOperator() { // when mockServerClient .when( request() .withMethod("GET") .withPath(calculatePath("some_pathRequest")) .withCookies( cookie(not("requestCookieNameOne"), not("requestCookieValueOne")), cookie("requestCookieNameTwo", "requestCookieValueTwo") ) ) .respond( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body_response") ); // then // wrong query string parameter name assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()), makeRequest( request() .withMethod("GET") .withPath(calculatePath("some_pathRequest")) .withCookies( cookie("requestCookieNameOne", "requestCookieValueOne"), cookie("requestCookieNameTwo", "requestCookieValueTwo") ), headersToIgnore) ); // wrong query string parameter name assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()), makeRequest( request() .withMethod("GET") .withPath(calculatePath("some_pathRequest")) .withCookies( cookie("requestCookieNameOne", "requestCookieValueOne"), cookie("requestCookieNameTwo", "requestCookieValueTwo") ), headersToIgnore) ); } @Test public void shouldNotReturnResponseForNonMatchingHeaderName() { // when mockServerClient .when( request() .withMethod("GET") .withPath(calculatePath("some_path")) .withQueryStringParameters( param("queryStringParameterOneName", "queryStringParameterOneValue"), param("queryStringParameterTwoName", "queryStringParameterTwoValue") ) .withBody(exact("some_body")) .withHeaders(header("headerName", "headerValue")) .withCookies(cookie("cookieName", "cookieValue")) ) .respond( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body") .withHeaders(header("headerName", "headerValue")) .withCookies(cookie("cookieName", "cookieValue")) ); // then // - in http assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()), makeRequest( request() .withMethod("GET") .withPath(calculatePath("some_path")) .withQueryStringParameters( param("queryStringParameterOneName", "queryStringParameterOneValue"), param("queryStringParameterTwoName", "queryStringParameterTwoValue") ) .withBody(exact("some_body")) .withHeaders(header("headerOtherName", "headerValue")) .withCookies(cookie("cookieName", "cookieValue")), headersToIgnore) ); // - in https assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()), makeRequest( request() .withMethod("GET") .withSecure(true) .withPath(calculatePath("some_path")) .withQueryStringParameters( param("queryStringParameterOneName", "queryStringParameterOneValue"), param("queryStringParameterTwoName", "queryStringParameterTwoValue") ) .withBody(exact("some_body")) .withHeaders(header("headerOtherName", "headerValue")) .withCookies(cookie("cookieName", "cookieValue")), headersToIgnore) ); } @Test public void shouldNotReturnResponseForNonMatchingHeaderValue() { // when mockServerClient .when( request() .withMethod("GET") .withPath(calculatePath("some_path")) .withQueryStringParameters( param("queryStringParameterOneName", "queryStringParameterOneValue"), param("queryStringParameterTwoName", "queryStringParameterTwoValue") ) .withBody(exact("some_body")) .withHeaders(header("headerName", "headerValue")) .withCookies(cookie("cookieName", "cookieValue")) ) .respond( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body") .withHeaders(header("headerName", "headerValue")) .withCookies(cookie("cookieName", "cookieValue")) ); // then // - in http assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()), makeRequest( request() .withMethod("GET") .withPath(calculatePath("some_path")) .withQueryStringParameters( param("queryStringParameterOneName", "queryStringParameterOneValue"), param("queryStringParameterTwoName", "queryStringParameterTwoValue") ) .withBody(exact("some_body")) .withHeaders(header("headerName", "headerOtherValue")) .withCookies(cookie("cookieName", "cookieValue")), headersToIgnore) ); // - in https assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()), makeRequest( request() .withMethod("GET") .withSecure(true) .withPath(calculatePath("some_path")) .withQueryStringParameters( param("queryStringParameterOneName", "queryStringParameterOneValue"), param("queryStringParameterTwoName", "queryStringParameterTwoValue") ) .withBody(exact("some_body")) .withHeaders(header("headerName", "headerOtherValue")) .withCookies(cookie("cookieName", "cookieValue")), headersToIgnore) ); } @Test public void shouldNotReturnResponseForMatchingHeaderWithNotOperator() { // when mockServerClient .when( request() .withMethod("GET") .withPath(calculatePath("some_pathRequest")) .withHeaders( header(not("requestHeaderNameOne"), not("requestHeaderValueOne")), header("requestHeaderNameTwo", "requestHeaderValueTwo") ) ) .respond( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body_response") ); // then // wrong query string parameter name assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()), makeRequest( request() .withMethod("GET") .withPath(calculatePath("some_pathRequest")) .withHeaders( header("requestHeaderNameOne", "requestHeaderValueOne"), header("requestHeaderNameTwo", "requestHeaderValueTwo") ), headersToIgnore) ); // wrong query string parameter name assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()), makeRequest( request() .withMethod("GET") .withPath(calculatePath("some_pathRequest")) .withHeaders( header("requestHeaderNameOne", "requestHeaderValueOne"), header("requestHeaderNameTwo", "requestHeaderValueTwo") ), headersToIgnore) ); } @Test public void shouldClearExpectations() { // given mockServerClient .when( request() .withPath(calculatePath("some_path1")) ) .respond( response() .withBody("some_body1") ); mockServerClient .when( request() .withPath(calculatePath("some_path2")) ) .respond( response() .withBody("some_body2") ); // when mockServerClient .clear( request() .withPath(calculatePath("some_path1")) ); // then // - in http assertEquals( response() .withHeader(HttpHeaders.CONTENT_TYPE, TEXT_PLAIN) .withStatusCode(HttpStatusCode.OK_200.code()) .withBody("some_body2"), makeRequest( request() .withPath(calculatePath("some_path2")), headersToIgnore) ); assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()), makeRequest( request() .withPath(calculatePath("some_path1")), headersToIgnore) ); // - in https assertEquals( response() .withHeader(HttpHeaders.CONTENT_TYPE, TEXT_PLAIN) .withStatusCode(HttpStatusCode.OK_200.code()) .withBody("some_body2"), makeRequest( request() .withSecure(true) .withPath(calculatePath("some_path2")), headersToIgnore) ); assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()), makeRequest( request() .withSecure(true) .withPath(calculatePath("some_path1")), headersToIgnore) ); } @Test public void shouldReset() { // given mockServerClient .when( request() .withPath(calculatePath("some_path1")) ) .respond( response() .withBody("some_body1") ); mockServerClient .when( request() .withPath(calculatePath("some_path2")) ) .respond( response() .withBody("some_body2") ); // when mockServerClient.reset(); // then // - in http assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()), makeRequest( request() .withPath(calculatePath("some_path1")), headersToIgnore) ); assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()), makeRequest( request() .withPath(calculatePath("some_path2")), headersToIgnore) ); // - in https assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()), makeRequest( request() .withSecure(true) .withPath(calculatePath("some_path1")), headersToIgnore) ); assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()), makeRequest( request() .withSecure(true) .withPath(calculatePath("some_path2")), headersToIgnore) ); } @Test public void shouldEnsureThatRequestDelaysDoNotAffectOtherRequests() throws Exception { mockServerClient .when( request("/slow") ) .respond( response("super slow") .withDelay(new Delay(TimeUnit.SECONDS, 8)) ); mockServerClient .when( request("/fast") ) .respond( response("quite fast") ); ExecutorService executorService = Executors.newFixedThreadPool(2); Future<Long> slowFuture = executorService.submit(new Callable<Long>() { @Override public Long call() throws Exception { long start = System.currentTimeMillis(); makeRequest(request("/slow")); return System.currentTimeMillis() - start; } }); // Let fast request come to the server slightly after slow request Uninterruptibles.sleepUninterruptibly(1, TimeUnit.SECONDS); Future<Long> fastFuture = executorService.submit(new Callable<Long>() { @Override public Long call() throws Exception { long start = System.currentTimeMillis(); makeRequest(request("/fast")); return System.currentTimeMillis() - start; } }); Long slowRequestElapsedMillis = slowFuture.get(); Long fastRequestElapsedMillis = fastFuture.get(); assertThat("Slow request takes less than expected", slowRequestElapsedMillis, is(greaterThan(7 * 1000L))); assertThat("Fast request takes longer than expected", fastRequestElapsedMillis, is(lessThan(3 * 1000L))); } protected HttpResponse makeRequest(HttpRequest httpRequest) { return makeRequest(httpRequest, Collections.<String>emptySet()); } protected HttpResponse makeRequest(HttpRequest httpRequest, Collection<String> headersToIgnore) { int attemptsRemaining = 10; while (attemptsRemaining > 0) { try { boolean isSsl = httpRequest.isSecure() != null && httpRequest.isSecure(); int port = (isSsl ? getMockServerSecurePort() : getMockServerPort()); HttpResponse httpResponse = httpClient.sendRequest(outboundRequest("localhost", port, servletContext, httpRequest)); List<Header> headers = new ArrayList<Header>(); for (Header header : httpResponse.getHeaders()) { if (!headersToIgnore.contains(header.getName().getValue().toLowerCase())) { if (header.getName().getValue().equalsIgnoreCase(HttpHeaders.CONTENT_TYPE)) { // this fixes Tomcat which removes the space between // media type and charset in the Content-Type header for (NottableString value : new ArrayList<NottableString>(header.getValues())) { header.getValues().clear(); header.addValues(value.getValue().replace(";charset", "; charset")); } } headers.add(header); } } httpResponse.withHeaders(headers); return httpResponse; } catch (SocketConnectionException caught) { attemptsRemaining--; logger.info("Retrying connection to mock server, attempts remaining: " + attemptsRemaining); try { TimeUnit.MILLISECONDS.sleep(500); } catch (InterruptedException e) { // do nothing } } } throw new RuntimeException("Failed to send request:" + System.getProperty("line.separator") + httpRequest); } }
hobofan/mockserver
mockserver-integration-testing/src/main/java/org/mockserver/integration/server/AbstractClientServerIntegrationTest.java
917
package org.mockserver.integration.server; import com.google.common.base.Charsets; import com.google.common.net.HttpHeaders; import com.google.common.net.MediaType; import com.google.common.util.concurrent.Uninterruptibles; import org.apache.commons.io.IOUtils; import org.junit.Before; import org.junit.Test; import org.mockserver.client.netty.NettyHttpClient; import org.mockserver.client.netty.SocketConnectionException; import org.mockserver.client.server.MockServerClient; import org.mockserver.echo.http.EchoServer; import org.mockserver.matchers.*; import org.mockserver.mock.Expectation; import org.mockserver.mock.action.ExpectationCallback; import org.mockserver.model.*; import org.mockserver.socket.PortFactory; import org.mockserver.verify.VerificationTimes; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.IOException; import java.util.*; import java.util.concurrent.*; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.*; import static org.hamcrest.core.Is.is; import static org.hamcrest.core.StringStartsWith.startsWith; import static org.hamcrest.number.OrderingComparison.greaterThan; import static org.junit.Assert.assertEquals; import static org.junit.Assert.fail; import static org.mockserver.matchers.Times.exactly; import static org.mockserver.matchers.Times.once; import static org.mockserver.model.BinaryBody.binary; import static org.mockserver.model.Cookie.cookie; import static org.mockserver.model.Header.header; import static org.mockserver.model.HttpClassCallback.callback; import static org.mockserver.model.HttpForward.forward; import static org.mockserver.model.HttpRequest.request; import static org.mockserver.model.HttpResponse.notFoundResponse; import static org.mockserver.model.HttpResponse.response; import static org.mockserver.model.JsonBody.json; import static org.mockserver.model.JsonSchemaBody.jsonSchema; import static org.mockserver.model.NottableString.not; import static org.mockserver.model.NottableString.string; import static org.mockserver.model.OutboundHttpRequest.outboundRequest; import static org.mockserver.model.Parameter.param; import static org.mockserver.model.ParameterBody.params; import static org.mockserver.model.StringBody.exact; import static org.mockserver.model.XPathBody.xpath; import static org.mockserver.model.XmlBody.xml; /** * @author jamesdbloom */ public abstract class AbstractClientServerIntegrationTest { protected static final String TEXT_PLAIN = MediaType.create("text", "plain").toString(); protected static MockServerClient mockServerClient; protected static String servletContext = ""; private final Logger logger = LoggerFactory.getLogger(this.getClass()); protected List<String> headersToIgnore = Arrays.asList( "server", "expires", "date", "host", "connection", "user-agent", "content-length", "accept-encoding", "transfer-encoding", "access-control-allow-origin", "access-control-allow-methods", "access-control-allow-headers", "access-control-expose-headers", "access-control-max-age", "x-cors" ); private NettyHttpClient httpClient = new NettyHttpClient(); public static Expectation expectation(HttpRequest httpRequest) { return new Expectation(httpRequest, Times.unlimited(), TimeToLive.unlimited()); } public abstract int getMockServerPort(); public abstract int getMockServerSecurePort(); public abstract int getTestServerPort(); protected String calculatePath(String path) { return "/" + path; } @Before public void resetServer() { mockServerClient.reset(); } @Test public void shouldForwardRequestInHTTP() { // when mockServerClient .when( request() .withPath(calculatePath("echo")) ) .forward( forward() .withHost("127.0.0.1") .withPort(getTestServerPort()) ); // then // - in http assertEquals( response() .withStatusCode(HttpStatusCode.OK_200.code()) .withHeaders( header("x-test", "test_headers_and_body") ) .withBody("an_example_body_http"), makeRequest( request() .withPath(calculatePath("echo")) .withMethod("POST") .withHeaders( header("x-test", "test_headers_and_body") ) .withBody("an_example_body_http"), headersToIgnore) ); // - in https assertEquals( response() .withStatusCode(HttpStatusCode.OK_200.code()) .withHeaders( header("x-test", "test_headers_and_body") ) .withBody("an_example_body_https"), makeRequest( request() .withSecure(true) .withPath(calculatePath("echo")) .withMethod("POST") .withHeaders( header("x-test", "test_headers_and_body") ) .withBody("an_example_body_https"), headersToIgnore) ); } @Test public void shouldForwardRequestInHTTPS() { int testServerHttpsPort = PortFactory.findFreePort(); EchoServer secureEchoServer = new EchoServer(testServerHttpsPort, true); try { // when mockServerClient .when( request() .withPath(calculatePath("echo")) ) .forward( forward() .withHost("127.0.0.1") .withPort(testServerHttpsPort) .withScheme(HttpForward.Scheme.HTTPS) ); // then // - in http assertEquals( response() .withStatusCode(HttpStatusCode.OK_200.code()) .withHeaders( header("x-test", "test_headers_and_body") ) .withBody("an_example_body_http"), makeRequest( request() .withPath(calculatePath("echo")) .withMethod("POST") .withHeaders( header("x-test", "test_headers_and_body") ) .withBody("an_example_body_http"), headersToIgnore) ); // - in https assertEquals( response() .withStatusCode(HttpStatusCode.OK_200.code()) .withHeaders( header("x-test", "test_headers_and_body") ) .withBody("an_example_body_https"), makeRequest( request() .withSecure(true) .withPath(calculatePath("echo")) .withMethod("POST") .withHeaders( header("x-test", "test_headers_and_body") ) .withBody("an_example_body_https"), headersToIgnore) ); } finally { secureEchoServer.stop(); } } @Test public void shouldAllowSimultaneousForwardAndResponseExpectations() { // when mockServerClient .when( request() .withPath(calculatePath("echo")), once() ) .forward( forward() .withHost("127.0.0.1") .withPort(getTestServerPort()) ); mockServerClient .when( request() .withPath(calculatePath("test_headers_and_body")), once() ) .respond( response() .withBody("some_body") ); // then // - forward assertEquals( response() .withStatusCode(HttpStatusCode.OK_200.code()) .withHeaders( header("x-test", "test_headers_and_body") ) .withBody("an_example_body"), makeRequest( request() .withPath(calculatePath("echo")) .withMethod("POST") .withHeaders( header("x-test", "test_headers_and_body") ) .withBody("an_example_body"), headersToIgnore) ); // - respond assertEquals( response() .withStatusCode(HttpStatusCode.OK_200.code()) .withBody("some_body"), makeRequest( request() .withPath(calculatePath("test_headers_and_body")), headersToIgnore) ); // - no response or forward assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()), makeRequest( request() .withPath(calculatePath("test_headers_and_body")), headersToIgnore) ); } @Test public void shouldCallbackToSpecifiedClassWithPrecannedResponse() { // when mockServerClient .when( request() .withPath(calculatePath("callback")) ) .callback( callback() .withCallbackClass("org.mockserver.integration.callback.PrecannedTestExpectationCallback") ); // then // - in http assertEquals( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withHeaders( header("x-callback", "test_callback_header") ) .withBody("a_callback_response"), makeRequest( request() .withPath(calculatePath("callback")) .withMethod("POST") .withHeaders( header("x-test", "test_headers_and_body") ) .withBody("an_example_body_http"), headersToIgnore ) ); // - in https assertEquals( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withHeaders( header("x-callback", "test_callback_header") ) .withBody("a_callback_response"), makeRequest( request() .withSecure(true) .withPath(calculatePath("callback")) .withMethod("POST") .withHeaders( header("x-test", "test_headers_and_body") ) .withBody("an_example_body_https"), headersToIgnore ) ); } @Test public void shouldReturnResponseWithOnlyBody() { // when mockServerClient.when(request()).respond(response().withBody("some_body")); // then // - in http assertEquals( response() .withStatusCode(HttpStatusCode.OK_200.code()) .withBody("some_body"), makeRequest( request() .withPath(calculatePath("")), headersToIgnore) ); // - in https assertEquals( response() .withStatusCode(HttpStatusCode.OK_200.code()) .withBody("some_body"), makeRequest( request() .withSecure(true) .withPath(calculatePath("")), headersToIgnore) ); } @Test public void shouldReturnResponseForRequestInSsl() { // when mockServerClient.when(request().withSecure(true)).respond(response().withBody("some_body")); // then // - in http assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()), makeRequest( request() .withPath(calculatePath("")), headersToIgnore) ); // - in https assertEquals( response() .withStatusCode(HttpStatusCode.OK_200.code()) .withBody("some_body"), makeRequest( request() .withSecure(true) .withPath(calculatePath("")), headersToIgnore) ); } @Test public void shouldReturnResponseForRequestNotInSsl() { // when mockServerClient.when(request().withSecure(false)).respond(response().withBody("some_body")); // then // - in http assertEquals( response() .withStatusCode(HttpStatusCode.OK_200.code()) .withBody("some_body"), makeRequest( request() .withPath(calculatePath("")), headersToIgnore) ); // - in https assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()), makeRequest( request() .withSecure(true) .withPath(calculatePath("")), headersToIgnore) ); } @Test public void shouldReturnMatchRequestWithBodyInUTF16() { // when String body = "我说中国话"; mockServerClient.when(request().withBody(body, Charsets.UTF_16)).respond(response().withBody(body, Charsets.UTF_8)); // then // - in http assertEquals( response() .withHeader(HttpHeaders.CONTENT_TYPE, MediaType.create("text", "plain").withCharset(Charsets.UTF_8).toString()) .withStatusCode(HttpStatusCode.OK_200.code()) .withBody(body), makeRequest( request() .withPath(calculatePath("")) .withBody(body, Charsets.UTF_16), headersToIgnore) ); // - in https assertEquals( response() .withHeader(HttpHeaders.CONTENT_TYPE, MediaType.create("text", "plain").withCharset(Charsets.UTF_8).toString()) .withStatusCode(HttpStatusCode.OK_200.code()) .withBody(body), makeRequest( request() .withSecure(true) .withPath(calculatePath("")) .withBody(body, Charsets.UTF_16), headersToIgnore) ); } @Test public void shouldReturnMatchRequestWithBodyInUTF16WithContentTypeHeader() { // when String body = "我说中国话"; mockServerClient .when( request() .withHeader(HttpHeaders.CONTENT_TYPE, MediaType.create("text", "plain").withCharset(Charsets.UTF_8).toString()) .withBody(body) ) .respond( response() .withBody(body, Charsets.UTF_8) ); // then // - in http assertEquals( response() .withHeader(HttpHeaders.CONTENT_TYPE, MediaType.create("text", "plain").withCharset(Charsets.UTF_8).toString()) .withStatusCode(HttpStatusCode.OK_200.code()) .withBody(body), makeRequest( request() .withHeader(HttpHeaders.CONTENT_TYPE, MediaType.create("text", "plain").withCharset(Charsets.UTF_8).toString()) .withPath(calculatePath("")) .withBody(body), headersToIgnore) ); // - in https assertEquals( response() .withHeader(HttpHeaders.CONTENT_TYPE, MediaType.create("text", "plain").withCharset(Charsets.UTF_8).toString()) .withStatusCode(HttpStatusCode.OK_200.code()) .withBody(body), makeRequest( request() .withHeader(HttpHeaders.CONTENT_TYPE, MediaType.create("text", "plain").withCharset(Charsets.UTF_8).toString()) .withSecure(true) .withPath(calculatePath("")) .withBody(body), headersToIgnore) ); } @Test public void shouldReturnResponseWithBodyInUTF8() { // when String body = "我说中国话"; mockServerClient.when(request()).respond(response().withBody(body, Charsets.UTF_16)); // then // - in http assertEquals( response() .withHeader(HttpHeaders.CONTENT_TYPE, MediaType.create("text", "plain").withCharset(Charsets.UTF_16).toString()) .withStatusCode(HttpStatusCode.OK_200.code()) .withBody(body), makeRequest( request() .withPath(calculatePath("")), headersToIgnore) ); // - in https assertEquals( response() .withHeader(HttpHeaders.CONTENT_TYPE, MediaType.create("text", "plain").withCharset(Charsets.UTF_16).toString()) .withStatusCode(HttpStatusCode.OK_200.code()) .withBody(body), makeRequest( request() .withSecure(true) .withPath(calculatePath("")), headersToIgnore) ); } @Test public void shouldReturnResponseWithBodyInUTF16WithContentTypeHeader() { // when String body = "我说中国话"; mockServerClient .when( request() ) .respond( response() .withHeader(HttpHeaders.CONTENT_TYPE, MediaType.create("text", "plain").withCharset(Charsets.UTF_8).toString()) .withBody(body) ); // then // - in http assertEquals( response() .withHeader(HttpHeaders.CONTENT_TYPE, MediaType.create("text", "plain").withCharset(Charsets.UTF_8).toString()) .withStatusCode(HttpStatusCode.OK_200.code()) .withBody(body), makeRequest( request() .withPath(calculatePath("")), headersToIgnore) ); // - in https assertEquals( response() .withHeader(HttpHeaders.CONTENT_TYPE, MediaType.create("text", "plain").withCharset(Charsets.UTF_8).toString()) .withStatusCode(HttpStatusCode.OK_200.code()) .withBody(body), makeRequest( request() .withSecure(true) .withPath(calculatePath("")), headersToIgnore) ); } @Test public void shouldReturnResponseWithOnlyStatusCode() { // when mockServerClient .when( request() .withMethod("POST") .withPath(calculatePath("some_path")) ) .respond( response() .withStatusCode(200) ); // then // - in http assertEquals( response() .withStatusCode(HttpStatusCode.OK_200.code()), makeRequest( request() .withPath(calculatePath("some_path")) .withMethod("POST"), headersToIgnore) ); // - in https assertEquals( response() .withStatusCode(HttpStatusCode.OK_200.code()), makeRequest( request() .withSecure(true) .withPath(calculatePath("some_path")) .withMethod("POST"), headersToIgnore) ); } @Test public void shouldReturnResponseByMatchingPath() { // when mockServerClient .when( request() .withPath(calculatePath("some_path1")) ) .respond( response() .withBody("some_body1") ); mockServerClient .when( request() .withPath(calculatePath("some_path2")) ) .respond( response() .withBody("some_body2") ); // then // - in http assertEquals( response() .withStatusCode(HttpStatusCode.OK_200.code()) .withBody("some_body2"), makeRequest( request() .withPath(calculatePath("some_path2")), headersToIgnore) ); assertEquals( response() .withStatusCode(HttpStatusCode.OK_200.code()) .withBody("some_body1"), makeRequest( request() .withPath(calculatePath("some_path1")), headersToIgnore) ); // - in https assertEquals( response() .withStatusCode(HttpStatusCode.OK_200.code()) .withBody("some_body2"), makeRequest( request() .withSecure(true) .withPath(calculatePath("some_path2")), headersToIgnore) ); assertEquals( response() .withStatusCode(HttpStatusCode.OK_200.code()) .withBody("some_body1"), makeRequest( request() .withSecure(true) .withPath(calculatePath("some_path1")), headersToIgnore) ); } @Test public void shouldReturnResponseByMatchingPathExactTimes() { // when mockServerClient .when( request() .withPath(calculatePath("some_path")), exactly(2) ) .respond( response() .withBody("some_body") ); // then // - in http assertEquals( response() .withStatusCode(HttpStatusCode.OK_200.code()) .withBody("some_body"), makeRequest( request() .withPath(calculatePath("some_path")), headersToIgnore) ); // - in https assertEquals( response() .withStatusCode(HttpStatusCode.OK_200.code()) .withBody("some_body"), makeRequest( request() .withSecure(true) .withPath(calculatePath("some_path")), headersToIgnore) ); // - in http assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()), makeRequest( request() .withPath(calculatePath("some_path")), headersToIgnore) ); // - in https assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()), makeRequest( request() .withSecure(true) .withPath(calculatePath("some_path")), headersToIgnore) ); } @Test public void shouldReturnResponseWhenTimeToLiveHasNotExpired() { // when mockServerClient .when( request().withPath(calculatePath("some_path")), exactly(2), TimeToLive.exactly(TimeUnit.HOURS, 1L) ) .respond( response().withBody("some_body") ); // then // - in http assertEquals( response() .withStatusCode(HttpStatusCode.OK_200.code()) .withBody("some_body"), makeRequest( request() .withPath(calculatePath("some_path")), headersToIgnore) ); // - in https assertEquals( response() .withStatusCode(HttpStatusCode.OK_200.code()) .withBody("some_body"), makeRequest( request() .withSecure(true) .withPath(calculatePath("some_path")), headersToIgnore) ); // - in http assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()), makeRequest( request() .withPath(calculatePath("some_path")), headersToIgnore) ); // - in https assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()), makeRequest( request() .withSecure(true) .withPath(calculatePath("some_path")), headersToIgnore) ); } @Test public void shouldReturnResponseByMatchingBodyWithXPath() { // when mockServerClient.when(request().withBody(xpath("/bookstore/book[price>30]/price")), exactly(2)).respond(response().withBody("some_body")); // then // - in http assertEquals( response() .withStatusCode(HttpStatusCode.OK_200.code()) .withBody("some_body"), makeRequest( request() .withPath(calculatePath("some_path")) .withMethod("POST") .withBody(new StringBody("" + "<?xml version=\"1.0\" encoding=\"ISO-8859-1\"?>" + System.getProperty("line.separator") + "<bookstore>" + System.getProperty("line.separator") + " <book category=\"COOKING\">" + System.getProperty("line.separator") + " <title lang=\"en\">Everyday Italian</title>" + System.getProperty("line.separator") + " <author>Giada De Laurentiis</author>" + System.getProperty("line.separator") + " <year>2005</year>" + System.getProperty("line.separator") + " <price>30.00</price>" + System.getProperty("line.separator") + " </book>" + System.getProperty("line.separator") + " <book category=\"CHILDREN\">" + System.getProperty("line.separator") + " <title lang=\"en\">Harry Potter</title>" + System.getProperty("line.separator") + " <author>J K. Rowling</author>" + System.getProperty("line.separator") + " <year>2005</year>" + System.getProperty("line.separator") + " <price>29.99</price>" + System.getProperty("line.separator") + " </book>" + System.getProperty("line.separator") + " <book category=\"WEB\">" + System.getProperty("line.separator") + " <title lang=\"en\">Learning XML</title>" + System.getProperty("line.separator") + " <author>Erik T. Ray</author>" + System.getProperty("line.separator") + " <year>2003</year>" + System.getProperty("line.separator") + " <price>31.95</price>" + System.getProperty("line.separator") + " </book>" + System.getProperty("line.separator") + "</bookstore>")), headersToIgnore) ); // - in https assertEquals( response() .withStatusCode(HttpStatusCode.OK_200.code()) .withBody("some_body"), makeRequest( request() .withSecure(true) .withPath(calculatePath("some_path")) .withMethod("POST") .withBody(new StringBody("" + "<?xml version=\"1.0\" encoding=\"ISO-8859-1\"?>" + System.getProperty("line.separator") + "<bookstore>" + System.getProperty("line.separator") + " <book category=\"COOKING\">" + System.getProperty("line.separator") + " <title lang=\"en\">Everyday Italian</title>" + System.getProperty("line.separator") + " <author>Giada De Laurentiis</author>" + System.getProperty("line.separator") + " <year>2005</year>" + System.getProperty("line.separator") + " <price>30.00</price>" + System.getProperty("line.separator") + " </book>" + System.getProperty("line.separator") + " <book category=\"CHILDREN\">" + System.getProperty("line.separator") + " <title lang=\"en\">Harry Potter</title>" + System.getProperty("line.separator") + " <author>J K. Rowling</author>" + System.getProperty("line.separator") + " <year>2005</year>" + System.getProperty("line.separator") + " <price>29.99</price>" + System.getProperty("line.separator") + " </book>" + System.getProperty("line.separator") + " <book category=\"WEB\">" + System.getProperty("line.separator") + " <title lang=\"en\">Learning XML</title>" + System.getProperty("line.separator") + " <author>Erik T. Ray</author>" + System.getProperty("line.separator") + " <year>2003</year>" + System.getProperty("line.separator") + " <price>31.95</price>" + System.getProperty("line.separator") + " </book>" + System.getProperty("line.separator") + "</bookstore>")), headersToIgnore) ); } @Test public void shouldReturnResponseByMatchingBodyWithXml() { // when mockServerClient.when(request().withBody(xml("" + "<bookstore>" + System.getProperty("line.separator") + " <book nationality=\"ITALIAN\" category=\"COOKING\"><title lang=\"en\">Everyday Italian</title><author>Giada De Laurentiis</author><year>2005</year><price>30.00</price></book>" + System.getProperty("line.separator") + "</bookstore>")), exactly(2)).respond(response().withBody("some_body")); // then // - in http assertEquals( response() .withStatusCode(HttpStatusCode.OK_200.code()) .withBody("some_body"), makeRequest( request() .withPath(calculatePath("some_path")) .withMethod("POST") .withBody(new StringBody("" + "<?xml version=\"1.0\" encoding=\"ISO-8859-1\"?>" + System.getProperty("line.separator") + "<bookstore>" + System.getProperty("line.separator") + " <book category=\"COOKING\" nationality=\"ITALIAN\">" + System.getProperty("line.separator") + " <title lang=\"en\">Everyday Italian</title>" + System.getProperty("line.separator") + " <author>Giada De Laurentiis</author>" + System.getProperty("line.separator") + " <year>2005</year>" + System.getProperty("line.separator") + " <price>30.00</price>" + System.getProperty("line.separator") + " </book>" + System.getProperty("line.separator") + "</bookstore>")), headersToIgnore) ); // - in https assertEquals( response() .withStatusCode(HttpStatusCode.OK_200.code()) .withBody("some_body"), makeRequest( request() .withSecure(true) .withPath(calculatePath("some_path")) .withMethod("POST") .withBody(new StringBody("" + "<?xml version=\"1.0\" encoding=\"ISO-8859-1\"?>" + System.getProperty("line.separator") + "<bookstore>" + System.getProperty("line.separator") + " <book category=\"COOKING\" nationality=\"ITALIAN\">" + System.getProperty("line.separator") + " <title lang=\"en\">Everyday Italian</title>" + System.getProperty("line.separator") + " <author>Giada De Laurentiis</author>" + System.getProperty("line.separator") + " <year>2005</year>" + System.getProperty("line.separator") + " <price>30.00</price>" + System.getProperty("line.separator") + " </book>" + System.getProperty("line.separator") + "</bookstore>")), headersToIgnore) ); } @Test public void shouldReturnResponseByMatchingBodyWithJson() { // when mockServerClient .when( request() .withBody(json("{" + System.getProperty("line.separator") + " \"id\": 1," + System.getProperty("line.separator") + " \"name\": \"A green door\"," + System.getProperty("line.separator") + " \"price\": 12.50," + System.getProperty("line.separator") + " \"tags\": [\"home\", \"green\"]" + System.getProperty("line.separator") + "}")), exactly(2) ) .respond( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body") ); // then // - in http assertEquals( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body"), makeRequest( request() .withPath(calculatePath("some_path")) .withMethod("POST") .withBody("{" + System.getProperty("line.separator") + " \"id\": 1," + System.getProperty("line.separator") + " \"extra ignored field\": \"some value\"," + System.getProperty("line.separator") + " \"name\": \"A green door\"," + System.getProperty("line.separator") + " \"price\": 12.50," + System.getProperty("line.separator") + " \"tags\": [\"home\", \"green\"]" + System.getProperty("line.separator") + "}"), headersToIgnore) ); // - in https assertEquals( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body"), makeRequest( request() .withSecure(true) .withPath(calculatePath("some_path")) .withMethod("POST") .withBody("{" + System.getProperty("line.separator") + " \"id\": 1," + System.getProperty("line.separator") + " \"extra ignored array\": [\"one\", \"two\"]," + System.getProperty("line.separator") + " \"name\": \"A green door\"," + System.getProperty("line.separator") + " \"price\": 12.50," + System.getProperty("line.separator") + " \"tags\": [\"home\", \"green\"]" + System.getProperty("line.separator") + "}"), headersToIgnore) ); } @Test public void shouldReturnResponseByMatchingBodyWithJsonWithCharsetUTF8() { // when mockServerClient .when( request() .withBody(json("{" + System.getProperty("line.separator") + " \"ταυτότητα\": 1," + System.getProperty("line.separator") + " \"όνομα\": \"μια πράσινη πόρτα\"," + System.getProperty("line.separator") + " \"τιμή\": 12.50," + System.getProperty("line.separator") + " \"ετικέτες\": [\"σπίτι\", \"πράσινος\"]" + System.getProperty("line.separator") + "}", Charsets.UTF_16, MatchType.ONLY_MATCHING_FIELDS)), exactly(2) ) .respond( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body") ); // then // - in http assertEquals( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body"), makeRequest( request() .withPath(calculatePath("some_path")) .withMethod("POST") .withBody(json("{" + System.getProperty("line.separator") + " \"ταυτότητα\": 1," + System.getProperty("line.separator") + " \"επιπλέον αγνοούνται τομέα\": \"κάποια αξία\"," + System.getProperty("line.separator") + " \"όνομα\": \"μια πράσινη πόρτα\"," + System.getProperty("line.separator") + " \"τιμή\": 12.50," + System.getProperty("line.separator") + " \"ετικέτες\": [\"σπίτι\", \"πράσινος\"]" + System.getProperty("line.separator") + "}", Charsets.UTF_16, MatchType.ONLY_MATCHING_FIELDS)), headersToIgnore) ); // - in https assertEquals( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body"), makeRequest( request() .withSecure(true) .withPath(calculatePath("some_path")) .withMethod("POST") .withBody(json("{" + System.getProperty("line.separator") + " \"ταυτότητα\": 1," + System.getProperty("line.separator") + " \"επιπλέον αγνοούνται σειρά\": [\"ένας\", \"δυο\"]," + System.getProperty("line.separator") + " \"όνομα\": \"μια πράσινη πόρτα\"," + System.getProperty("line.separator") + " \"τιμή\": 12.50," + System.getProperty("line.separator") + " \"ετικέτες\": [\"σπίτι\", \"πράσινος\"]" + System.getProperty("line.separator") + "}", Charsets.UTF_16, MatchType.ONLY_MATCHING_FIELDS)), headersToIgnore) ); } @Test public void shouldReturnResponseByMatchingBodyWithJsonWithContentTypeHeader() { // when mockServerClient .when( request() .withBody(json("{" + System.getProperty("line.separator") + " \"ταυτότητα\": 1," + System.getProperty("line.separator") + " \"όνομα\": \"μια πράσινη πόρτα\"," + System.getProperty("line.separator") + " \"τιμή\": 12.50," + System.getProperty("line.separator") + " \"ετικέτες\": [\"σπίτι\", \"πράσινος\"]" + System.getProperty("line.separator") + "}", Charsets.UTF_16, MatchType.ONLY_MATCHING_FIELDS)), exactly(2) ) .respond( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body") ); // then // - in http assertEquals( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body"), makeRequest( request() .withHeader(HttpHeaders.CONTENT_TYPE, MediaType.create("text", "plain").withCharset(Charsets.UTF_16).toString()) .withPath(calculatePath("some_path")) .withMethod("POST") .withBody(json("{" + System.getProperty("line.separator") + " \"ταυτότητα\": 1," + System.getProperty("line.separator") + " \"επιπλέον αγνοούνται τομέα\": \"κάποια αξία\"," + System.getProperty("line.separator") + " \"όνομα\": \"μια πράσινη πόρτα\"," + System.getProperty("line.separator") + " \"τιμή\": 12.50," + System.getProperty("line.separator") + " \"ετικέτες\": [\"σπίτι\", \"πράσινος\"]" + System.getProperty("line.separator") + "}")), headersToIgnore) ); // - in https assertEquals( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body"), makeRequest( request() .withSecure(true) .withHeader(HttpHeaders.CONTENT_TYPE, MediaType.create("text", "plain").withCharset(Charsets.UTF_16).toString()) .withPath(calculatePath("some_path")) .withMethod("POST") .withBody(json("{" + System.getProperty("line.separator") + " \"ταυτότητα\": 1," + System.getProperty("line.separator") + " \"επιπλέον αγνοούνται σειρά\": [\"ένας\", \"δυο\"]," + System.getProperty("line.separator") + " \"όνομα\": \"μια πράσινη πόρτα\"," + System.getProperty("line.separator") + " \"τιμή\": 12.50," + System.getProperty("line.separator") + " \"ετικέτες\": [\"σπίτι\", \"πράσινος\"]" + System.getProperty("line.separator") + "}")), headersToIgnore) ); } @Test public void shouldReturnResponseByMatchingBodyWithJsonWithMatchType() { // when mockServerClient .when( request() .withBody(json("{" + System.getProperty("line.separator") + " \"id\": 1," + System.getProperty("line.separator") + " \"name\": \"A green door\"," + System.getProperty("line.separator") + " \"price\": 12.50," + System.getProperty("line.separator") + " \"tags\": [\"home\", \"green\"]" + System.getProperty("line.separator") + "}", MatchType.ONLY_MATCHING_FIELDS)), exactly(2) ) .respond( response() .withBody("some_body") ); // then // - in http assertEquals( response("some_body"), makeRequest( request() .withPath(calculatePath("some_path")) .withMethod("POST") .withBody("{" + System.getProperty("line.separator") + " \"id\": 1," + System.getProperty("line.separator") + " \"extra field\": \"some value\"," + System.getProperty("line.separator") + " \"name\": \"A green door\"," + System.getProperty("line.separator") + " \"price\": 12.50," + System.getProperty("line.separator") + " \"tags\": [\"home\", \"green\"]" + System.getProperty("line.separator") + "}"), headersToIgnore) ); // - in https assertEquals( response("some_body"), makeRequest( request() .withSecure(true) .withPath(calculatePath("some_path")) .withMethod("POST") .withBody("{" + System.getProperty("line.separator") + " \"id\": 1," + System.getProperty("line.separator") + " \"extra field\": \"some value\"," + System.getProperty("line.separator") + " \"name\": \"A green door\"," + System.getProperty("line.separator") + " \"price\": 12.50," + System.getProperty("line.separator") + " \"tags\": [\"home\", \"green\"]" + System.getProperty("line.separator") + "}"), headersToIgnore) ); } @Test public void shouldReturnResponseByMatchingBodyWithJsonSchema() { // when mockServerClient.when(request().withBody(jsonSchema("{" + System.getProperty("line.separator") + " \"$schema\": \"http://json-schema.org/draft-04/schema#\"," + System.getProperty("line.separator") + " \"title\": \"Product\"," + System.getProperty("line.separator") + " \"description\": \"A product from Acme's catalog\"," + System.getProperty("line.separator") + " \"type\": \"object\"," + System.getProperty("line.separator") + " \"properties\": {" + System.getProperty("line.separator") + " \"id\": {" + System.getProperty("line.separator") + " \"description\": \"The unique identifier for a product\"," + System.getProperty("line.separator") + " \"type\": \"integer\"" + System.getProperty("line.separator") + " }," + System.getProperty("line.separator") + " \"name\": {" + System.getProperty("line.separator") + " \"description\": \"Name of the product\"," + System.getProperty("line.separator") + " \"type\": \"string\"" + System.getProperty("line.separator") + " }," + System.getProperty("line.separator") + " \"price\": {" + System.getProperty("line.separator") + " \"type\": \"number\"," + System.getProperty("line.separator") + " \"minimum\": 0," + System.getProperty("line.separator") + " \"exclusiveMinimum\": true" + System.getProperty("line.separator") + " }," + System.getProperty("line.separator") + " \"tags\": {" + System.getProperty("line.separator") + " \"type\": \"array\"," + System.getProperty("line.separator") + " \"items\": {" + System.getProperty("line.separator") + " \"type\": \"string\"" + System.getProperty("line.separator") + " }," + System.getProperty("line.separator") + " \"minItems\": 1," + System.getProperty("line.separator") + " \"uniqueItems\": true" + System.getProperty("line.separator") + " }" + System.getProperty("line.separator") + " }," + System.getProperty("line.separator") + " \"required\": [\"id\", \"name\", \"price\"]" + System.getProperty("line.separator") + "}")), exactly(2)).respond(response().withBody("some_body")); // then // - in http assertEquals( response() .withStatusCode(HttpStatusCode.OK_200.code()) .withBody("some_body"), makeRequest( request() .withPath(calculatePath("some_path")) .withMethod("POST") .withBody("{" + System.getProperty("line.separator") + " \"id\": 1," + System.getProperty("line.separator") + " \"name\": \"A green door\"," + System.getProperty("line.separator") + " \"price\": 12.50," + System.getProperty("line.separator") + " \"tags\": [\"home\", \"green\"]" + System.getProperty("line.separator") + "}"), headersToIgnore) ); // - in https assertEquals( response() .withStatusCode(HttpStatusCode.OK_200.code()) .withBody("some_body"), makeRequest( request() .withSecure(true) .withPath(calculatePath("some_path")) .withMethod("POST") .withBody("{" + System.getProperty("line.separator") + " \"id\": 1," + System.getProperty("line.separator") + " \"name\": \"A green door\"," + System.getProperty("line.separator") + " \"price\": 12.50," + System.getProperty("line.separator") + " \"tags\": [\"home\", \"green\"]" + System.getProperty("line.separator") + "}"), headersToIgnore) ); } @Test public void shouldReturnPDFResponseByMatchingPath() throws IOException { // when byte[] pdfBytes = IOUtils.toByteArray(getClass().getClassLoader().getResourceAsStream("test.pdf")); mockServerClient .when( request() .withPath(calculatePath("ws/rest/user/[0-9]+/document/[0-9]+\\.pdf")) ) .respond( response() .withStatusCode(HttpStatusCode.OK_200.code()) .withHeaders( header(HttpHeaders.CONTENT_TYPE, MediaType.PDF.toString()), header(HttpHeaders.CONTENT_DISPOSITION, "form-data; name=\"test.pdf\"; filename=\"test.pdf\""), header(HttpHeaders.CACHE_CONTROL, "must-revalidate, post-check=0, pre-check=0") ) .withBody(binary(pdfBytes)) ); // then // - in http assertEquals( response() .withStatusCode(HttpStatusCode.OK_200.code()) .withHeaders( header(HttpHeaders.CONTENT_DISPOSITION, "form-data; name=\"test.pdf\"; filename=\"test.pdf\""), header(HttpHeaders.CACHE_CONTROL, "must-revalidate, post-check=0, pre-check=0"), header(HttpHeaders.CONTENT_TYPE, MediaType.PDF.toString()) ) .withBody(binary(pdfBytes)), makeRequest( request() .withPath(calculatePath("ws/rest/user/1/document/2.pdf")) .withMethod("GET"), headersToIgnore) ); // - in https assertEquals( response() .withStatusCode(HttpStatusCode.OK_200.code()) .withHeaders( header(HttpHeaders.CONTENT_DISPOSITION, "form-data; name=\"test.pdf\"; filename=\"test.pdf\""), header(HttpHeaders.CACHE_CONTROL, "must-revalidate, post-check=0, pre-check=0"), header(HttpHeaders.CONTENT_TYPE, MediaType.PDF.toString()) ) .withBody(binary(pdfBytes)), makeRequest( request() .withSecure(true) .withPath(calculatePath("ws/rest/user/1/document/2.pdf")) .withMethod("GET"), headersToIgnore) ); } @Test public void shouldReturnPNGResponseByMatchingPath() throws IOException { // when byte[] pngBytes = IOUtils.toByteArray(getClass().getClassLoader().getResourceAsStream("test.png")); mockServerClient .when( request() .withPath(calculatePath("ws/rest/user/[0-9]+/icon/[0-9]+\\.png")) ) .respond( response() .withStatusCode(HttpStatusCode.OK_200.code()) .withHeaders( header(HttpHeaders.CONTENT_TYPE, MediaType.PNG.toString()), header(HttpHeaders.CONTENT_DISPOSITION, "form-data; name=\"test.png\"; filename=\"test.png\"") ) .withBody(binary(pngBytes)) ); // then // - in http assertEquals( response() .withStatusCode(HttpStatusCode.OK_200.code()) .withHeaders( header(HttpHeaders.CONTENT_DISPOSITION, "form-data; name=\"test.png\"; filename=\"test.png\""), header(HttpHeaders.CONTENT_TYPE, MediaType.PNG.toString()) ) .withBody(binary(pngBytes)), makeRequest( request() .withPath(calculatePath("ws/rest/user/1/icon/1.png")) .withMethod("GET"), headersToIgnore) ); // - in https assertEquals( response() .withStatusCode(HttpStatusCode.OK_200.code()) .withHeaders( header(HttpHeaders.CONTENT_DISPOSITION, "form-data; name=\"test.png\"; filename=\"test.png\""), header(HttpHeaders.CONTENT_TYPE, MediaType.PNG.toString()) ) .withBody(binary(pngBytes)), makeRequest( request() .withSecure(true) .withPath(calculatePath("ws/rest/user/1/icon/1.png")) .withMethod("GET"), headersToIgnore) ); } @Test public void shouldReturnPDFResponseByMatchingBinaryPDFBody() throws IOException { // when byte[] pdfBytes = IOUtils.toByteArray(getClass().getClassLoader().getResourceAsStream("test.pdf")); mockServerClient .when( request().withBody(binary(pdfBytes)) ) .respond( response() .withStatusCode(HttpStatusCode.OK_200.code()) .withHeaders( header(HttpHeaders.CONTENT_TYPE, MediaType.PDF.toString()), header(HttpHeaders.CONTENT_DISPOSITION, "form-data; name=\"test.pdf\"; filename=\"test.pdf\""), header(HttpHeaders.CACHE_CONTROL, "must-revalidate, post-check=0, pre-check=0") ) .withBody(binary(pdfBytes)) ); // then // - in http assertEquals( response() .withStatusCode(HttpStatusCode.OK_200.code()) .withHeaders( header(HttpHeaders.CONTENT_DISPOSITION, "form-data; name=\"test.pdf\"; filename=\"test.pdf\""), header(HttpHeaders.CACHE_CONTROL, "must-revalidate, post-check=0, pre-check=0"), header(HttpHeaders.CONTENT_TYPE, MediaType.PDF.toString()) ) .withBody(binary(pdfBytes)), makeRequest( request() .withPath(calculatePath("ws/rest/user/1/document/2.pdf")) .withBody(binary(pdfBytes)) .withMethod("POST"), headersToIgnore) ); // - in https assertEquals( response() .withStatusCode(HttpStatusCode.OK_200.code()) .withHeaders( header(HttpHeaders.CONTENT_DISPOSITION, "form-data; name=\"test.pdf\"; filename=\"test.pdf\""), header(HttpHeaders.CACHE_CONTROL, "must-revalidate, post-check=0, pre-check=0"), header(HttpHeaders.CONTENT_TYPE, MediaType.PDF.toString()) ) .withBody(binary(pdfBytes)), makeRequest( request() .withSecure(true) .withPath(calculatePath("ws/rest/user/1/document/2.pdf")) .withBody(binary(pdfBytes)) .withMethod("POST"), headersToIgnore) ); } @Test public void shouldReturnPNGResponseByMatchingBinaryPNGBody() throws IOException { // when byte[] pngBytes = IOUtils.toByteArray(getClass().getClassLoader().getResourceAsStream("test.png")); mockServerClient .when( request().withBody(binary(pngBytes)) ) .respond( response() .withStatusCode(HttpStatusCode.OK_200.code()) .withHeaders( header(HttpHeaders.CONTENT_TYPE, MediaType.PNG.toString()), header(HttpHeaders.CONTENT_DISPOSITION, "form-data; name=\"test.png\"; filename=\"test.png\"") ) .withBody(binary(pngBytes)) ); // then // - in http assertEquals( response() .withStatusCode(HttpStatusCode.OK_200.code()) .withHeaders( header(HttpHeaders.CONTENT_DISPOSITION, "form-data; name=\"test.png\"; filename=\"test.png\""), header(HttpHeaders.CONTENT_TYPE, MediaType.PNG.toString()) ) .withBody(binary(pngBytes)), makeRequest( request() .withPath(calculatePath("ws/rest/user/1/icon/1.png")) .withBody(binary(pngBytes)) .withMethod("POST"), headersToIgnore) ); // - in https assertEquals( response() .withStatusCode(HttpStatusCode.OK_200.code()) .withHeaders( header(HttpHeaders.CONTENT_DISPOSITION, "form-data; name=\"test.png\"; filename=\"test.png\""), header(HttpHeaders.CONTENT_TYPE, MediaType.PNG.toString()) ) .withBody(binary(pngBytes)), makeRequest( request() .withSecure(true) .withPath(calculatePath("ws/rest/user/1/icon/1.png")) .withBody(binary(pngBytes)) .withMethod("POST"), headersToIgnore) ); } @Test public void shouldReturnResponseForExpectationWithDelay() { // when mockServerClient .when( request() .withPath(calculatePath("some_path1")) ) .respond( response() .withBody("some_body1") .withDelay(new Delay(TimeUnit.MILLISECONDS, 10)) ); mockServerClient .when( request() .withPath(calculatePath("some_path2")) ) .respond( response() .withBody("some_body2") .withDelay(new Delay(TimeUnit.MILLISECONDS, 20)) ); // then // - in http assertEquals( response() .withStatusCode(HttpStatusCode.OK_200.code()) .withBody("some_body2"), makeRequest( request() .withPath(calculatePath("some_path2")), headersToIgnore) ); assertEquals( response() .withStatusCode(HttpStatusCode.OK_200.code()) .withBody("some_body1"), makeRequest( request() .withPath(calculatePath("some_path1")), headersToIgnore) ); // - in https assertEquals( response() .withStatusCode(HttpStatusCode.OK_200.code()) .withBody("some_body2"), makeRequest( request() .withSecure(true) .withPath(calculatePath("some_path2")), headersToIgnore) ); assertEquals( response() .withStatusCode(HttpStatusCode.OK_200.code()) .withBody("some_body1"), makeRequest( request() .withSecure(true) .withPath(calculatePath("some_path1")), headersToIgnore) ); } @Test public void shouldReturnResponseByMatchingPathAndMethod() { // when mockServerClient .when( request() .withMethod("GET") .withPath(calculatePath("some_pathRequest")) ) .respond( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body_response") ); // then // - in http assertEquals( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body_response"), makeRequest( request() .withMethod("GET") .withPath(calculatePath("some_pathRequest")) .withQueryStringParameters( param("queryStringParameterOneName", "queryStringParameterOneValue"), param("queryStringParameterTwoName", "queryStringParameterTwoValue") ) .withHeaders(header("headerNameRequest", "headerValueRequest")) .withCookies(cookie("cookieNameRequest", "cookieValueRequest")), headersToIgnore) ); // - in https assertEquals( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body_response"), makeRequest( request() .withMethod("GET") .withSecure(true) .withPath(calculatePath("some_pathRequest")) .withQueryStringParameters( param("queryStringParameterOneName", "queryStringParameterOneValue"), param("queryStringParameterTwoName", "queryStringParameterTwoValue") ) .withHeaders(header("headerNameRequest", "headerValueRequest")) .withCookies(cookie("cookieNameRequest", "cookieValueRequest")), headersToIgnore) ); } @Test public void shouldReturnResponseByNotMatchingPathWithNotOperator() { // when mockServerClient .when( request() .withPath(not(calculatePath("some_path"))) ) .respond( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body_response") ); // then // - in http assertEquals( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body_response"), makeRequest( request() .withPath(calculatePath("some_other_path")), headersToIgnore) ); // - in https assertEquals( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body_response"), makeRequest( request() .withPath(calculatePath("some_other_path")), headersToIgnore) ); } @Test public void shouldReturnResponseByNotMatchingMethodWithNotOperator() { // when mockServerClient .when( request() .withMethod(not("GET")) ) .respond( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body_response") ); // then // - in http assertEquals( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body_response"), makeRequest( request() .withMethod("POST"), headersToIgnore) ); // - in https assertEquals( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body_response"), makeRequest( request() .withMethod("POST"), headersToIgnore) ); } @Test public void shouldReturnResponseByMatchingPathAndMethodAndBody() { // when mockServerClient .when( request() .withMethod("POST") .withPath(calculatePath("some_pathRequest")) .withBody("some_bodyRequest") ) .respond( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body_response") .withHeaders(header("headerNameResponse", "headerValueResponse")) ); // then // - in http assertEquals( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body_response") .withHeaders( header("headerNameResponse", "headerValueResponse") ), makeRequest( request() .withMethod("POST") .withPath(calculatePath("some_pathRequest")) .withQueryStringParameters( param("queryStringParameterOneName", "queryStringParameterOneValue"), param("queryStringParameterTwoName", "queryStringParameterTwoValue") ) .withBody("some_bodyRequest") .withHeaders(header("headerNameRequest", "headerValueRequest")) .withCookies(cookie("cookieNameRequest", "cookieValueRequest")), headersToIgnore) ); // - in https assertEquals( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body_response") .withHeaders( header("headerNameResponse", "headerValueResponse") ), makeRequest( request() .withMethod("POST") .withSecure(true) .withPath(calculatePath("some_pathRequest")) .withQueryStringParameters( param("queryStringParameterOneName", "queryStringParameterOneValue"), param("queryStringParameterTwoName", "queryStringParameterTwoValue") ) .withBody("some_bodyRequest") .withHeaders(header("headerNameRequest", "headerValueRequest")) .withCookies(cookie("cookieNameRequest", "cookieValueRequest")), headersToIgnore) ); } @Test public void shouldReturnResponseByMatchingPathAndMethodAndQueryStringParameters() { // when mockServerClient .when( request() .withMethod("GET") .withPath(calculatePath("some_pathRequest")) .withQueryStringParameters( param("queryStringParameterOneName", "queryStringParameterOneValue"), param("queryStringParameterTwoName", "queryStringParameterTwoValue") ) ) .respond( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body_response") .withCookies(cookie("cookieNameResponse", "cookieValueResponse")) ); // then // - in http assertEquals( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body_response") .withCookies(cookie("cookieNameResponse", "cookieValueResponse")) .withHeaders( header("Set-Cookie", "cookieNameResponse=cookieValueResponse") ), makeRequest( request() .withMethod("GET") .withPath(calculatePath("some_pathRequest")) .withQueryStringParameters( param("queryStringParameterOneName", "queryStringParameterOneValue"), param("queryStringParameterTwoName", "queryStringParameterTwoValue") ) .withHeaders(header("headerNameRequest", "headerValueRequest")) .withCookies(cookie("cookieNameRequest", "cookieValueRequest")), headersToIgnore) ); // - in https assertEquals( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body_response") .withCookies(cookie("cookieNameResponse", "cookieValueResponse")) .withHeaders( header("Set-Cookie", "cookieNameResponse=cookieValueResponse") ), makeRequest( request() .withMethod("GET") .withSecure(true) .withPath(calculatePath("some_pathRequest")) .withQueryStringParameters( param("queryStringParameterOneName", "queryStringParameterOneValue"), param("queryStringParameterTwoName", "queryStringParameterTwoValue") ) .withHeaders(header("headerNameRequest", "headerValueRequest")) .withCookies(cookie("cookieNameRequest", "cookieValueRequest")), headersToIgnore) ); } @Test public void shouldReturnResponseByMatchingPathAndMethodAndHeaders() { // when mockServerClient .when( request() .withMethod("GET") .withPath(calculatePath("some_pathRequest")) .withHeaders( header("requestHeaderNameOne", "requestHeaderValueOne_One", "requestHeaderValueOne_Two"), header("requestHeaderNameTwo", "requestHeaderValueTwo") ) ) .respond( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body_response") .withCookies(cookie("cookieNameResponse", "cookieValueResponse")) ); // then // - in http assertEquals( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body_response") .withCookies(cookie("cookieNameResponse", "cookieValueResponse")) .withHeaders( header("Set-Cookie", "cookieNameResponse=cookieValueResponse") ), makeRequest( request() .withMethod("GET") .withPath(calculatePath("some_pathRequest")) .withHeaders( header("requestHeaderNameOne", "requestHeaderValueOne_One", "requestHeaderValueOne_Two"), header("requestHeaderNameTwo", "requestHeaderValueTwo") ) .withCookies(cookie("cookieNameRequest", "cookieValueRequest")), headersToIgnore) ); // - in https assertEquals( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body_response") .withCookies(cookie("cookieNameResponse", "cookieValueResponse")) .withHeaders( header("Set-Cookie", "cookieNameResponse=cookieValueResponse") ), makeRequest( request() .withMethod("GET") .withSecure(true) .withPath(calculatePath("some_pathRequest")) .withHeaders( header("requestHeaderNameOne", "requestHeaderValueOne_One", "requestHeaderValueOne_Two"), header("requestHeaderNameTwo", "requestHeaderValueTwo") ) .withCookies(cookie("cookieNameRequest", "cookieValueRequest")), headersToIgnore) ); } @Test public void shouldReturnResponseByMatchingPathAndMethodAndCookies() { // when mockServerClient .when( request() .withMethod("GET") .withPath(calculatePath("some_pathRequest")) .withCookies( cookie("requestCookieNameOne", "requestCookieValueOne"), cookie("requestCookieNameTwo", "requestCookieValueTwo") ) ) .respond( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body_response") .withCookies( cookie("responseCookieNameOne", "responseCookieValueOne"), cookie("responseCookieNameTwo", "responseCookieValueTwo") ) ); // then // - in http - cookie objects assertEquals( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body_response") .withCookies( cookie("responseCookieNameOne", "responseCookieValueOne"), cookie("responseCookieNameTwo", "responseCookieValueTwo") ) .withHeaders( header("Set-Cookie", "responseCookieNameOne=responseCookieValueOne", "responseCookieNameTwo=responseCookieValueTwo") ), makeRequest( request() .withMethod("GET") .withPath(calculatePath("some_pathRequest")) .withHeaders( header("headerNameRequest", "headerValueRequest"), header(HttpHeaders.CONTENT_TYPE, TEXT_PLAIN) ) .withCookies( cookie("requestCookieNameOne", "requestCookieValueOne"), cookie("requestCookieNameTwo", "requestCookieValueTwo") ), headersToIgnore) ); // - in http - cookie header assertEquals( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body_response") .withCookies( cookie("responseCookieNameOne", "responseCookieValueOne"), cookie("responseCookieNameTwo", "responseCookieValueTwo") ) .withHeaders( header("Set-Cookie", "responseCookieNameOne=responseCookieValueOne", "responseCookieNameTwo=responseCookieValueTwo") ), makeRequest( request() .withMethod("GET") .withPath(calculatePath("some_pathRequest")) .withHeaders( header("headerNameRequest", "headerValueRequest"), header("Cookie", "requestCookieNameOne=requestCookieValueOne; requestCookieNameTwo=requestCookieValueTwo") ), headersToIgnore) ); // - in https - cookie objects assertEquals( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body_response") .withCookies( cookie("responseCookieNameOne", "responseCookieValueOne"), cookie("responseCookieNameTwo", "responseCookieValueTwo") ) .withHeaders( header("Set-Cookie", "responseCookieNameOne=responseCookieValueOne", "responseCookieNameTwo=responseCookieValueTwo") ), makeRequest( request() .withMethod("GET") .withSecure(true) .withPath(calculatePath("some_pathRequest")) .withHeaders( header("headerNameRequest", "headerValueRequest") ) .withCookies( cookie("requestCookieNameOne", "requestCookieValueOne"), cookie("requestCookieNameTwo", "requestCookieValueTwo") ), headersToIgnore) ); // - in https - cookie header assertEquals( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body_response") .withCookies( cookie("responseCookieNameOne", "responseCookieValueOne"), cookie("responseCookieNameTwo", "responseCookieValueTwo") ) .withHeaders( header("Set-Cookie", "responseCookieNameOne=responseCookieValueOne", "responseCookieNameTwo=responseCookieValueTwo") ), makeRequest( request() .withMethod("GET") .withSecure(true) .withPath(calculatePath("some_pathRequest")) .withHeaders( header("headerNameRequest", "headerValueRequest"), header("Cookie", "requestCookieNameOne=requestCookieValueOne; requestCookieNameTwo=requestCookieValueTwo") ), headersToIgnore) ); } @Test public void shouldReturnResponseByMatchingPathAndMethodAndQueryStringParametersAndBodyParameters() { // when mockServerClient .when( request() .withMethod("POST") .withPath(calculatePath("some_pathRequest")) .withQueryStringParameters( param("queryStringParameterOneName", "queryStringParameterOneValueOne", "queryStringParameterOneValueTwo"), param("queryStringParameterTwoName", "queryStringParameterTwoValue") ) .withBody(params(param("bodyParameterName", "bodyParameterValue"))) ) .respond( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body") ); // then // - in http - url query string assertEquals( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body"), makeRequest( request() .withMethod("POST") .withPath(calculatePath("some_pathRequest")) .withQueryStringParameters( param("queryStringParameterOneName", "queryStringParameterOneValueOne", "queryStringParameterOneValueTwo"), param("queryStringParameterTwoName", "queryStringParameterTwoValue") ) .withBody(params(param("bodyParameterName", "bodyParameterValue"))), headersToIgnore) ); // - in https - query string parameter objects assertEquals( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body"), makeRequest( request() .withSecure(true) .withMethod("POST") .withPath(calculatePath("some_pathRequest")) .withQueryStringParameters( param("queryStringParameterOneName", "queryStringParameterOneValueOne", "queryStringParameterOneValueTwo"), param("queryStringParameterTwoName", "queryStringParameterTwoValue") ) .withBody(params(param("bodyParameterName", "bodyParameterValue"))), headersToIgnore) ); } @Test public void shouldReturnResponseByMatchingPathAndMethodAndQueryStringParametersAndBody() { // when mockServerClient .when( request() .withMethod("POST") .withPath(calculatePath("some_pathRequest")) .withQueryStringParameters( param("queryStringParameterOneName", "queryStringParameterOneValueOne", "queryStringParameterOneValueTwo"), param("queryStringParameterTwoName", "queryStringParameterTwoValue") ) .withBody("some_bodyRequest") ) .respond( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body_response") .withHeaders(header("headerNameResponse", "headerValueResponse")) .withCookies(cookie("cookieNameResponse", "cookieValueResponse")) ); // then // - in http - url query string assertEquals( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body_response") .withCookies(cookie("cookieNameResponse", "cookieValueResponse")) .withHeaders( header("headerNameResponse", "headerValueResponse"), header("Set-Cookie", "cookieNameResponse=cookieValueResponse") ), makeRequest( request() .withMethod("POST") .withPath(calculatePath("some_pathRequest")) .withQueryStringParameters( param("queryStringParameterOneName", "queryStringParameterOneValueOne", "queryStringParameterOneValueTwo"), param("queryStringParameterTwoName", "queryStringParameterTwoValue") ) .withBody("some_bodyRequest") .withHeaders(header("headerNameRequest", "headerValueRequest")) .withCookies(cookie("cookieNameRequest", "cookieValueRequest")), headersToIgnore) ); // - in http - query string parameter objects assertEquals( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body_response") .withCookies(cookie("cookieNameResponse", "cookieValueResponse")) .withHeaders( header("headerNameResponse", "headerValueResponse"), header("Set-Cookie", "cookieNameResponse=cookieValueResponse") ), makeRequest( request() .withMethod("POST") .withPath(calculatePath("some_pathRequest")) .withQueryStringParameters( param("queryStringParameterOneName", "queryStringParameterOneValueOne", "queryStringParameterOneValueTwo"), param("queryStringParameterTwoName", "queryStringParameterTwoValue") ) .withBody("some_bodyRequest") .withHeaders(header("headerNameRequest", "headerValueRequest")) .withCookies(cookie("cookieNameRequest", "cookieValueRequest")), headersToIgnore) ); // - in https - url string and query string parameter objects assertEquals( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body_response") .withCookies(cookie("cookieNameResponse", "cookieValueResponse")) .withHeaders( header("headerNameResponse", "headerValueResponse"), header("Set-Cookie", "cookieNameResponse=cookieValueResponse") ), makeRequest( request() .withMethod("POST") .withPath(calculatePath("some_pathRequest")) .withQueryStringParameters( param("queryStringParameterOneName", "queryStringParameterOneValueOne", "queryStringParameterOneValueTwo"), param("queryStringParameterTwoName", "queryStringParameterTwoValue") ) .withBody("some_bodyRequest") .withHeaders(header("headerNameRequest", "headerValueRequest")) .withCookies(cookie("cookieNameRequest", "cookieValueRequest")), headersToIgnore) ); } @Test public void shouldReturnResponseByMatchingPathAndMethodAndBodyParameters() { // when mockServerClient .when( request() .withMethod("POST") .withPath(calculatePath("some_pathRequest")) .withBody(params( param("bodyParameterOneName", "Parameter One Value One", "Parameter One Value Two"), param("bodyParameterTwoName", "Parameter Two") )) ) .respond( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body_response") .withHeaders(header("headerNameResponse", "headerValueResponse")) .withCookies(cookie("cookieNameResponse", "cookieValueResponse")) ); // then // - in http - body string assertEquals( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body_response") .withCookies(cookie("cookieNameResponse", "cookieValueResponse")) .withHeaders( header("headerNameResponse", "headerValueResponse"), header("Set-Cookie", "cookieNameResponse=cookieValueResponse") ), makeRequest( request() .withMethod("POST") .withPath(calculatePath("some_pathRequest")) .withBody(new StringBody("bodyParameterOneName=Parameter+One+Value+One" + "&bodyParameterOneName=Parameter+One+Value+Two" + "&bodyParameterTwoName=Parameter+Two")) .withHeaders(header("headerNameRequest", "headerValueRequest")) .withCookies(cookie("cookieNameRequest", "cookieValueRequest")), headersToIgnore) ); // - in http - body parameter objects assertEquals( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body_response") .withCookies(cookie("cookieNameResponse", "cookieValueResponse")) .withHeaders( header("headerNameResponse", "headerValueResponse"), header("Set-Cookie", "cookieNameResponse=cookieValueResponse") ), makeRequest( request() .withMethod("POST") .withPath(calculatePath("some_pathRequest")) .withBody(params( param("bodyParameterOneName", "Parameter One Value One", "Parameter One Value Two"), param("bodyParameterTwoName", "Parameter Two") )) .withHeaders(header("headerNameRequest", "headerValueRequest")) .withCookies(cookie("cookieNameRequest", "cookieValueRequest")), headersToIgnore) ); // - in https - url string and query string parameter objects assertEquals( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body_response") .withCookies(cookie("cookieNameResponse", "cookieValueResponse")) .withHeaders( header("headerNameResponse", "headerValueResponse"), header("Set-Cookie", "cookieNameResponse=cookieValueResponse") ), makeRequest( request() .withMethod("POST") .withPath(calculatePath("some_pathRequest")) .withBody(params( param("bodyParameterOneName", "Parameter One Value One", "Parameter One Value Two"), param("bodyParameterTwoName", "Parameter Two") )) .withHeaders(header("headerNameRequest", "headerValueRequest")) .withCookies(cookie("cookieNameRequest", "cookieValueRequest")), headersToIgnore) ); } @Test public void shouldReturnResponseByMatchingPathAndMethodAndParametersAndHeadersAndCookies() { // when mockServerClient .when( request() .withMethod("PUT") .withPath(calculatePath("some_pathRequest")) .withBody(new StringBody("bodyParameterOneName=Parameter+One+Value+One" + "&bodyParameterOneName=Parameter+One+Value+Two" + "&bodyParameterTwoName=Parameter+Two")) .withHeaders(header("headerNameRequest", "headerValueRequest")) .withCookies(cookie("cookieNameRequest", "cookieValueRequest")) ) .respond( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body_response") .withHeaders(header("headerNameResponse", "headerValueResponse")) .withCookies(cookie("cookieNameResponse", "cookieValueResponse")) ); // then // - in http - body string assertEquals( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body_response") .withCookies(cookie("cookieNameResponse", "cookieValueResponse")) .withHeaders( header("headerNameResponse", "headerValueResponse"), header("Set-Cookie", "cookieNameResponse=cookieValueResponse") ), makeRequest( request() .withMethod("PUT") .withPath(calculatePath("some_pathRequest")) .withBody(new StringBody("bodyParameterOneName=Parameter+One+Value+One" + "&bodyParameterOneName=Parameter+One+Value+Two" + "&bodyParameterTwoName=Parameter+Two")) .withHeaders( header("headerNameRequest", "headerValueRequest"), header("Cookie", "cookieNameRequest=cookieValueRequest") ), headersToIgnore) ); // - in http - body parameter objects assertEquals( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body_response") .withCookies(cookie("cookieNameResponse", "cookieValueResponse")) .withHeaders( header("headerNameResponse", "headerValueResponse"), header("Set-Cookie", "cookieNameResponse=cookieValueResponse") ), makeRequest( request() .withMethod("PUT") .withPath(calculatePath("some_pathRequest")) .withBody(params( param("bodyParameterOneName", "Parameter One Value One", "Parameter One Value Two"), param("bodyParameterTwoName", "Parameter Two") )) .withHeaders(header("headerNameRequest", "headerValueRequest")) .withCookies(cookie("cookieNameRequest", "cookieValueRequest")), headersToIgnore) ); } @Test public void shouldReturnResponseByNotMatchingBodyParameterWithNotOperatorForNameAndValue() { // when mockServerClient .when( request() .withMethod("POST") .withPath(calculatePath("some_pathRequest")) .withBody(params( param(not("bodyParameterOneName"), not("Parameter One Value One"), not("Parameter One Value Two")), param("bodyParameterTwoName", "Parameter Two") )) ) .respond( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body_response") ); // then // wrong query string parameter name assertEquals( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body_response"), makeRequest( request() .withMethod("POST") .withPath(calculatePath("some_pathRequest")) .withBody(params( param("OTHERBodyParameterOneName", "Parameter One Value One", "Parameter One Value Two"), param("bodyParameterTwoName", "Parameter Two") )) .withHeaders(header("headerNameRequest", "headerValueRequest")) .withCookies(cookie("cookieNameRequest", "cookieValueRequest")), headersToIgnore) ); // wrong query string parameter name assertEquals( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body_response"), makeRequest( request() .withMethod("POST") .withPath(calculatePath("some_pathRequest")) .withBody(new StringBody("OTHERBodyParameterOneName=Parameter+One+Value+One" + "&OTHERBodyParameterOneName=Parameter+One+Value+Two" + "&bodyParameterTwoName=Parameter+Two")) .withHeaders(header("headerNameRequest", "headerValueRequest")) .withCookies(cookie("cookieNameRequest", "cookieValueRequest")), headersToIgnore) ); // wrong query string parameter value assertEquals( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body_response"), makeRequest( request() .withMethod("POST") .withPath(calculatePath("some_pathRequest")) .withBody(params( param("bodyParameterOneName", "OTHER Parameter One Value One", "OTHER Parameter One Value Two"), param("bodyParameterTwoName", "Parameter Two") )) .withHeaders(header("headerNameRequest", "headerValueRequest")) .withCookies(cookie("cookieNameRequest", "cookieValueRequest")), headersToIgnore) ); // wrong query string parameter value assertEquals( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body_response"), makeRequest( request() .withMethod("POST") .withPath(calculatePath("some_pathRequest")) .withBody(new StringBody("bodyParameterOneName=OTHER Parameter+One+Value+One" + "&bodyParameterOneName=OTHER Parameter+One+Value+Two" + "&bodyParameterTwoName=Parameter+Two")) .withHeaders(header("headerNameRequest", "headerValueRequest")) .withCookies(cookie("cookieNameRequest", "cookieValueRequest")), headersToIgnore) ); } @Test public void shouldReturnResponseByNotMatchingBodyParameterWithNotOperatorForName() { // when mockServerClient .when( request() .withMethod("POST") .withPath(calculatePath("some_pathRequest")) .withBody(params( param(not("bodyParameterOneName"), string("Parameter One Value One"), string("Parameter One Value Two")), param("bodyParameterTwoName", "Parameter Two") )) ) .respond( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body_response") ); // then // wrong query string parameter name assertEquals( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body_response"), makeRequest( request() .withMethod("POST") .withPath(calculatePath("some_pathRequest")) .withBody(params( param("OTHERBodyParameterOneName", "Parameter One Value One", "Parameter One Value Two"), param("bodyParameterTwoName", "Parameter Two") )) .withHeaders(header("headerNameRequest", "headerValueRequest")) .withCookies(cookie("cookieNameRequest", "cookieValueRequest")), headersToIgnore) ); // wrong query string parameter name assertEquals( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body_response"), makeRequest( request() .withMethod("POST") .withPath(calculatePath("some_pathRequest")) .withBody(new StringBody("OTHERBodyParameterOneName=Parameter+One+Value+One" + "&OTHERBodyParameterOneName=Parameter+One+Value+Two" + "&bodyParameterTwoName=Parameter+Two")) .withHeaders(header("headerNameRequest", "headerValueRequest")) .withCookies(cookie("cookieNameRequest", "cookieValueRequest")), headersToIgnore) ); } @Test public void shouldReturnResponseByNotMatchingBodyParameterWithNotOperatorForValue() { // when mockServerClient .when( request() .withMethod("POST") .withPath(calculatePath("some_pathRequest")) .withBody(params( param(string("bodyParameterOneName"), not("Parameter One Value One"), not("Parameter One Value Two")), param("bodyParameterTwoName", "Parameter Two") )) ) .respond( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body_response") ); // then // wrong query string parameter value assertEquals( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body_response"), makeRequest( request() .withMethod("POST") .withPath(calculatePath("some_pathRequest")) .withBody(params( param("bodyParameterOneName", "OTHER Parameter One Value One", "OTHER Parameter One Value Two"), param("bodyParameterTwoName", "Parameter Two") )) .withHeaders(header("headerNameRequest", "headerValueRequest")) .withCookies(cookie("cookieNameRequest", "cookieValueRequest")), headersToIgnore) ); // wrong query string parameter value assertEquals( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body_response"), makeRequest( request() .withMethod("POST") .withPath(calculatePath("some_pathRequest")) .withBody(new StringBody("bodyParameterOneName=OTHER Parameter+One+Value+One" + "&bodyParameterOneName=OTHER Parameter+One+Value+Two" + "&bodyParameterTwoName=Parameter+Two")) .withHeaders(header("headerNameRequest", "headerValueRequest")) .withCookies(cookie("cookieNameRequest", "cookieValueRequest")), headersToIgnore) ); } @Test public void shouldReturnResponseByNotMatchingQueryStringParameterWithNotOperatorForNameAndValue() { // when mockServerClient .when( request() .withMethod("POST") .withPath(calculatePath("some_pathRequest")) .withQueryStringParameters( param(not("queryStringParameterOneName"), not("Parameter One Value One"), not("Parameter One Value Two")), param("queryStringParameterTwoName", "Parameter Two") ) ) .respond( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body_response") ); // then // wrong query string parameter name assertEquals( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body_response"), makeRequest( request() .withMethod("POST") .withPath(calculatePath("some_pathRequest")) .withQueryStringParameters( param("OTHERQueryStringParameterOneName", "Parameter One Value One", "Parameter One Value Two"), param("queryStringParameterTwoName", "Parameter Two") ), headersToIgnore) ); // wrong query string parameter value assertEquals( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body_response"), makeRequest( request() .withMethod("POST") .withPath(calculatePath("some_pathRequest")) .withQueryStringParameters( param("queryStringParameterOneName", "OTHER Parameter One Value One", "OTHER Parameter One Value Two"), param("queryStringParameterTwoName", "Parameter Two") ), headersToIgnore) ); } @Test public void shouldReturnResponseByNotMatchingQueryStringParameterWithNotOperatorForName() { // when mockServerClient .when( request() .withMethod("POST") .withPath(calculatePath("some_pathRequest")) .withQueryStringParameters( param(not("queryStringParameterOneName"), string("Parameter One Value One"), string("Parameter One Value Two")), param("queryStringParameterTwoName", "Parameter Two") ) ) .respond( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body_response") ); // then // wrong query string parameter name assertEquals( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body_response"), makeRequest( request() .withMethod("POST") .withPath(calculatePath("some_pathRequest")) .withQueryStringParameters( param("OTHERQueryStringParameterOneName", "Parameter One Value One", "Parameter One Value Two"), param("queryStringParameterTwoName", "Parameter Two") ), headersToIgnore) ); } @Test public void shouldReturnResponseByNotMatchingQueryStringParameterWithNotOperatorForValue() { // when mockServerClient .when( request() .withMethod("POST") .withPath(calculatePath("some_pathRequest")) .withQueryStringParameters( param(string("queryStringParameterOneName"), not("Parameter One Value One"), not("Parameter One Value Two")), param("queryStringParameterTwoName", "Parameter Two") ) ) .respond( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body_response") ); // then // wrong query string parameter value assertEquals( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body_response"), makeRequest( request() .withMethod("POST") .withPath(calculatePath("some_pathRequest")) .withQueryStringParameters( param("queryStringParameterOneName", "OTHER Parameter One Value One", "OTHER Parameter One Value Two"), param("queryStringParameterTwoName", "Parameter Two") ), headersToIgnore) ); } @Test public void shouldReturnResponseByNotMatchingCookieWithNotOperatorForNameAndValue() { // when mockServerClient .when( request() .withMethod("GET") .withPath(calculatePath("some_pathRequest")) .withCookies( cookie(not("requestCookieNameOne"), not("requestCookieValueOne")), cookie("requestCookieNameTwo", "requestCookieValueTwo") ) ) .respond( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body_response") ); // then // wrong query string cookie name assertEquals( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body_response"), makeRequest( request() .withMethod("GET") .withPath(calculatePath("some_pathRequest")) .withCookies( cookie("OTHERrequestCookieNameOne", "requestCookieValueOne"), cookie("requestCookieNameTwo", "requestCookieValueTwo") ), headersToIgnore) ); // wrong query string cookie value assertEquals( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body_response"), makeRequest( request() .withMethod("GET") .withPath(calculatePath("some_pathRequest")) .withCookies( cookie("requestCookieNameOne", "OTHERrequestCookieValueOne"), cookie("requestCookieNameTwo", "requestCookieValueTwo") ), headersToIgnore) ); } @Test public void shouldReturnResponseByNotMatchingCookieWithNotOperatorForName() { // when mockServerClient .when( request() .withMethod("GET") .withPath(calculatePath("some_pathRequest")) .withCookies( cookie(not("requestCookieNameOne"), string("requestCookieValueOne")), cookie("requestCookieNameTwo", "requestCookieValueTwo") ) ) .respond( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body_response") ); // then // wrong query string cookie name assertEquals( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body_response"), makeRequest( request() .withMethod("GET") .withPath(calculatePath("some_pathRequest")) .withCookies( cookie("OTHERrequestCookieNameOne", "requestCookieValueOne"), cookie("requestCookieNameTwo", "requestCookieValueTwo") ), headersToIgnore) ); } @Test public void shouldReturnResponseByNotMatchingCookieWithNotOperatorForValue() { // when mockServerClient .when( request() .withMethod("GET") .withPath(calculatePath("some_pathRequest")) .withCookies( cookie(string("requestCookieNameOne"), not("requestCookieValueOne")), cookie("requestCookieNameTwo", "requestCookieValueTwo") ) ) .respond( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body_response") ); // then // wrong query string cookie value assertEquals( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body_response"), makeRequest( request() .withMethod("GET") .withPath(calculatePath("some_pathRequest")) .withCookies( cookie("requestCookieNameOne", "OTHERrequestCookieValueOne"), cookie("requestCookieNameTwo", "requestCookieValueTwo") ), headersToIgnore) ); } @Test public void shouldReturnResponseByNotMatchingHeaderWithNotOperatorForNameAndValue() { // when mockServerClient .when( request() .withMethod("GET") .withPath(calculatePath("some_pathRequest")) .withHeaders( header(not("requestHeaderNameOne"), not("requestHeaderValueOne")), header("requestHeaderNameTwo", "requestHeaderValueTwo") ) ) .respond( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body_response") ); // then // wrong query string header name assertEquals( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body_response"), makeRequest( request() .withMethod("GET") .withPath(calculatePath("some_pathRequest")) .withHeaders( header("OTHERrequestHeaderNameOne", "requestHeaderValueOne"), header("requestHeaderNameTwo", "requestHeaderValueTwo") ), headersToIgnore) ); // wrong query string header value assertEquals( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body_response"), makeRequest( request() .withMethod("GET") .withPath(calculatePath("some_pathRequest")) .withHeaders( header("requestHeaderNameOne", "OTHERrequestHeaderValueOne"), header("requestHeaderNameTwo", "requestHeaderValueTwo") ), headersToIgnore) ); } @Test public void shouldReturnResponseByNotMatchingHeaderWithNotOperatorForName() { // when mockServerClient .when( request() .withMethod("GET") .withPath(calculatePath("some_pathRequest")) .withHeaders( header(not("requestHeaderNameOne"), string("requestHeaderValueOne")), header("requestHeaderNameTwo", "requestHeaderValueTwo") ) ) .respond( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body_response") ); // then // wrong query string header name assertEquals( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body_response"), makeRequest( request() .withMethod("GET") .withPath(calculatePath("some_pathRequest")) .withHeaders( header("OTHERrequestHeaderNameOne", "requestHeaderValueOne"), header("requestHeaderNameTwo", "requestHeaderValueTwo") ), headersToIgnore) ); } @Test public void shouldReturnResponseByNotMatchingHeaderWithNotOperatorForValue() { // when mockServerClient .when( request() .withMethod("GET") .withPath(calculatePath("some_pathRequest")) .withHeaders( header(string("requestHeaderNameOne"), not("requestHeaderValueOne")), header("requestHeaderNameTwo", "requestHeaderValueTwo") ) ) .respond( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body_response") ); // then // wrong query string header value assertEquals( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body_response"), makeRequest( request() .withMethod("GET") .withPath(calculatePath("some_pathRequest")) .withHeaders( header("requestHeaderNameOne", "OTHERrequestHeaderValueOne"), header("requestHeaderNameTwo", "requestHeaderValueTwo") ), headersToIgnore) ); } @Test public void shouldNotReturnResponseForWhenTimeToLiveExpired() { // when mockServerClient .when( request().withPath(calculatePath("some_path")), exactly(2), TimeToLive.exactly(TimeUnit.SECONDS, 5L) ) .respond( response().withBody("some_body").withDelay(TimeUnit.SECONDS, 5L) ); // then assertEquals( response() .withStatusCode(HttpStatusCode.OK_200.code()) .withBody("some_body"), makeRequest( request() .withPath(calculatePath("some_path")), headersToIgnore) ); // - in http assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()), makeRequest( request() .withPath(calculatePath("some_path")), headersToIgnore) ); // - in https assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()), makeRequest( request() .withSecure(true) .withPath(calculatePath("some_path")), headersToIgnore) ); } @Test public void shouldNotReturnResponseForNonMatchingBody() { // when mockServerClient .when( request() .withMethod("GET") .withPath(calculatePath("some_path")) .withQueryStringParameters( param("queryStringParameterOneName", "queryStringParameterOneValue"), param("queryStringParameterTwoName", "queryStringParameterTwoValue") ) .withBody(exact("some_body")) .withHeaders(header("headerName", "headerValue")) .withCookies(cookie("cookieName", "cookieValue")) ) .respond( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body") .withHeaders(header("headerName", "headerValue")) .withCookies(cookie("cookieName", "cookieValue")) ); // then // - in http assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()), makeRequest( request() .withMethod("GET") .withPath(calculatePath("some_path")) .withQueryStringParameters( param("queryStringParameterOneName", "queryStringParameterOneValue"), param("queryStringParameterTwoName", "queryStringParameterTwoValue") ) .withBody(exact("some_other_body")) .withHeaders(header("headerName", "headerValue")) .withCookies(cookie("cookieName", "cookieValue")), headersToIgnore) ); // - in https assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()), makeRequest( request() .withMethod("GET") .withSecure(true) .withPath(calculatePath("some_path")) .withQueryStringParameters( param("queryStringParameterOneName", "queryStringParameterOneValue"), param("queryStringParameterTwoName", "queryStringParameterTwoValue") ) .withBody(exact("some_other_body")) .withHeaders(header("headerName", "headerValue")) .withCookies(cookie("cookieName", "cookieValue")), headersToIgnore) ); } @Test public void shouldNotReturnResponseForMatchingBodyWithNotOperator() { // when mockServerClient .when( request() .withBody(Not.not(json("{" + System.getProperty("line.separator") + " \"id\": 1," + System.getProperty("line.separator") + " \"name\": \"A green door\"," + System.getProperty("line.separator") + " \"price\": 12.50," + System.getProperty("line.separator") + " \"tags\": [\"home\", \"green\"]" + System.getProperty("line.separator") + "}"))), exactly(2) ) .respond( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body") ); // then // - in http assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()), makeRequest( request() .withPath(calculatePath("some_path")) .withMethod("POST") .withBody("{" + System.getProperty("line.separator") + " \"id\": 1," + System.getProperty("line.separator") + " \"extra_ignored_field\": \"some value\"," + System.getProperty("line.separator") + " \"name\": \"A green door\"," + System.getProperty("line.separator") + " \"price\": 12.50," + System.getProperty("line.separator") + " \"tags\": [\"home\", \"green\"]" + System.getProperty("line.separator") + "}"), headersToIgnore) ); // - in https assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()), makeRequest( request() .withSecure(true) .withPath(calculatePath("some_path")) .withMethod("POST") .withBody("{" + System.getProperty("line.separator") + " \"id\": 1," + System.getProperty("line.separator") + " \"extra_ignored_array\": [\"one\", \"two\"]," + System.getProperty("line.separator") + " \"name\": \"A green door\"," + System.getProperty("line.separator") + " \"price\": 12.50," + System.getProperty("line.separator") + " \"tags\": [\"home\", \"green\"]" + System.getProperty("line.separator") + "}"), headersToIgnore) ); } @Test public void shouldNotReturnResponseForNonMatchingXPathBody() { // when mockServerClient.when(request().withBody(new XPathBody("/bookstore/book[price>35]/price")), exactly(2)).respond(response().withBody("some_body")); // then // - in http assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()), makeRequest( request() .withSecure(true) .withPath(calculatePath("some_path")) .withMethod("POST") .withBody(new StringBody("" + "<?xml version=\"1.0\" encoding=\"ISO-8859-1\"?>" + System.getProperty("line.separator") + "<bookstore>" + System.getProperty("line.separator") + " <book category=\"COOKING\">" + System.getProperty("line.separator") + " <title lang=\"en\">Everyday Italian</title>" + System.getProperty("line.separator") + " <author>Giada De Laurentiis</author>" + System.getProperty("line.separator") + " <year>2005</year>" + System.getProperty("line.separator") + " <price>30.00</price>" + System.getProperty("line.separator") + " </book>" + System.getProperty("line.separator") + " <book category=\"CHILDREN\">" + System.getProperty("line.separator") + " <title lang=\"en\">Harry Potter</title>" + System.getProperty("line.separator") + " <author>J K. Rowling</author>" + System.getProperty("line.separator") + " <year>2005</year>" + System.getProperty("line.separator") + " <price>29.99</price>" + System.getProperty("line.separator") + " </book>" + System.getProperty("line.separator") + " <book category=\"WEB\">" + System.getProperty("line.separator") + " <title lang=\"en\">Learning XML</title>" + System.getProperty("line.separator") + " <author>Erik T. Ray</author>" + System.getProperty("line.separator") + " <year>2003</year>" + System.getProperty("line.separator") + " <price>31.95</price>" + System.getProperty("line.separator") + " </book>" + System.getProperty("line.separator") + "</bookstore>")), headersToIgnore) ); // - in https assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()), makeRequest( request() .withSecure(true) .withPath(calculatePath("some_path")) .withMethod("POST") .withBody(new StringBody("" + "<?xml version=\"1.0\" encoding=\"ISO-8859-1\"?>" + System.getProperty("line.separator") + "<bookstore>" + System.getProperty("line.separator") + " <book category=\"COOKING\">" + System.getProperty("line.separator") + " <title lang=\"en\">Everyday Italian</title>" + System.getProperty("line.separator") + " <author>Giada De Laurentiis</author>" + System.getProperty("line.separator") + " <year>2005</year>" + System.getProperty("line.separator") + " <price>30.00</price>" + System.getProperty("line.separator") + " </book>" + System.getProperty("line.separator") + " <book category=\"CHILDREN\">" + System.getProperty("line.separator") + " <title lang=\"en\">Harry Potter</title>" + System.getProperty("line.separator") + " <author>J K. Rowling</author>" + System.getProperty("line.separator") + " <year>2005</year>" + System.getProperty("line.separator") + " <price>29.99</price>" + System.getProperty("line.separator") + " </book>" + System.getProperty("line.separator") + " <book category=\"WEB\">" + System.getProperty("line.separator") + " <title lang=\"en\">Learning XML</title>" + System.getProperty("line.separator") + " <author>Erik T. Ray</author>" + System.getProperty("line.separator") + " <year>2003</year>" + System.getProperty("line.separator") + " <price>31.95</price>" + System.getProperty("line.separator") + " </book>" + System.getProperty("line.separator") + "</bookstore>")), headersToIgnore) ); } @Test public void shouldNotReturnResponseForNonMatchingXmlBody() { // when mockServerClient.when(request().withBody(xml("" + "<?xml version=\"1.0\" encoding=\"ISO-8859-1\"?>" + System.getProperty("line.separator") + "<bookstore>" + System.getProperty("line.separator") + " <book category=\"COOKING\" nationality=\"ITALIAN\">" + System.getProperty("line.separator") + " <title lang=\"en\">Everyday Italian</title>" + System.getProperty("line.separator") + " <author>Giada De Laurentiis</author>" + System.getProperty("line.separator") + " <year>2005</year>" + System.getProperty("line.separator") + " <price>30.00</price>" + System.getProperty("line.separator") + " </book>" + System.getProperty("line.separator") + "</bookstore>")), exactly(2)).respond(response().withBody("some_body")); // then // - in http assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()), makeRequest( request() .withSecure(true) .withPath(calculatePath("some_path")) .withMethod("POST") .withBody(new StringBody("" + "<?xml version=\"1.0\" encoding=\"ISO-8859-1\"?>" + System.getProperty("line.separator") + "<bookstore>" + System.getProperty("line.separator") + " <book category=\"COOKING\">" + System.getProperty("line.separator") + " <title lang=\"en\">Everyday Italian</title>" + System.getProperty("line.separator") + " <author>Giada De Laurentiis</author>" + System.getProperty("line.separator") + " <year>2005</year>" + System.getProperty("line.separator") + " <price>30.00</price>" + System.getProperty("line.separator") + " </book>" + System.getProperty("line.separator") + "</bookstore>")), headersToIgnore) ); // - in https assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()), makeRequest( request() .withSecure(true) .withPath(calculatePath("some_path")) .withMethod("POST") .withBody(new StringBody("" + "<?xml version=\"1.0\" encoding=\"ISO-8859-1\"?>" + System.getProperty("line.separator") + "<bookstore>" + System.getProperty("line.separator") + " <book category=\"COOKING\">" + System.getProperty("line.separator") + " <title lang=\"en\">Everyday Italian</title>" + System.getProperty("line.separator") + " <author>Giada De Laurentiis</author>" + System.getProperty("line.separator") + " <year>2005</year>" + System.getProperty("line.separator") + " <price>30.00</price>" + System.getProperty("line.separator") + " </book>" + System.getProperty("line.separator") + "</bookstore>")), headersToIgnore) ); } @Test public void shouldNotReturnResponseForNonMatchingJsonBody() { // when mockServerClient.when(request().withBody(json("{" + System.getProperty("line.separator") + " \"id\": 1," + System.getProperty("line.separator") + " \"name\": \"A green door\"," + System.getProperty("line.separator") + " \"price\": 12.50," + System.getProperty("line.separator") + " \"tags\": [\"home\", \"green\"]" + System.getProperty("line.separator") + "}")), exactly(2)).respond(response().withBody("some_body")); // then // - in http assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()), makeRequest( request() .withPath(calculatePath("some_path")) .withMethod("POST") .withBody("{" + System.getProperty("line.separator") + " \"id\": 1," + System.getProperty("line.separator") + " \"name\": \"---- XXXX WRONG VALUE XXXX ----\"," + System.getProperty("line.separator") + " \"price\": 12.50," + System.getProperty("line.separator") + " \"tags\": [\"home\", \"green\"]" + System.getProperty("line.separator") + "}"), headersToIgnore) ); // - in https assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()), makeRequest( request() .withSecure(true) .withPath(calculatePath("some_path")) .withMethod("POST") .withBody("{" + System.getProperty("line.separator") + " \"id\": 1," + System.getProperty("line.separator") + " \"name\": \"---- XXXX WRONG VALUE XXXX ----\"," + System.getProperty("line.separator") + " \"price\": 12.50," + System.getProperty("line.separator") + " \"tags\": [\"home\", \"green\"]" + System.getProperty("line.separator") + "}"), headersToIgnore) ); } @Test public void shouldNotReturnResponseForNonMatchingJsonBodyWithMatchType() { // when mockServerClient .when( request() .withBody(json("{" + System.getProperty("line.separator") + " \"id\": 1," + System.getProperty("line.separator") + " \"name\": \"A green door\"," + System.getProperty("line.separator") + " \"price\": 12.50," + System.getProperty("line.separator") + " \"tags\": [\"home\", \"green\"]" + System.getProperty("line.separator") + "}", MatchType.STRICT)), exactly(2)) .respond( response() .withBody("some_body") ); // then // - in http assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()), makeRequest( request() .withPath(calculatePath("some_path")) .withMethod("POST") .withBody("{" + System.getProperty("line.separator") + " \"id\": 1," + System.getProperty("line.separator") + " \"extra field\": \"some value\"," + System.getProperty("line.separator") + " \"name\": \"A green door\"," + System.getProperty("line.separator") + " \"price\": 12.50," + System.getProperty("line.separator") + " \"tags\": [\"home\", \"green\"]" + System.getProperty("line.separator") + "}"), headersToIgnore) ); // - in https assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()), makeRequest( request() .withSecure(true) .withPath(calculatePath("some_path")) .withMethod("POST") .withBody("{" + System.getProperty("line.separator") + " \"id\": 1," + System.getProperty("line.separator") + " \"extra field\": \"some value\"," + System.getProperty("line.separator") + " \"name\": \"A green door\"," + System.getProperty("line.separator") + " \"price\": 12.50," + System.getProperty("line.separator") + " \"tags\": [\"home\", \"green\"]" + System.getProperty("line.separator") + "}"), headersToIgnore) ); } @Test public void shouldNotReturnResponseForNonMatchingJsonSchema() { // when mockServerClient.when(request().withBody(jsonSchema("{" + System.getProperty("line.separator") + " \"$schema\": \"http://json-schema.org/draft-04/schema#\"," + System.getProperty("line.separator") + " \"title\": \"Product\"," + System.getProperty("line.separator") + " \"description\": \"A product from Acme's catalog\"," + System.getProperty("line.separator") + " \"type\": \"object\"," + System.getProperty("line.separator") + " \"properties\": {" + System.getProperty("line.separator") + " \"id\": {" + System.getProperty("line.separator") + " \"description\": \"The unique identifier for a product\"," + System.getProperty("line.separator") + " \"type\": \"integer\"" + System.getProperty("line.separator") + " }," + System.getProperty("line.separator") + " \"name\": {" + System.getProperty("line.separator") + " \"description\": \"Name of the product\"," + System.getProperty("line.separator") + " \"type\": \"string\"" + System.getProperty("line.separator") + " }," + System.getProperty("line.separator") + " \"price\": {" + System.getProperty("line.separator") + " \"type\": \"number\"," + System.getProperty("line.separator") + " \"minimum\": 0," + System.getProperty("line.separator") + " \"exclusiveMinimum\": true" + System.getProperty("line.separator") + " }," + System.getProperty("line.separator") + " \"tags\": {" + System.getProperty("line.separator") + " \"type\": \"array\"," + System.getProperty("line.separator") + " \"items\": {" + System.getProperty("line.separator") + " \"type\": \"string\"" + System.getProperty("line.separator") + " }," + System.getProperty("line.separator") + " \"minItems\": 1," + System.getProperty("line.separator") + " \"uniqueItems\": true" + System.getProperty("line.separator") + " }" + System.getProperty("line.separator") + " }," + System.getProperty("line.separator") + " \"required\": [\"id\", \"name\", \"price\"]" + System.getProperty("line.separator") + "}")), exactly(2)).respond(response().withBody("some_body")); // then // - in http assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()), makeRequest( request() .withPath(calculatePath("some_path")) .withMethod("POST") .withBody("{" + System.getProperty("line.separator") + " \"id\": 1," + System.getProperty("line.separator") + " \"wrong field name\": \"A green door\"," + System.getProperty("line.separator") + " \"price\": 12.50," + System.getProperty("line.separator") + " \"tags\": [\"home\", \"green\"]" + System.getProperty("line.separator") + "}"), headersToIgnore) ); // - in https assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()), makeRequest( request() .withSecure(true) .withPath(calculatePath("some_path")) .withMethod("POST") .withBody("{" + System.getProperty("line.separator") + " \"id\": 1," + System.getProperty("line.separator") + " \"name\": \"A green door\"," + System.getProperty("line.separator") + " \"wrong field name\": 12.50," + System.getProperty("line.separator") + " \"tags\": [\"home\", \"green\"]" + System.getProperty("line.separator") + "}"), headersToIgnore) ); } @Test public void shouldNotReturnResponseForNonMatchingPath() { // when mockServerClient .when( request() .withMethod("GET") .withPath(calculatePath("some_path")) .withQueryStringParameters( param("queryStringParameterOneName", "queryStringParameterOneValue"), param("queryStringParameterTwoName", "queryStringParameterTwoValue") ) .withBody(exact("some_body")) .withHeaders(header("headerName", "headerValue")) .withCookies(cookie("cookieName", "cookieValue")) ) .respond( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body") .withHeaders(header("headerName", "headerValue")) .withCookies(cookie("cookieName", "cookieValue")) ); // then // - in http assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()), makeRequest( request() .withMethod("GET") .withPath(calculatePath("some_other_path")) .withQueryStringParameters( param("queryStringParameterOneName", "queryStringParameterOneValue"), param("queryStringParameterTwoName", "queryStringParameterTwoValue") ) .withBody(exact("some_body")) .withHeaders(header("headerName", "headerValue")) .withCookies(cookie("cookieName", "cookieValue")), headersToIgnore) ); // - in https assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()), makeRequest( request() .withMethod("GET") .withSecure(true) .withPath(calculatePath("some_other_path")) .withQueryStringParameters( param("queryStringParameterOneName", "queryStringParameterOneValue"), param("queryStringParameterTwoName", "queryStringParameterTwoValue") ) .withBody(exact("some_body")) .withHeaders(header("headerName", "headerValue")) .withCookies(cookie("cookieName", "cookieValue")), headersToIgnore) ); } @Test public void shouldNotReturnResponseForMatchingPathWithNotOperator() { // when mockServerClient .when( request() .withPath(not(calculatePath("some_path"))) ) .respond( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body_response") ); // then // - in http assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()), makeRequest( request() .withPath(calculatePath("some_path")), headersToIgnore) ); // - in https assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()), makeRequest( request() .withPath(calculatePath("some_path")), headersToIgnore) ); } @Test public void shouldNotReturnResponseForMatchingMethodWithNotOperator() { // when mockServerClient .when( request() .withMethod(not("GET")) ) .respond( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body_response") ); // then // - in http assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()), makeRequest( request() .withMethod("GET"), headersToIgnore) ); // - in https assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()), makeRequest( request() .withMethod("GET"), headersToIgnore) ); } @Test public void shouldNotReturnResponseForNonMatchingBodyParameterName() { // when mockServerClient .when( request() .withMethod("POST") .withPath(calculatePath("some_pathRequest")) .withBody(params( param("bodyParameterOneName", "Parameter One Value One", "Parameter One Value Two"), param("bodyParameterTwoName", "Parameter Two") )) ) .respond( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body_response") .withHeaders(header("headerNameResponse", "headerValueResponse")) .withCookies(cookie("cookieNameResponse", "cookieValueResponse")) ); // then // wrong query string parameter name assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()), makeRequest( request() .withMethod("POST") .withPath(calculatePath("some_pathRequest")) .withBody(params( param("OTHERBodyParameterOneName", "Parameter One Value One", "Parameter One Value Two"), param("bodyParameterTwoName", "Parameter Two") )) .withHeaders(header("headerNameRequest", "headerValueRequest")) .withCookies(cookie("cookieNameRequest", "cookieValueRequest")), headersToIgnore) ); // wrong query string parameter name assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()), makeRequest( request() .withMethod("POST") .withPath(calculatePath("some_pathRequest")) .withBody(new StringBody("OTHERBodyParameterOneName=Parameter+One+Value+One" + "&bodyParameterOneName=Parameter+One+Value+Two" + "&bodyParameterTwoName=Parameter+Two")) .withHeaders(header("headerNameRequest", "headerValueRequest")) .withCookies(cookie("cookieNameRequest", "cookieValueRequest")), headersToIgnore) ); } @Test public void shouldNotReturnResponseForMatchingBodyParameterWithNotOperator() { // when mockServerClient .when( request() .withMethod("POST") .withPath(calculatePath("some_pathRequest")) .withBody(params( param(not("bodyParameterOneName"), not("Parameter One Value One"), not("Parameter One Value Two")), param("bodyParameterTwoName", "Parameter Two") )) ) .respond( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body_response") ); // then // wrong query string parameter name assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()), makeRequest( request() .withMethod("POST") .withPath(calculatePath("some_pathRequest")) .withBody(params( param("bodyParameterOneName", "Parameter One Value One", "Parameter One Value Two"), param("bodyParameterTwoName", "Parameter Two") )) .withHeaders(header("headerNameRequest", "headerValueRequest")) .withCookies(cookie("cookieNameRequest", "cookieValueRequest")), headersToIgnore) ); // wrong query string parameter name assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()), makeRequest( request() .withMethod("POST") .withPath(calculatePath("some_pathRequest")) .withBody(new StringBody("bodyParameterOneName=Other Parameter+One+Value+One" + "&bodyParameterOneName=Parameter+One+Value+Two" + "&bodyParameterTwoName=Parameter+Two")) .withHeaders(header("headerNameRequest", "headerValueRequest")) .withCookies(cookie("cookieNameRequest", "cookieValueRequest")), headersToIgnore) ); } @Test public void shouldNotReturnResponseForNonMatchingBodyParameterValue() { // when mockServerClient .when( request() .withMethod("POST") .withPath(calculatePath("some_pathRequest")) .withBody(params( param("bodyParameterOneName", "Parameter One Value One", "Parameter One Value Two"), param("bodyParameterTwoName", "Parameter Two") )) ) .respond( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body_response") .withHeaders(header("headerNameResponse", "headerValueResponse")) .withCookies(cookie("cookieNameResponse", "cookieValueResponse")) ); // then // wrong body parameter value assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()), makeRequest( request() .withMethod("POST") .withPath(calculatePath("some_pathRequest")) .withBody(params( param("bodyParameterOneName", "Other Parameter One Value One", "Parameter One Value Two"), param("bodyParameterTwoName", "Parameter Two") )) .withHeaders(header("headerNameRequest", "headerValueRequest")) .withCookies(cookie("cookieNameRequest", "cookieValueRequest")), headersToIgnore) ); // wrong body parameter value assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()), makeRequest( request() .withMethod("POST") .withPath(calculatePath("some_pathRequest")) .withBody(new StringBody("bodyParameterOneName=Other Parameter+One+Value+One" + "&bodyParameterOneName=Parameter+One+Value+Two" + "&bodyParameterTwoName=Parameter+Two")) .withHeaders(header("headerNameRequest", "headerValueRequest")) .withCookies(cookie("cookieNameRequest", "cookieValueRequest")), headersToIgnore) ); } @Test public void shouldNotReturnResponseForNonMatchingQueryStringParameterName() { // when mockServerClient .when( request() .withMethod("POST") .withPath(calculatePath("some_pathRequest")) .withQueryStringParameters( param("queryStringParameterOneName", "queryStringParameterOneValueOne", "queryStringParameterOneValueTwo"), param("queryStringParameterTwoName", "queryStringParameterTwoValue") ) .withBody("some_bodyRequest") ) .respond( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body_response") .withHeaders(header("headerNameResponse", "headerValueResponse")) .withCookies(cookie("cookieNameResponse", "cookieValueResponse")) ); // then // wrong query string parameter name assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()), makeRequest( request() .withMethod("POST") .withPath(calculatePath("some_pathRequest")) .withQueryStringParameters( param("OTHERQueryStringParameterOneName", "queryStringParameterOneValueOne", "queryStringParameterOneValueTwo"), param("queryStringParameterTwoName", "queryStringParameterTwoValue") ) .withBody("some_bodyRequest") .withHeaders( header("headerNameRequest", "headerValueRequest") ) .withCookies(cookie("cookieNameRequest", "cookieValueRequest")), headersToIgnore) ); } @Test public void shouldNotReturnResponseForNonMatchingQueryStringParameterValue() { // when mockServerClient .when( request() .withMethod("POST") .withPath(calculatePath("some_pathRequest")) .withQueryStringParameters( param("queryStringParameterOneName", "queryStringParameterOneValueOne", "queryStringParameterOneValueTwo"), param("queryStringParameterTwoName", "queryStringParameterTwoValue") ) .withBody("some_bodyRequest") ) .respond( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body_response") .withHeaders(header("headerNameResponse", "headerValueResponse")) .withCookies(cookie("cookieNameResponse", "cookieValueResponse")) ); // then // wrong query string parameter value assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()), makeRequest( request() .withMethod("POST") .withPath(calculatePath("some_pathRequest")) .withQueryStringParameters( param("queryStringParameterOneName", "OTHERqueryStringParameterOneValueOne", "queryStringParameterOneValueTwo"), param("queryStringParameterTwoName", "queryStringParameterTwoValue") ) .withBody("some_bodyRequest") .withHeaders(header("headerNameRequest", "headerValueRequest")) .withCookies(cookie("cookieNameRequest", "cookieValueRequest")), headersToIgnore) ); } @Test public void shouldNotReturnResponseForMatchingQueryStringParameterWithNotOperator() { // when mockServerClient .when( request() .withMethod("POST") .withPath(calculatePath("some_pathRequest")) .withQueryStringParameters( param(not("queryStringParameterOneName"), not("Parameter One Value One"), not("Parameter One Value Two")), param("queryStringParameterTwoName", "Parameter Two") ) ) .respond( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body_response") ); // then // wrong query string parameter name assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()), makeRequest( request() .withMethod("POST") .withPath(calculatePath("some_pathRequest")) .withQueryStringParameters( param("queryStringParameterOneName", "Parameter One Value One", "Parameter One Value Two"), param("queryStringParameterTwoName", "Parameter Two") ), headersToIgnore) ); // wrong query string parameter name assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()), makeRequest( request() .withMethod("POST") .withPath(calculatePath("some_pathRequest")) .withQueryStringParameters( param("queryStringParameterOneName", "Parameter One Value One", "Parameter One Value Two"), param("queryStringParameterTwoName", "Parameter Two") ), headersToIgnore) ); } @Test public void shouldNotReturnResponseForNonMatchingCookieName() { // when mockServerClient .when( request() .withMethod("GET") .withPath(calculatePath("some_path")) .withQueryStringParameters( param("queryStringParameterOneName", "queryStringParameterOneValue"), param("queryStringParameterTwoName", "queryStringParameterTwoValue") ) .withBody(exact("some_body")) .withHeaders(header("headerName", "headerValue")) .withCookies(cookie("cookieName", "cookieValue")) ) .respond( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body") .withHeaders(header("headerName", "headerValue")) .withCookies(cookie("cookieName", "cookieValue")) ); // then // - in http assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()), makeRequest( request() .withMethod("GET") .withPath(calculatePath("some_path")) .withQueryStringParameters( param("queryStringParameterOneName", "queryStringParameterOneValue"), param("queryStringParameterTwoName", "queryStringParameterTwoValue") ) .withBody(exact("some_body")) .withHeaders(header("headerName", "headerValue")) .withCookies(cookie("cookieOtherName", "cookieValue")), headersToIgnore) ); // - in https assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()), makeRequest( request() .withMethod("GET") .withSecure(true) .withPath(calculatePath("some_path")) .withQueryStringParameters( param("queryStringParameterOneName", "queryStringParameterOneValue"), param("queryStringParameterTwoName", "queryStringParameterTwoValue") ) .withBody(exact("some_body")) .withHeaders(header("headerName", "headerValue")) .withCookies(cookie("cookieOtherName", "cookieValue")), headersToIgnore) ); } @Test public void shouldNotReturnResponseForNonMatchingCookieValue() { // when mockServerClient .when( request() .withMethod("GET") .withPath(calculatePath("some_path")) .withQueryStringParameters( param("queryStringParameterOneName", "queryStringParameterOneValue"), param("queryStringParameterTwoName", "queryStringParameterTwoValue") ) .withBody(exact("some_body")) .withHeaders(header("headerName", "headerValue")) .withCookies(cookie("cookieName", "cookieValue")) ) .respond( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body") .withHeaders(header("headerName", "headerValue")) .withCookies(cookie("cookieName", "cookieValue")) ); // then // - in http assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()), makeRequest( request() .withMethod("GET") .withPath(calculatePath("some_path")) .withQueryStringParameters( param("queryStringParameterOneName", "queryStringParameterOneValue"), param("queryStringParameterTwoName", "queryStringParameterTwoValue") ) .withBody(exact("some_body")) .withHeaders(header("headerName", "headerValue")) .withCookies(cookie("cookieName", "cookieOtherValue")), headersToIgnore) ); // - in https assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()), makeRequest( request() .withMethod("GET") .withSecure(true) .withPath(calculatePath("some_path")) .withQueryStringParameters( param("queryStringParameterOneName", "queryStringParameterOneValue"), param("queryStringParameterTwoName", "queryStringParameterTwoValue") ) .withBody(exact("some_body")) .withHeaders(header("headerName", "headerValue")) .withCookies(cookie("cookieName", "cookieOtherValue")), headersToIgnore) ); } @Test public void shouldNotReturnResponseForMatchingCookieWithNotOperator() { // when mockServerClient .when( request() .withMethod("GET") .withPath(calculatePath("some_pathRequest")) .withCookies( cookie(not("requestCookieNameOne"), not("requestCookieValueOne")), cookie("requestCookieNameTwo", "requestCookieValueTwo") ) ) .respond( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body_response") ); // then // wrong query string parameter name assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()), makeRequest( request() .withMethod("GET") .withPath(calculatePath("some_pathRequest")) .withCookies( cookie("requestCookieNameOne", "requestCookieValueOne"), cookie("requestCookieNameTwo", "requestCookieValueTwo") ), headersToIgnore) ); // wrong query string parameter name assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()), makeRequest( request() .withMethod("GET") .withPath(calculatePath("some_pathRequest")) .withCookies( cookie("requestCookieNameOne", "requestCookieValueOne"), cookie("requestCookieNameTwo", "requestCookieValueTwo") ), headersToIgnore) ); } @Test public void shouldNotReturnResponseForNonMatchingHeaderName() { // when mockServerClient .when( request() .withMethod("GET") .withPath(calculatePath("some_path")) .withQueryStringParameters( param("queryStringParameterOneName", "queryStringParameterOneValue"), param("queryStringParameterTwoName", "queryStringParameterTwoValue") ) .withBody(exact("some_body")) .withHeaders(header("headerName", "headerValue")) .withCookies(cookie("cookieName", "cookieValue")) ) .respond( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body") .withHeaders(header("headerName", "headerValue")) .withCookies(cookie("cookieName", "cookieValue")) ); // then // - in http assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()), makeRequest( request() .withMethod("GET") .withPath(calculatePath("some_path")) .withQueryStringParameters( param("queryStringParameterOneName", "queryStringParameterOneValue"), param("queryStringParameterTwoName", "queryStringParameterTwoValue") ) .withBody(exact("some_body")) .withHeaders(header("headerOtherName", "headerValue")) .withCookies(cookie("cookieName", "cookieValue")), headersToIgnore) ); // - in https assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()), makeRequest( request() .withMethod("GET") .withSecure(true) .withPath(calculatePath("some_path")) .withQueryStringParameters( param("queryStringParameterOneName", "queryStringParameterOneValue"), param("queryStringParameterTwoName", "queryStringParameterTwoValue") ) .withBody(exact("some_body")) .withHeaders(header("headerOtherName", "headerValue")) .withCookies(cookie("cookieName", "cookieValue")), headersToIgnore) ); } @Test public void shouldNotReturnResponseForNonMatchingHeaderValue() { // when mockServerClient .when( request() .withMethod("GET") .withPath(calculatePath("some_path")) .withQueryStringParameters( param("queryStringParameterOneName", "queryStringParameterOneValue"), param("queryStringParameterTwoName", "queryStringParameterTwoValue") ) .withBody(exact("some_body")) .withHeaders(header("headerName", "headerValue")) .withCookies(cookie("cookieName", "cookieValue")) ) .respond( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body") .withHeaders(header("headerName", "headerValue")) .withCookies(cookie("cookieName", "cookieValue")) ); // then // - in http assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()), makeRequest( request() .withMethod("GET") .withPath(calculatePath("some_path")) .withQueryStringParameters( param("queryStringParameterOneName", "queryStringParameterOneValue"), param("queryStringParameterTwoName", "queryStringParameterTwoValue") ) .withBody(exact("some_body")) .withHeaders(header("headerName", "headerOtherValue")) .withCookies(cookie("cookieName", "cookieValue")), headersToIgnore) ); // - in https assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()), makeRequest( request() .withMethod("GET") .withSecure(true) .withPath(calculatePath("some_path")) .withQueryStringParameters( param("queryStringParameterOneName", "queryStringParameterOneValue"), param("queryStringParameterTwoName", "queryStringParameterTwoValue") ) .withBody(exact("some_body")) .withHeaders(header("headerName", "headerOtherValue")) .withCookies(cookie("cookieName", "cookieValue")), headersToIgnore) ); } @Test public void shouldNotReturnResponseForMatchingHeaderWithNotOperator() { // when mockServerClient .when( request() .withMethod("GET") .withPath(calculatePath("some_pathRequest")) .withHeaders( header(not("requestHeaderNameOne"), not("requestHeaderValueOne")), header("requestHeaderNameTwo", "requestHeaderValueTwo") ) ) .respond( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body_response") ); // then // wrong query string parameter name assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()), makeRequest( request() .withMethod("GET") .withPath(calculatePath("some_pathRequest")) .withHeaders( header("requestHeaderNameOne", "requestHeaderValueOne"), header("requestHeaderNameTwo", "requestHeaderValueTwo") ), headersToIgnore) ); // wrong query string parameter name assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()), makeRequest( request() .withMethod("GET") .withPath(calculatePath("some_pathRequest")) .withHeaders( header("requestHeaderNameOne", "requestHeaderValueOne"), header("requestHeaderNameTwo", "requestHeaderValueTwo") ), headersToIgnore) ); } @Test public void shouldVerifyReceivedRequests() { // when mockServerClient .when( request() .withPath(calculatePath("some_path")), exactly(2) ) .respond( response() .withBody("some_body") ); // then // - in http assertEquals( response() .withStatusCode(HttpStatusCode.OK_200.code()) .withBody("some_body"), makeRequest( request() .withPath(calculatePath("some_path")), headersToIgnore) ); mockServerClient.verify(request() .withPath(calculatePath("some_path"))); mockServerClient.verify(request() .withPath(calculatePath("some_path")), VerificationTimes.exactly(1)); // - in https assertEquals( response() .withStatusCode(HttpStatusCode.OK_200.code()) .withBody("some_body"), makeRequest( request() .withSecure(true) .withPath(calculatePath("some_path")), headersToIgnore) ); mockServerClient.verify(request().withPath(calculatePath("some_path")), VerificationTimes.atLeast(1)); mockServerClient.verify(request().withPath(calculatePath("some_path")), VerificationTimes.exactly(2)); } @Test public void shouldVerifyReceivedRequestInSsl() { // when mockServerClient .when( request() .withPath(calculatePath("some.*path")), exactly(2) ) .respond( response() .withBody("some_body") ); // then // - in http assertEquals( response() .withStatusCode(HttpStatusCode.OK_200.code()) .withBody("some_body"), makeRequest( request() .withPath(calculatePath("some_path")), headersToIgnore) ); mockServerClient.verify(request() .withPath(calculatePath("some_path")) .withSecure(false)); mockServerClient.verify(request() .withPath(calculatePath("some_path")) .withSecure(false), VerificationTimes.exactly(1)); // - in https assertEquals( response() .withStatusCode(HttpStatusCode.OK_200.code()) .withBody("some_body"), makeRequest( request() .withPath(calculatePath("some_secure_path")) .withSecure(true), headersToIgnore) ); mockServerClient.verify(request() .withPath(calculatePath("some_secure_path")) .withSecure(true)); mockServerClient.verify(request() .withPath(calculatePath("some_secure_path")) .withSecure(true), VerificationTimes.exactly(1)); } @Test public void shouldVerifyReceivedRequestsWithNoBody() { // when mockServerClient.when(request().withPath(calculatePath("some_path")), exactly(2)).respond(response()); // then // - in http assertEquals( response() .withStatusCode(HttpStatusCode.OK_200.code()), makeRequest( request() .withPath(calculatePath("some_path")), headersToIgnore) ); mockServerClient.verify(request() .withPath(calculatePath("some_path"))); mockServerClient.verify(request() .withPath(calculatePath("some_path")), VerificationTimes.exactly(1)); } @Test public void shouldVerifyNotEnoughRequestsReceived() { // when mockServerClient.when(request().withPath(calculatePath("some_path")), exactly(2)).respond(response().withBody("some_body")); // then assertEquals( response() .withStatusCode(HttpStatusCode.OK_200.code()) .withBody("some_body"), makeRequest( request() .withPath(calculatePath("some_path")), headersToIgnore) ); try { mockServerClient.verify(request() .withPath(calculatePath("some_path")), VerificationTimes.atLeast(2)); fail(); } catch (AssertionError ae) { assertThat(ae.getMessage(), startsWith("Request not found at least 2 times, expected:<{" + System.getProperty("line.separator") + " \"path\" : \"" + calculatePath("some_path") + "\"" + System.getProperty("line.separator") + "}> but was:<{" + System.getProperty("line.separator") + " \"method\" : \"GET\"," + System.getProperty("line.separator") + " \"path\" : \"" + calculatePath("some_path") + "\"," + System.getProperty("line.separator"))); } } @Test public void shouldVerifyTooManyRequestsReceived() { // when mockServerClient.when(request().withPath(calculatePath("some_path")), exactly(2)).respond(response().withBody("some_body")); // then assertEquals( response() .withStatusCode(HttpStatusCode.OK_200.code()) .withBody("some_body"), makeRequest( request() .withPath(calculatePath("some_path")), headersToIgnore) ); try { mockServerClient.verify(request() .withPath(calculatePath("some_path")), VerificationTimes.exactly(0)); fail(); } catch (AssertionError ae) { assertThat(ae.getMessage(), startsWith("Request not found exactly 0 times, expected:<{" + System.getProperty("line.separator") + " \"path\" : \"" + calculatePath("some_path") + "\"" + System.getProperty("line.separator") + "}> but was:<{" + System.getProperty("line.separator") + " \"method\" : \"GET\"," + System.getProperty("line.separator") + " \"path\" : \"" + calculatePath("some_path") + "\"," + System.getProperty("line.separator"))); } } @Test public void shouldVerifyNoMatchingRequestsReceived() { // when mockServerClient.when(request().withPath(calculatePath("some_path")), exactly(2)).respond(response().withBody("some_body")); // then assertEquals( response() .withStatusCode(HttpStatusCode.OK_200.code()) .withBody("some_body"), makeRequest( request() .withPath(calculatePath("some_path")), headersToIgnore) ); try { mockServerClient.verify(request() .withPath(calculatePath("some_other_path")), VerificationTimes.exactly(2)); fail(); } catch (AssertionError ae) { assertThat(ae.getMessage(), startsWith("Request not found exactly 2 times, expected:<{" + System.getProperty("line.separator") + " \"path\" : \"" + calculatePath("some_other_path") + "\"" + System.getProperty("line.separator") + "}> but was:<{" + System.getProperty("line.separator") + " \"method\" : \"GET\"," + System.getProperty("line.separator") + " \"path\" : \"" + calculatePath("some_path") + "\"," + System.getProperty("line.separator"))); } } @Test public void shouldVerifyNoRequestsReceived() { // when mockServerClient.reset(); // then mockServerClient.verifyZeroInteractions(); } @Test public void shouldNotVerifyNoRequestsReceived() { // when mockServerClient.when(request().withPath(calculatePath("some_path")), exactly(2)).respond(response().withBody("some_body")); // then assertEquals( response() .withStatusCode(HttpStatusCode.OK_200.code()) .withBody("some_body"), makeRequest( request() .withPath(calculatePath("some_path")), headersToIgnore) ); try { mockServerClient.verifyZeroInteractions(); fail(); } catch (AssertionError ae) { assertThat(ae.getMessage(), startsWith("Request not found exactly 0 times, expected:<{ }> but was:<{" + System.getProperty("line.separator") + " \"method\" : \"GET\"," + System.getProperty("line.separator") + " \"path\" : \"" + calculatePath("some_path") + "\"," + System.getProperty("line.separator"))); } } @Test public void shouldVerifyNoMatchingRequestsReceivedInSsl() { // when mockServerClient.when(request().withPath(calculatePath("some.*path")), exactly(2)).respond(response().withBody("some_body")); // then // - in http assertEquals( response() .withStatusCode(HttpStatusCode.OK_200.code()) .withBody("some_body"), makeRequest( request() .withPath(calculatePath("some_path")), headersToIgnore) ); try { mockServerClient.verify( request() .withPath(calculatePath("some_path")) .withSecure(true), VerificationTimes.atLeast(1) ); fail(); } catch (AssertionError ae) { assertThat(ae.getMessage(), startsWith("Request not found at least once, expected:<{" + System.getProperty("line.separator") + " \"path\" : \"" + calculatePath("some_path") + "\"," + System.getProperty("line.separator") + " \"secure\" : true" + System.getProperty("line.separator") + "}> but was:<{" + System.getProperty("line.separator") + " \"method\" : \"GET\"," + System.getProperty("line.separator") + " \"path\" : \"" + calculatePath("some_path") + "\"," + System.getProperty("line.separator"))); } // - in https assertEquals( response() .withStatusCode(HttpStatusCode.OK_200.code()) .withBody("some_body"), makeRequest( request() .withPath(calculatePath("some_secure_path")) .withSecure(true), headersToIgnore) ); try { mockServerClient.verify( request() .withPath(calculatePath("some_secure_path")) .withSecure(false), VerificationTimes.atLeast(1) ); fail(); } catch (AssertionError ae) { assertThat(ae.getMessage(), startsWith("Request not found at least once, expected:<{" + System.getProperty("line.separator") + " \"path\" : \"" + calculatePath("some_secure_path") + "\"," + System.getProperty("line.separator") + " \"secure\" : false" + System.getProperty("line.separator") + "}> but was:<[ {" + System.getProperty("line.separator") + " \"method\" : \"GET\"," + System.getProperty("line.separator") + " \"path\" : \"" + calculatePath("some_path") + "\"," + System.getProperty("line.separator"))); } } @Test public void shouldVerifySequenceOfRequestsReceived() { // when mockServerClient.when(request().withPath(calculatePath("some_path.*")), exactly(6)).respond(response().withBody("some_body")); // then assertEquals( response("some_body"), makeRequest( request().withPath(calculatePath("some_path_one")), headersToIgnore) ); assertEquals( response("some_body"), makeRequest( request().withPath(calculatePath("some_path_two")), headersToIgnore) ); assertEquals( response("some_body"), makeRequest( request().withPath(calculatePath("some_path_three")), headersToIgnore) ); mockServerClient.verify(request(calculatePath("some_path_one")), request(calculatePath("some_path_three"))); mockServerClient.verify(request(calculatePath("some_path_one")), request(calculatePath("some_path_two"))); mockServerClient.verify(request(calculatePath("some_path_one")), request(calculatePath("some_path_two")), request(calculatePath("some_path_three"))); } @Test public void shouldVerifySequenceOfRequestsReceivedIncludingThoseNotMatchingAnException() { // when mockServerClient.when(request().withPath(calculatePath("some_path.*")), exactly(4)).respond(response().withBody("some_body")); // then assertEquals( response("some_body"), makeRequest( request().withPath(calculatePath("some_path_one")), headersToIgnore) ); assertEquals( notFoundResponse(), makeRequest( request().withPath(calculatePath("not_found")), headersToIgnore) ); assertEquals( response("some_body"), makeRequest( request().withPath(calculatePath("some_path_three")), headersToIgnore) ); mockServerClient.verify(request(calculatePath("some_path_one")), request(calculatePath("some_path_three"))); mockServerClient.verify(request(calculatePath("some_path_one")), request(calculatePath("not_found"))); mockServerClient.verify(request(calculatePath("some_path_one")), request(calculatePath("not_found")), request(calculatePath("some_path_three"))); mockServerClient.verify(request(calculatePath("some_path_one")), request(calculatePath("not_found")), request(calculatePath("some_path_three"))); } @Test public void shouldRetrieveSequenceOfRequestsReceivedIncludingThoseNotMatchingAnException() { // when mockServerClient.when(request().withPath(calculatePath("some_path.*")), exactly(4)).respond(response().withBody("some_body")); assertEquals( response("some_body"), makeRequest( request().withPath(calculatePath("some_path_one")), headersToIgnore) ); assertEquals( notFoundResponse(), makeRequest( request().withPath(calculatePath("not_found")), headersToIgnore) ); assertEquals( response("some_body"), makeRequest( request().withPath(calculatePath("some_path_three")), headersToIgnore) ); // then verifyRequestMatches( mockServerClient.retrieveRecordedRequests(request().withPath(calculatePath("some_path.*"))), request(calculatePath("some_path_one")), request(calculatePath("some_path_three")) ); verifyRequestMatches( mockServerClient.retrieveRecordedRequests(request()), request(calculatePath("some_path_one")), request(calculatePath("not_found")), request(calculatePath("some_path_three")) ); verifyRequestMatches( mockServerClient.retrieveRecordedRequests(null), request(calculatePath("some_path_one")), request(calculatePath("not_found")), request(calculatePath("some_path_three")) ); } @Test public void shouldRetrieveSequenceOfExpectationsSetup() { // when mockServerClient.when(request().withPath(calculatePath("some_path.*")), exactly(4)) .respond(response().withBody("some_body")); mockServerClient.when(request().withPath(calculatePath("some_path.*"))) .respond(response().withBody("some_body")); mockServerClient.when(request().withPath(calculatePath("some_other_path"))) .respond(response().withBody("some_other_body")); mockServerClient.when(request().withPath(calculatePath("some_forward_path"))) .forward(forward()); // then assertThat( mockServerClient.retrieveExistingExpectations(request().withPath(calculatePath("some_path.*"))), arrayContaining( new Expectation(request().withPath(calculatePath("some_path.*")), exactly(4), TimeToLive.unlimited()) .thenRespond(response().withBody("some_body")), expectation(request().withPath(calculatePath("some_path.*"))) .thenRespond(response().withBody("some_body")) ) ); assertThat( mockServerClient.retrieveExistingExpectations(null), arrayContaining( new Expectation(request().withPath(calculatePath("some_path.*")), exactly(4), TimeToLive.unlimited()) .thenRespond(response().withBody("some_body")), expectation(request().withPath(calculatePath("some_path.*"))) .thenRespond(response().withBody("some_body")), expectation(request().withPath(calculatePath("some_other_path"))) .thenRespond(response().withBody("some_other_body")), expectation(request().withPath(calculatePath("some_forward_path"))) .thenForward(forward()) ) ); assertThat( mockServerClient.retrieveExistingExpectations(request()), arrayContaining( new Expectation(request().withPath(calculatePath("some_path.*")), exactly(4), TimeToLive.unlimited()) .thenRespond(response().withBody("some_body")), expectation(request().withPath(calculatePath("some_path.*"))) .thenRespond(response().withBody("some_body")), expectation(request().withPath(calculatePath("some_other_path"))) .thenRespond(response().withBody("some_other_body")), expectation(request().withPath(calculatePath("some_forward_path"))) .thenForward(forward()) ) ); } @Test public void shouldVerifySequenceOfRequestsNotReceived() { // when mockServerClient.when(request().withPath(calculatePath("some_path.*")), exactly(6)).respond(response().withBody("some_body")); // then assertEquals( response("some_body"), makeRequest( request().withPath(calculatePath("some_path_one")), headersToIgnore) ); assertEquals( response("some_body"), makeRequest( request().withPath(calculatePath("some_path_two")), headersToIgnore) ); assertEquals( response("some_body"), makeRequest( request().withPath(calculatePath("some_path_three")), headersToIgnore) ); try { mockServerClient.verify(request(calculatePath("some_path_two")), request(calculatePath("some_path_one"))); fail(); } catch (AssertionError ae) { assertThat(ae.getMessage(), startsWith("Request sequence not found, expected:<[ {" + System.getProperty("line.separator") + " \"path\" : \"" + calculatePath("some_path_two") + "\"" + System.getProperty("line.separator") + "}, {" + System.getProperty("line.separator") + " \"path\" : \"" + calculatePath("some_path_one") + "\"" + System.getProperty("line.separator") + "} ]> but was:<[ {" + System.getProperty("line.separator") + " \"method\" : \"GET\"," + System.getProperty("line.separator") + " \"path\" : \"" + calculatePath("some_path_one") + "\"," + System.getProperty("line.separator"))); } try { mockServerClient.verify(request(calculatePath("some_path_three")), request(calculatePath("some_path_two"))); fail(); } catch (AssertionError ae) { assertThat(ae.getMessage(), startsWith("Request sequence not found, expected:<[ {" + System.getProperty("line.separator") + " \"path\" : \"" + calculatePath("some_path_three") + "\"" + System.getProperty("line.separator") + "}, {" + System.getProperty("line.separator") + " \"path\" : \"" + calculatePath("some_path_two") + "\"" + System.getProperty("line.separator") + "} ]> but was:<[ {" + System.getProperty("line.separator") + " \"method\" : \"GET\"," + System.getProperty("line.separator") + " \"path\" : \"" + calculatePath("some_path_one") + "\"," + System.getProperty("line.separator"))); } try { mockServerClient.verify(request(calculatePath("some_path_four"))); fail(); } catch (AssertionError ae) { assertThat(ae.getMessage(), startsWith("Request sequence not found, expected:<[ {" + System.getProperty("line.separator") + " \"path\" : \"" + calculatePath("some_path_four") + "\"" + System.getProperty("line.separator") + "} ]> but was:<[ {" + System.getProperty("line.separator") + " \"method\" : \"GET\"," + System.getProperty("line.separator") + " \"path\" : \"" + calculatePath("some_path_one") + "\"," + System.getProperty("line.separator"))); } } @Test public void shouldClearExpectationsAndLogs() { // given - some expectations mockServerClient .when( request() .withPath(calculatePath("some_path1")) ) .respond( response() .withBody("some_body1") ); mockServerClient .when( request() .withPath(calculatePath("some_path2")) ) .respond( response() .withBody("some_body2") ); // and - some matching requests assertEquals( response() .withStatusCode(HttpStatusCode.OK_200.code()) .withBody("some_body1"), makeRequest( request() .withPath(calculatePath("some_path1")), headersToIgnore) ); assertEquals( response() .withStatusCode(HttpStatusCode.OK_200.code()) .withBody("some_body2"), makeRequest( request() .withPath(calculatePath("some_path2")), headersToIgnore) ); // when mockServerClient .clear( request() .withPath(calculatePath("some_path1")) ); // then - expectations cleared assertThat( mockServerClient.retrieveExistingExpectations(null), arrayContaining( expectation( request() .withPath(calculatePath("some_path2")) ) .thenRespond( response() .withBody("some_body2") ) ) ); // and then - request log cleared verifyRequestMatches( mockServerClient.retrieveRecordedRequests(null), request(calculatePath("some_path2")) ); // and then - remaining expectations not cleared assertEquals( response() .withStatusCode(HttpStatusCode.OK_200.code()) .withBody("some_body2"), makeRequest( request() .withPath(calculatePath("some_path2")), headersToIgnore) ); assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()), makeRequest( request() .withPath(calculatePath("some_path1")), headersToIgnore) ); } @Test public void shouldClearExpectationsOnly() { // given - some expectations mockServerClient .when( request() .withPath(calculatePath("some_path1")) ) .respond( response() .withBody("some_body1") ); mockServerClient .when( request() .withPath(calculatePath("some_path2")) ) .respond( response() .withBody("some_body2") ); // and - some matching requests assertEquals( response() .withStatusCode(HttpStatusCode.OK_200.code()) .withBody("some_body1"), makeRequest( request() .withPath(calculatePath("some_path1")), headersToIgnore) ); assertEquals( response() .withStatusCode(HttpStatusCode.OK_200.code()) .withBody("some_body2"), makeRequest( request() .withPath(calculatePath("some_path2")), headersToIgnore) ); // when mockServerClient .clear( request() .withPath(calculatePath("some_path1")), MockServerClient.TYPE.EXPECTATION ); // then - expectations cleared assertThat( mockServerClient.retrieveExistingExpectations(null), arrayContaining( expectation( request() .withPath(calculatePath("some_path2")) ) .thenRespond( response() .withBody("some_body2") ) ) ); // and then - request log not cleared verifyRequestMatches( mockServerClient.retrieveRecordedRequests(null), request(calculatePath("some_path1")), request(calculatePath("some_path2")) ); } @Test public void shouldClearLogsOnly() { // given - some expectations mockServerClient .when( request() .withPath(calculatePath("some_path1")) ) .respond( response() .withBody("some_body1") ); mockServerClient .when( request() .withPath(calculatePath("some_path2")) ) .respond( response() .withBody("some_body2") ); // and - some matching requests assertEquals( response() .withStatusCode(HttpStatusCode.OK_200.code()) .withBody("some_body1"), makeRequest( request() .withPath(calculatePath("some_path1")), headersToIgnore) ); assertEquals( response() .withStatusCode(HttpStatusCode.OK_200.code()) .withBody("some_body2"), makeRequest( request() .withPath(calculatePath("some_path2")), headersToIgnore) ); // when mockServerClient .clear( request() .withPath(calculatePath("some_path1")), MockServerClient.TYPE.LOG ); // then - expectations cleared assertThat( mockServerClient.retrieveExistingExpectations(null), arrayContaining( expectation( request() .withPath(calculatePath("some_path1")) ) .thenRespond( response() .withBody("some_body1") ), expectation( request() .withPath(calculatePath("some_path2")) ) .thenRespond( response() .withBody("some_body2") ) ) ); // and then - request log cleared verifyRequestMatches( mockServerClient.retrieveRecordedRequests(null), request(calculatePath("some_path2")) ); } @Test public void shouldClearAllExpectationsWithNull() { // given mockServerClient .when( request() .withPath(calculatePath("some_path1")) ) .respond( response() .withBody("some_body1") ); mockServerClient .when( request() .withPath(calculatePath("some_path2")) ) .respond( response() .withBody("some_body2") ); assertEquals( response() .withStatusCode(HttpStatusCode.OK_200.code()) .withBody("some_body2"), makeRequest( request() .withPath(calculatePath("some_path2")), headersToIgnore) ); // when mockServerClient.clear(null); // then assertThat(mockServerClient.retrieveExistingExpectations(null), emptyArray()); assertThat(mockServerClient.retrieveRecordedRequests(null), emptyArray()); } @Test public void shouldClearAllExpectationsWithEmptyRequest() { // given mockServerClient .when( request() .withPath(calculatePath("some_path1")) ) .respond( response() .withBody("some_body1") ); mockServerClient .when( request() .withPath(calculatePath("some_path2")) ) .respond( response() .withBody("some_body2") ); assertEquals( response() .withStatusCode(HttpStatusCode.OK_200.code()) .withBody("some_body2"), makeRequest( request() .withPath(calculatePath("some_path2")), headersToIgnore) ); // when mockServerClient.clear(request()); // then assertThat(mockServerClient.retrieveExistingExpectations(null), emptyArray()); assertThat(mockServerClient.retrieveRecordedRequests(null), emptyArray()); } @Test public void shouldClearExpectationsWithXPathBody() { // given mockServerClient .when( request() .withBody(xpath("/bookstore/book[year=2005]/price")) ) .respond( response() .withBody("some_body1") ); mockServerClient .when( request() .withBody(xpath("/bookstore/book[year=2006]/price")) ) .respond( response() .withBody("some_body2") ); // and StringBody xmlBody = new StringBody("" + "<?xml version=\"1.0\" encoding=\"ISO-8859-1\"?>" + System.getProperty("line.separator") + "<bookstore>" + System.getProperty("line.separator") + " <book category=\"COOKING\">" + System.getProperty("line.separator") + " <title lang=\"en\">Everyday Italian</title>" + System.getProperty("line.separator") + " <author>Giada De Laurentiis</author>" + System.getProperty("line.separator") + " <year>2005</year>" + System.getProperty("line.separator") + " <price>30.00</price>" + System.getProperty("line.separator") + " </book>" + System.getProperty("line.separator") + " <book category=\"CHILDREN\">" + System.getProperty("line.separator") + " <title lang=\"en\">Harry Potter</title>" + System.getProperty("line.separator") + " <author>J K. Rowling</author>" + System.getProperty("line.separator") + " <year>2006</year>" + System.getProperty("line.separator") + " <price>29.99</price>" + System.getProperty("line.separator") + " </book>" + System.getProperty("line.separator") + " <book category=\"WEB\">" + System.getProperty("line.separator") + " <title lang=\"en\">Learning XML</title>" + System.getProperty("line.separator") + " <author>Erik T. Ray</author>" + System.getProperty("line.separator") + " <year>2003</year>" + System.getProperty("line.separator") + " <price>31.95</price>" + System.getProperty("line.separator") + " </book>" + System.getProperty("line.separator") + "</bookstore>"); // then assertEquals( response() .withStatusCode(HttpStatusCode.OK_200.code()) .withBody("some_body1"), makeRequest( request() .withBody(xmlBody), headersToIgnore) ); // when mockServerClient .clear( request() .withBody(xpath("/bookstore/book[year=2005]/price")) ); // then assertThat( mockServerClient.retrieveExistingExpectations(null), arrayContaining( expectation( request() .withBody(xpath("/bookstore/book[year=2006]/price")) ) .thenRespond( response() .withBody("some_body2") ) ) ); // - in http assertEquals( response() .withStatusCode(HttpStatusCode.OK_200.code()) .withBody("some_body2"), makeRequest( request() .withBody(xmlBody), headersToIgnore) ); // - in https assertEquals( response() .withStatusCode(HttpStatusCode.OK_200.code()) .withBody("some_body2"), makeRequest( request() .withSecure(true) .withBody(xmlBody), headersToIgnore) ); } @Test public void shouldClearExpectationsWithJsonSchemaBody() { // given JsonSchemaBody jsonSchemaBodyOne = jsonSchema("{" + System.getProperty("line.separator") + " \"$schema\": \"http://json-schema.org/draft-04/schema#\"," + System.getProperty("line.separator") + " \"title\": \"Product\"," + System.getProperty("line.separator") + " \"description\": \"A product from Acme's catalog\"," + System.getProperty("line.separator") + " \"type\": \"object\"," + System.getProperty("line.separator") + " \"properties\": {" + System.getProperty("line.separator") + " \"id\": {" + System.getProperty("line.separator") + " \"description\": \"The unique identifier for a product\"," + System.getProperty("line.separator") + " \"type\": \"integer\"" + System.getProperty("line.separator") + " }," + System.getProperty("line.separator") + " \"name\": {" + System.getProperty("line.separator") + " \"description\": \"Name of the product\"," + System.getProperty("line.separator") + " \"type\": \"string\"" + System.getProperty("line.separator") + " }," + System.getProperty("line.separator") + " \"price\": {" + System.getProperty("line.separator") + " \"type\": \"number\"," + System.getProperty("line.separator") + " \"minimum\": 0," + System.getProperty("line.separator") + " \"exclusiveMinimum\": true" + System.getProperty("line.separator") + " }," + System.getProperty("line.separator") + " \"tags\": {" + System.getProperty("line.separator") + " \"type\": \"array\"," + System.getProperty("line.separator") + " \"items\": {" + System.getProperty("line.separator") + " \"type\": \"string\"" + System.getProperty("line.separator") + " }," + System.getProperty("line.separator") + " \"minItems\": 1," + System.getProperty("line.separator") + " \"uniqueItems\": true" + System.getProperty("line.separator") + " }" + System.getProperty("line.separator") + " }," + System.getProperty("line.separator") + " \"required\": [\"id\", \"name\", \"price\"]" + System.getProperty("line.separator") + "}"); JsonSchemaBody jsonSchemaBodyTwo = jsonSchema("{" + System.getProperty("line.separator") + " \"$schema\": \"http://json-schema.org/draft-04/schema#\"," + System.getProperty("line.separator") + " \"title\": \"Product\"," + System.getProperty("line.separator") + " \"description\": \"A product from Acme's catalog\"," + System.getProperty("line.separator") + " \"type\": \"object\"," + System.getProperty("line.separator") + " \"properties\": {" + System.getProperty("line.separator") + " \"id\": {" + System.getProperty("line.separator") + " \"description\": \"The unique identifier for a product\"," + System.getProperty("line.separator") + " \"type\": \"integer\"" + System.getProperty("line.separator") + " }," + System.getProperty("line.separator") + " \"name\": {" + System.getProperty("line.separator") + " \"description\": \"Name of the product\"," + System.getProperty("line.separator") + " \"type\": \"string\"" + System.getProperty("line.separator") + " }," + System.getProperty("line.separator") + " \"price\": {" + System.getProperty("line.separator") + " \"type\": \"number\"," + System.getProperty("line.separator") + " \"minimum\": 10," + System.getProperty("line.separator") + " \"exclusiveMinimum\": true" + System.getProperty("line.separator") + " }," + System.getProperty("line.separator") + " \"tags\": {" + System.getProperty("line.separator") + " \"type\": \"array\"," + System.getProperty("line.separator") + " \"items\": {" + System.getProperty("line.separator") + " \"type\": \"string\"" + System.getProperty("line.separator") + " }," + System.getProperty("line.separator") + " \"minItems\": 1," + System.getProperty("line.separator") + " \"uniqueItems\": true" + System.getProperty("line.separator") + " }" + System.getProperty("line.separator") + " }," + System.getProperty("line.separator") + " \"required\": [\"id\", \"name\", \"price\"]" + System.getProperty("line.separator") + "}"); mockServerClient .when( request() .withBody(jsonSchemaBodyOne) ) .respond( response() .withBody("some_body1") ); mockServerClient .when( request() .withBody(jsonSchemaBodyTwo) ) .respond( response() .withBody("some_body2") ); // then assertEquals( response() .withStatusCode(HttpStatusCode.OK_200.code()) .withBody("some_body1"), makeRequest( request() .withBody("{" + System.getProperty("line.separator") + " \"id\": 1," + System.getProperty("line.separator") + " \"name\": \"A green door\"," + System.getProperty("line.separator") + " \"price\": 12.50," + System.getProperty("line.separator") + " \"tags\": [\"home\", \"green\"]" + System.getProperty("line.separator") + "}"), headersToIgnore) ); // when mockServerClient .clear( request() .withBody(jsonSchemaBodyOne) ); // then assertThat( mockServerClient.retrieveExistingExpectations(null), arrayContaining( expectation( request() .withBody(jsonSchemaBodyTwo) ) .thenRespond( response() .withBody("some_body2") ) ) ); // - in http assertEquals( response() .withStatusCode(HttpStatusCode.OK_200.code()) .withBody("some_body2"), makeRequest( request() .withBody("{" + System.getProperty("line.separator") + " \"id\": 1," + System.getProperty("line.separator") + " \"name\": \"A green door\"," + System.getProperty("line.separator") + " \"price\": 12.50," + System.getProperty("line.separator") + " \"tags\": [\"home\", \"green\"]" + System.getProperty("line.separator") + "}"), headersToIgnore) ); // - in https assertEquals( response() .withStatusCode(HttpStatusCode.OK_200.code()) .withBody("some_body2"), makeRequest( request() .withSecure(true) .withBody("{" + System.getProperty("line.separator") + " \"id\": 1," + System.getProperty("line.separator") + " \"name\": \"A green door\"," + System.getProperty("line.separator") + " \"price\": 12.50," + System.getProperty("line.separator") + " \"tags\": [\"home\", \"green\"]" + System.getProperty("line.separator") + "}"), headersToIgnore) ); } @Test public void shouldClearExpectationsWithParameterBody() { // given mockServerClient .when( request() .withBody(params(param("bodyParameterNameOne", "bodyParameterValueOne"))) ) .respond( response() .withBody("some_body1") ); mockServerClient .when( request() .withBody(params(param("bodyParameterNameTwo", "bodyParameterValueTwo"))) ) .respond( response() .withBody("some_body2") ); // then assertEquals( response() .withStatusCode(HttpStatusCode.OK_200.code()) .withBody("some_body1"), makeRequest( request() .withBody(params(param("bodyParameterName.*", "bodyParameterValue.*"))), headersToIgnore) ); // when mockServerClient .clear( request() .withBody(params(param("bodyParameterNameOne", "bodyParameterValueOne"))) ); // then assertThat( mockServerClient.retrieveExistingExpectations(null), arrayContaining( expectation( request() .withBody(params(param("bodyParameterNameTwo", "bodyParameterValueTwo"))) ) .thenRespond( response() .withBody("some_body2") ) ) ); // - in http assertEquals( response() .withStatusCode(HttpStatusCode.OK_200.code()) .withBody("some_body2"), makeRequest( request() .withBody(params(param("bodyParameterName.*", "bodyParameterValue.*"))), headersToIgnore) ); // - in https assertEquals( response() .withStatusCode(HttpStatusCode.OK_200.code()) .withBody("some_body2"), makeRequest( request() .withSecure(true) .withBody(params(param("bodyParameterName.*", "bodyParameterValue.*"))), headersToIgnore) ); } @Test public void shouldReset() { // given mockServerClient .when( request() .withPath(calculatePath("some_path1")) ) .respond( response() .withBody("some_body1") ); mockServerClient .when( request() .withPath(calculatePath("some_path2")) ) .respond( response() .withBody("some_body2") ); // when mockServerClient.reset(); // then // - in http assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()), makeRequest( request() .withPath(calculatePath("some_path1")), headersToIgnore) ); assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()), makeRequest( request() .withPath(calculatePath("some_path2")), headersToIgnore) ); // - in https assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()), makeRequest( request() .withSecure(true) .withPath(calculatePath("some_path1")), headersToIgnore) ); assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()), makeRequest( request() .withSecure(true) .withPath(calculatePath("some_path2")), headersToIgnore) ); } @Test public void shouldEnsureThatRequestDelaysDoNotAffectOtherRequests() throws Exception { mockServerClient .when( request("/slow") ) .respond( response("super slow") .withDelay(new Delay(TimeUnit.SECONDS, 8)) ); mockServerClient .when( request("/fast") ) .respond( response("quite fast") ); ExecutorService executorService = Executors.newFixedThreadPool(2); Future<Long> slowFuture = executorService.submit(new Callable<Long>() { @Override public Long call() throws Exception { long start = System.currentTimeMillis(); makeRequest(request("/slow")); return System.currentTimeMillis() - start; } }); // Let fast request come to the server slightly after slow request Uninterruptibles.sleepUninterruptibly(1, TimeUnit.SECONDS); Future<Long> fastFuture = executorService.submit(new Callable<Long>() { @Override public Long call() throws Exception { long start = System.currentTimeMillis(); makeRequest(request("/fast")); return System.currentTimeMillis() - start; } }); Long slowRequestElapsedMillis = slowFuture.get(); Long fastRequestElapsedMillis = fastFuture.get(); assertThat("Slow request takes less than expected", slowRequestElapsedMillis, is(greaterThan(7 * 1000L))); assertThat("Fast request takes longer than expected", fastRequestElapsedMillis, is(lessThan(3 * 1000L))); } protected void verifyRequestMatches(HttpRequest[] httpRequests, HttpRequest... httpRequestMatchers) { if (httpRequests.length != httpRequestMatchers.length) { throw new AssertionError("Number of request matchers does not match number of requests, expected:<" + httpRequestMatchers.length + "> but was:<" + httpRequests.length + ">"); } else { for (int i = 0; i < httpRequestMatchers.length; i++) { if (!new HttpRequestMatcher(httpRequestMatchers[i]).matches(httpRequests[i])) { throw new AssertionError("Request does not match request matcher, expected:<" + httpRequestMatchers[i] + "> but was:<" + httpRequests[i] + ">"); } } } } protected HttpResponse makeRequest(HttpRequest httpRequest) { return makeRequest(httpRequest, Collections.<String>emptySet()); } protected HttpResponse makeRequest(HttpRequest httpRequest, Collection<String> headersToIgnore) { int attemptsRemaining = 10; while (attemptsRemaining > 0) { try { boolean isSsl = httpRequest.isSecure() != null && httpRequest.isSecure(); int port = (isSsl ? getMockServerSecurePort() : getMockServerPort()); HttpResponse httpResponse = httpClient.sendRequest(outboundRequest("localhost", port, servletContext, httpRequest)); List<Header> headers = new ArrayList<Header>(); for (Header header : httpResponse.getHeaders()) { if (!headersToIgnore.contains(header.getName().getValue().toLowerCase())) { if (header.getName().getValue().equalsIgnoreCase(HttpHeaders.CONTENT_TYPE)) { // this fixes Tomcat which removes the space between // media type and charset in the Content-Type header for (NottableString value : new ArrayList<NottableString>(header.getValues())) { header.getValues().clear(); header.addValues(value.getValue().replace(";charset", "; charset")); } } headers.add(header); } } httpResponse.withHeaders(headers); return httpResponse; } catch (SocketConnectionException caught) { attemptsRemaining--; logger.info("Retrying connection to mock server, attempts remaining: " + attemptsRemaining); try { TimeUnit.MILLISECONDS.sleep(50); } catch (InterruptedException e) { // do nothing } } } throw new RuntimeException("Failed to send request:" + System.getProperty("line.separator") + httpRequest); } }
smartpcr/mockserver
mockserver-integration-testing/src/main/java/org/mockserver/integration/server/AbstractClientServerIntegrationTest.java
918
package org.mockserver.integration.server; import com.google.common.base.Charsets; import com.google.common.base.Strings; import com.google.common.net.MediaType; import com.google.common.util.concurrent.Uninterruptibles; import org.apache.commons.io.IOUtils; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Ignore; import org.junit.Test; import org.mockserver.client.netty.NettyHttpClient; import org.mockserver.client.netty.SocketConnectionException; import org.mockserver.client.serialization.ExpectationSerializer; import org.mockserver.client.server.MockServerClient; import org.mockserver.echo.http.EchoServer; import org.mockserver.matchers.HttpRequestMatcher; import org.mockserver.matchers.MatchType; import org.mockserver.matchers.TimeToLive; import org.mockserver.matchers.Times; import org.mockserver.mock.Expectation; import org.mockserver.model.*; import org.mockserver.socket.PortFactory; import org.mockserver.verify.VerificationTimes; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.IOException; import java.net.InetSocketAddress; import java.util.*; import java.util.concurrent.*; import static io.netty.handler.codec.http.HttpHeaderNames.*; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.*; import static org.hamcrest.core.Is.is; import static org.hamcrest.core.StringStartsWith.startsWith; import static org.hamcrest.number.OrderingComparison.greaterThan; import static org.junit.Assert.assertEquals; import static org.junit.Assert.fail; import static org.mockserver.character.Character.NEW_LINE; import static org.mockserver.matchers.Times.exactly; import static org.mockserver.matchers.Times.once; import static org.mockserver.matchers.Times.unlimited; import static org.mockserver.model.BinaryBody.binary; import static org.mockserver.model.Cookie.cookie; import static org.mockserver.model.Header.header; import static org.mockserver.model.HttpClassCallback.callback; import static org.mockserver.model.HttpForward.forward; import static org.mockserver.model.HttpRequest.request; import static org.mockserver.model.HttpResponse.notFoundResponse; import static org.mockserver.model.HttpResponse.response; import static org.mockserver.model.HttpStatusCode.NOT_FOUND_404; import static org.mockserver.model.HttpStatusCode.OK_200; import static org.mockserver.model.JsonBody.json; import static org.mockserver.model.JsonSchemaBody.jsonSchema; import static org.mockserver.model.NottableString.not; import static org.mockserver.model.NottableString.string; import static org.mockserver.model.Parameter.param; import static org.mockserver.model.ParameterBody.params; import static org.mockserver.model.RegexBody.regex; import static org.mockserver.model.StringBody.exact; import static org.mockserver.model.XPathBody.xpath; import static org.mockserver.model.XmlBody.xml; import static org.mockserver.model.XmlSchemaBody.xmlSchema; /** * @author jamesdbloom */ public abstract class AbstractClientServerIntegrationTest { protected static final String TEXT_PLAIN = MediaType.create("text", "plain").toString(); protected static MockServerClient mockServerClient; protected static String servletContext = ""; private final Logger logger = LoggerFactory.getLogger(this.getClass()); protected List<String> headersToIgnore = Arrays.asList( "server", "expires", "date", "host", "connection", "user-agent", "content-length", "accept-encoding", "transfer-encoding", "access-control-allow-origin", "access-control-allow-methods", "access-control-allow-headers", "access-control-expose-headers", "access-control-max-age", "x-cors" ); private NettyHttpClient httpClient = new NettyHttpClient(); public static Expectation expectation(HttpRequest httpRequest) { return new Expectation(httpRequest, Times.unlimited(), TimeToLive.unlimited()); } public abstract int getMockServerPort(); public abstract int getMockServerSecurePort(); public abstract int getTestServerPort(); @BeforeClass public static void resetServletContext() throws Exception { servletContext = ""; } @Before public void resetServer() { mockServerClient.reset(); } @Test public void shouldForwardRequestInHTTP() { // when mockServerClient .when( request() .withPath(calculatePath("echo")) ) .forward( forward() .withHost("127.0.0.1") .withPort(getTestServerPort()) ); // then // - in http assertEquals( response() .withStatusCode(OK_200.code()) .withHeaders( header("x-test", "test_headers_and_body") ) .withBody("an_example_body_http"), makeRequest( request() .withPath(calculatePath("echo")) .withMethod("POST") .withHeaders( header("x-test", "test_headers_and_body") ) .withBody("an_example_body_http"), headersToIgnore) ); // - in https assertEquals( response() .withStatusCode(OK_200.code()) .withHeaders( header("x-test", "test_headers_and_body") ) .withBody("an_example_body_https"), makeRequest( request() .withSecure(true) .withPath(calculatePath("echo")) .withMethod("POST") .withHeaders( header("x-test", "test_headers_and_body") ) .withBody("an_example_body_https"), headersToIgnore) ); } @Test public void shouldForwardRequestInHTTPS() { int testServerHttpsPort = PortFactory.findFreePort(); EchoServer secureEchoServer = new EchoServer(testServerHttpsPort, true); try { // when mockServerClient .when( request() .withPath(calculatePath("echo")) ) .forward( forward() .withHost("127.0.0.1") .withPort(testServerHttpsPort) .withScheme(HttpForward.Scheme.HTTPS) ); // then // - in http assertEquals( response() .withStatusCode(OK_200.code()) .withHeaders( header("x-test", "test_headers_and_body") ) .withBody("an_example_body_http"), makeRequest( request() .withPath(calculatePath("echo")) .withMethod("POST") .withHeaders( header("x-test", "test_headers_and_body") ) .withBody("an_example_body_http"), headersToIgnore) ); // - in https assertEquals( response() .withStatusCode(OK_200.code()) .withHeaders( header("x-test", "test_headers_and_body") ) .withBody("an_example_body_https"), makeRequest( request() .withSecure(true) .withPath(calculatePath("echo")) .withMethod("POST") .withHeaders( header("x-test", "test_headers_and_body") ) .withBody("an_example_body_https"), headersToIgnore) ); } finally { secureEchoServer.stop(); } } @Test public void shouldAllowSimultaneousForwardAndResponseExpectations() { // when mockServerClient .when( request() .withPath(calculatePath("echo")), once() ) .forward( forward() .withHost("127.0.0.1") .withPort(getTestServerPort()) ); mockServerClient .when( request() .withPath(calculatePath("test_headers_and_body")), once() ) .respond( response() .withBody("some_body") ); // then // - forward assertEquals( response() .withStatusCode(OK_200.code()) .withHeaders( header("x-test", "test_headers_and_body") ) .withBody("an_example_body"), makeRequest( request() .withPath(calculatePath("echo")) .withMethod("POST") .withHeaders( header("x-test", "test_headers_and_body") ) .withBody("an_example_body"), headersToIgnore) ); // - respond assertEquals( response() .withStatusCode(OK_200.code()) .withBody("some_body"), makeRequest( request() .withPath(calculatePath("test_headers_and_body")), headersToIgnore) ); // - no response or forward assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()), makeRequest( request() .withPath(calculatePath("test_headers_and_body")), headersToIgnore) ); } @Test public void shouldCallbackToSpecifiedClassWithPrecannedResponse() { // when mockServerClient .when( request() .withPath(calculatePath("callback")) ) .callback( callback() .withCallbackClass("org.mockserver.integration.callback.PrecannedTestExpectationCallback") ); // then // - in http assertEquals( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withHeaders( header("x-callback", "test_callback_header") ) .withBody("a_callback_response"), makeRequest( request() .withPath(calculatePath("callback")) .withMethod("POST") .withHeaders( header("x-test", "test_headers_and_body") ) .withBody("an_example_body_http"), headersToIgnore ) ); // - in https assertEquals( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withHeaders( header("x-callback", "test_callback_header") ) .withBody("a_callback_response"), makeRequest( request() .withSecure(true) .withPath(calculatePath("callback")) .withMethod("POST") .withHeaders( header("x-test", "test_headers_and_body") ) .withBody("an_example_body_https"), headersToIgnore ) ); } @Test public void shouldReturnResponseWithOnlyBody() { // when mockServerClient.when(request()).respond(response().withBody("some_body")); // then // - in http assertEquals( response() .withStatusCode(OK_200.code()) .withBody("some_body"), makeRequest( request() .withPath(calculatePath("")), headersToIgnore) ); // - in https assertEquals( response() .withStatusCode(OK_200.code()) .withBody("some_body"), makeRequest( request() .withSecure(true) .withPath(calculatePath("")), headersToIgnore) ); } @Test public void shouldSupportBatchedExpectations() { // when new NettyHttpClient().sendRequest( request() .withMethod("PUT") .withHeader(HOST.toString(), "localhost:" + getMockServerPort()) .withPath(addContextToPath("/expectation")) .withBody("" + "[" + new ExpectationSerializer() .serialize( new Expectation(request("/path_one"), once(), TimeToLive.unlimited()) .thenRespond(response().withBody("some_body_one")) ) + "," + new ExpectationSerializer() .serialize( new Expectation(request("/path_two"), once(), TimeToLive.unlimited()) .thenRespond(response().withBody("some_body_two")) ) + "," + new ExpectationSerializer() .serialize( new Expectation(request("/path_three"), once(), TimeToLive.unlimited()) .thenRespond(response().withBody("some_body_three")) ) + "]" ) ); // then assertEquals( response() .withStatusCode(OK_200.code()) .withBody("some_body_one"), makeRequest( request() .withPath(calculatePath("/path_one")), headersToIgnore) ); assertEquals( response() .withStatusCode(OK_200.code()) .withBody("some_body_two"), makeRequest( request() .withPath(calculatePath("/path_two")), headersToIgnore) ); assertEquals( response() .withStatusCode(OK_200.code()) .withBody("some_body_three"), makeRequest( request() .withPath(calculatePath("/path_three")), headersToIgnore) ); } @Test public void shouldReturnResponseForRequestInSsl() { // when mockServerClient.when(request().withSecure(true)).respond(response().withBody("some_body")); // then // - in http assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()), makeRequest( request() .withPath(calculatePath("")), headersToIgnore) ); // - in https assertEquals( response() .withStatusCode(OK_200.code()) .withBody("some_body"), makeRequest( request() .withSecure(true) .withPath(calculatePath("")), headersToIgnore) ); } @Test public void shouldReturnResponseForRequestNotInSsl() { // when mockServerClient.when(request().withSecure(false)).respond(response().withBody("some_body")); // then // - in http assertEquals( response() .withStatusCode(OK_200.code()) .withBody("some_body"), makeRequest( request() .withPath(calculatePath("")), headersToIgnore) ); // - in https assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()), makeRequest( request() .withSecure(true) .withPath(calculatePath("")), headersToIgnore) ); } @Test public void shouldReturnMatchRequestWithBodyInUTF16() { // when String body = "我说中国话"; mockServerClient.when(request().withBody(body, Charsets.UTF_16)).respond(response().withBody(body, Charsets.UTF_8)); // then // - in http assertEquals( response() .withHeader(CONTENT_TYPE.toString(), MediaType.create("text", "plain").withCharset(Charsets.UTF_8).toString()) .withStatusCode(OK_200.code()) .withBody(body), makeRequest( request() .withPath(calculatePath("")) .withBody(body, Charsets.UTF_16), headersToIgnore) ); // - in https assertEquals( response() .withHeader(CONTENT_TYPE.toString(), MediaType.create("text", "plain").withCharset(Charsets.UTF_8).toString()) .withStatusCode(OK_200.code()) .withBody(body), makeRequest( request() .withSecure(true) .withPath(calculatePath("")) .withBody(body, Charsets.UTF_16), headersToIgnore) ); } @Test public void shouldReturnMatchRequestWithBodyInUTF16WithContentTypeHeader() { // when String body = "我说中国话"; mockServerClient .when( request() .withHeader(CONTENT_TYPE.toString(), MediaType.create("text", "plain").withCharset(Charsets.UTF_8).toString()) .withBody(body) ) .respond( response() .withBody(body, Charsets.UTF_8) ); // then // - in http assertEquals( response() .withHeader(CONTENT_TYPE.toString(), MediaType.create("text", "plain").withCharset(Charsets.UTF_8).toString()) .withStatusCode(OK_200.code()) .withBody(body), makeRequest( request() .withHeader(CONTENT_TYPE.toString(), MediaType.create("text", "plain").withCharset(Charsets.UTF_8).toString()) .withPath(calculatePath("")) .withBody(body), headersToIgnore) ); // - in https assertEquals( response() .withHeader(CONTENT_TYPE.toString(), MediaType.create("text", "plain").withCharset(Charsets.UTF_8).toString()) .withStatusCode(OK_200.code()) .withBody(body), makeRequest( request() .withHeader(CONTENT_TYPE.toString(), MediaType.create("text", "plain").withCharset(Charsets.UTF_8).toString()) .withSecure(true) .withPath(calculatePath("")) .withBody(body), headersToIgnore) ); } @Test public void shouldReturnResponseWithBodyInUTF8() { // when String body = "我说中国话"; mockServerClient.when(request()).respond(response().withBody(body, Charsets.UTF_16)); // then // - in http assertEquals( response() .withHeader(CONTENT_TYPE.toString(), MediaType.create("text", "plain").withCharset(Charsets.UTF_16).toString()) .withStatusCode(OK_200.code()) .withBody(body), makeRequest( request() .withPath(calculatePath("")), headersToIgnore) ); // - in https assertEquals( response() .withHeader(CONTENT_TYPE.toString(), MediaType.create("text", "plain").withCharset(Charsets.UTF_16).toString()) .withStatusCode(OK_200.code()) .withBody(body), makeRequest( request() .withSecure(true) .withPath(calculatePath("")), headersToIgnore) ); } @Test public void shouldReturnResponseWithBodyInUTF16WithContentTypeHeader() { // when String body = "我说中国话"; mockServerClient .when( request() ) .respond( response() .withHeader(CONTENT_TYPE.toString(), MediaType.create("text", "plain").withCharset(Charsets.UTF_8).toString()) .withBody(body) ); // then // - in http assertEquals( response() .withHeader(CONTENT_TYPE.toString(), MediaType.create("text", "plain").withCharset(Charsets.UTF_8).toString()) .withStatusCode(OK_200.code()) .withBody(body), makeRequest( request() .withPath(calculatePath("")), headersToIgnore) ); // - in https assertEquals( response() .withHeader(CONTENT_TYPE.toString(), MediaType.create("text", "plain").withCharset(Charsets.UTF_8).toString()) .withStatusCode(OK_200.code()) .withBody(body), makeRequest( request() .withSecure(true) .withPath(calculatePath("")), headersToIgnore) ); } @Test public void shouldReturnResponseWithOnlyStatusCode() { // when mockServerClient .when( request() .withMethod("POST") .withPath(calculatePath("some_path")) ) .respond( response() .withStatusCode(200) ); // then // - in http assertEquals( response() .withStatusCode(OK_200.code()), makeRequest( request() .withPath(calculatePath("some_path")) .withMethod("POST"), headersToIgnore) ); // - in https assertEquals( response() .withStatusCode(OK_200.code()), makeRequest( request() .withSecure(true) .withPath(calculatePath("some_path")) .withMethod("POST"), headersToIgnore) ); } @Test public void shouldReturnResponseByMatchingPath() { // when mockServerClient .when( request() .withPath(calculatePath("some_path1")) ) .respond( response() .withBody("some_body1") ); mockServerClient .when( request() .withPath(calculatePath("some_path2")) ) .respond( response() .withBody("some_body2") ); // then // - in http assertEquals( response() .withStatusCode(OK_200.code()) .withBody("some_body2"), makeRequest( request() .withPath(calculatePath("some_path2")), headersToIgnore) ); assertEquals( response() .withStatusCode(OK_200.code()) .withBody("some_body1"), makeRequest( request() .withPath(calculatePath("some_path1")), headersToIgnore) ); // - in https assertEquals( response() .withStatusCode(OK_200.code()) .withBody("some_body2"), makeRequest( request() .withSecure(true) .withPath(calculatePath("some_path2")), headersToIgnore) ); assertEquals( response() .withStatusCode(OK_200.code()) .withBody("some_body1"), makeRequest( request() .withSecure(true) .withPath(calculatePath("some_path1")), headersToIgnore) ); } @Test public void shouldReturnResponseByMatchingPathExactTimes() { // when mockServerClient .when( request() .withPath(calculatePath("some_path")), exactly(2) ) .respond( response() .withBody("some_body") ); // then // - in http assertEquals( response() .withStatusCode(OK_200.code()) .withBody("some_body"), makeRequest( request() .withPath(calculatePath("some_path")), headersToIgnore) ); // - in https assertEquals( response() .withStatusCode(OK_200.code()) .withBody("some_body"), makeRequest( request() .withSecure(true) .withPath(calculatePath("some_path")), headersToIgnore) ); // - in http assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()), makeRequest( request() .withPath(calculatePath("some_path")), headersToIgnore) ); // - in https assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()), makeRequest( request() .withSecure(true) .withPath(calculatePath("some_path")), headersToIgnore) ); } @Test public void shouldReturnResponseWhenTimeToLiveHasNotExpired() { // when mockServerClient .when( request().withPath(calculatePath("some_path")), exactly(2), TimeToLive.exactly(TimeUnit.HOURS, 1L) ) .respond( response().withBody("some_body") ); // then // - in http assertEquals( response() .withStatusCode(OK_200.code()) .withBody("some_body"), makeRequest( request() .withPath(calculatePath("some_path")), headersToIgnore) ); // - in https assertEquals( response() .withStatusCode(OK_200.code()) .withBody("some_body"), makeRequest( request() .withSecure(true) .withPath(calculatePath("some_path")), headersToIgnore) ); // - in http assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()), makeRequest( request() .withPath(calculatePath("some_path")), headersToIgnore) ); // - in https assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()), makeRequest( request() .withSecure(true) .withPath(calculatePath("some_path")), headersToIgnore) ); } @Test public void shouldReturnResponseByMatchingBodyWithXPath() { // when mockServerClient.when(request().withBody(xpath("/bookstore/book[price>30]/price")), exactly(2)).respond(response().withBody("some_body")); // then // - in http assertEquals( response() .withStatusCode(OK_200.code()) .withBody("some_body"), makeRequest( request() .withPath(calculatePath("some_path")) .withMethod("POST") .withBody(new StringBody("" + "<?xml version=\"1.0\" encoding=\"ISO-8859-1\"?>" + NEW_LINE + "<bookstore>" + NEW_LINE + " <book category=\"COOKING\">" + NEW_LINE + " <title lang=\"en\">Everyday Italian</title>" + NEW_LINE + " <author>Giada De Laurentiis</author>" + NEW_LINE + " <year>2005</year>" + NEW_LINE + " <price>30.00</price>" + NEW_LINE + " </book>" + NEW_LINE + " <book category=\"CHILDREN\">" + NEW_LINE + " <title lang=\"en\">Harry Potter</title>" + NEW_LINE + " <author>J K. Rowling</author>" + NEW_LINE + " <year>2005</year>" + NEW_LINE + " <price>29.99</price>" + NEW_LINE + " </book>" + NEW_LINE + " <book category=\"WEB\">" + NEW_LINE + " <title lang=\"en\">Learning XML</title>" + NEW_LINE + " <author>Erik T. Ray</author>" + NEW_LINE + " <year>2003</year>" + NEW_LINE + " <price>31.95</price>" + NEW_LINE + " </book>" + NEW_LINE + "</bookstore>")), headersToIgnore) ); // - in https assertEquals( response() .withStatusCode(OK_200.code()) .withBody("some_body"), makeRequest( request() .withSecure(true) .withPath(calculatePath("some_path")) .withMethod("POST") .withBody(new StringBody("" + "<?xml version=\"1.0\" encoding=\"ISO-8859-1\"?>" + NEW_LINE + "<bookstore>" + NEW_LINE + " <book category=\"COOKING\">" + NEW_LINE + " <title lang=\"en\">Everyday Italian</title>" + NEW_LINE + " <author>Giada De Laurentiis</author>" + NEW_LINE + " <year>2005</year>" + NEW_LINE + " <price>30.00</price>" + NEW_LINE + " </book>" + NEW_LINE + " <book category=\"CHILDREN\">" + NEW_LINE + " <title lang=\"en\">Harry Potter</title>" + NEW_LINE + " <author>J K. Rowling</author>" + NEW_LINE + " <year>2005</year>" + NEW_LINE + " <price>29.99</price>" + NEW_LINE + " </book>" + NEW_LINE + " <book category=\"WEB\">" + NEW_LINE + " <title lang=\"en\">Learning XML</title>" + NEW_LINE + " <author>Erik T. Ray</author>" + NEW_LINE + " <year>2003</year>" + NEW_LINE + " <price>31.95</price>" + NEW_LINE + " </book>" + NEW_LINE + "</bookstore>")), headersToIgnore) ); } @Test public void shouldReturnResponseByMatchingBodyWithXml() { // when mockServerClient.when(request().withBody(xml("" + "<bookstore>" + NEW_LINE + " <book nationality=\"ITALIAN\" category=\"COOKING\"><title lang=\"en\">Everyday Italian</title><author>Giada De Laurentiis</author><year>2005</year><price>30.00</price></book>" + NEW_LINE + "</bookstore>")), exactly(2)).respond(response().withBody("some_body")); // then // - in http assertEquals( response() .withStatusCode(OK_200.code()) .withBody("some_body"), makeRequest( request() .withPath(calculatePath("some_path")) .withMethod("POST") .withBody(new StringBody("" + "<?xml version=\"1.0\" encoding=\"ISO-8859-1\"?>" + NEW_LINE + "<bookstore>" + NEW_LINE + " <book category=\"COOKING\" nationality=\"ITALIAN\">" + NEW_LINE + " <title lang=\"en\">Everyday Italian</title>" + NEW_LINE + " <author>Giada De Laurentiis</author>" + NEW_LINE + " <year>2005</year>" + NEW_LINE + " <price>30.00</price>" + NEW_LINE + " </book>" + NEW_LINE + "</bookstore>")), headersToIgnore) ); // - in https assertEquals( response() .withStatusCode(OK_200.code()) .withBody("some_body"), makeRequest( request() .withSecure(true) .withPath(calculatePath("some_path")) .withMethod("POST") .withBody(new StringBody("" + "<?xml version=\"1.0\" encoding=\"ISO-8859-1\"?>" + NEW_LINE + "<bookstore>" + NEW_LINE + " <book category=\"COOKING\" nationality=\"ITALIAN\">" + NEW_LINE + " <title lang=\"en\">Everyday Italian</title>" + NEW_LINE + " <author>Giada De Laurentiis</author>" + NEW_LINE + " <year>2005</year>" + NEW_LINE + " <price>30.00</price>" + NEW_LINE + " </book>" + NEW_LINE + "</bookstore>")), headersToIgnore) ); } @Test public void shouldReturnResponseByMatchingBodyWithJson() { // when mockServerClient .when( request() .withBody(json("{" + NEW_LINE + " \"id\": 1," + NEW_LINE + " \"name\": \"A green door\"," + NEW_LINE + " \"price\": 12.50," + NEW_LINE + " \"tags\": [\"home\", \"green\"]" + NEW_LINE + "}")), exactly(2) ) .respond( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body") ); // then // - in http assertEquals( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body"), makeRequest( request() .withPath(calculatePath("some_path")) .withMethod("POST") .withBody("{" + NEW_LINE + " \"id\": 1," + NEW_LINE + " \"extra ignored field\": \"some value\"," + NEW_LINE + " \"name\": \"A green door\"," + NEW_LINE + " \"price\": 12.50," + NEW_LINE + " \"tags\": [\"home\", \"green\"]" + NEW_LINE + "}"), headersToIgnore) ); // - in https assertEquals( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body"), makeRequest( request() .withSecure(true) .withPath(calculatePath("some_path")) .withMethod("POST") .withBody("{" + NEW_LINE + " \"id\": 1," + NEW_LINE + " \"extra ignored array\": [\"one\", \"two\"]," + NEW_LINE + " \"name\": \"A green door\"," + NEW_LINE + " \"price\": 12.50," + NEW_LINE + " \"tags\": [\"home\", \"green\"]" + NEW_LINE + "}"), headersToIgnore) ); } @Test public void shouldReturnResponseByMatchingBodyWithJsonWithCharsetUTF8() { // when mockServerClient .when( request() .withBody(json("{" + NEW_LINE + " \"ταυτότητα\": 1," + NEW_LINE + " \"όνομα\": \"μια πράσινη πόρτα\"," + NEW_LINE + " \"τιμή\": 12.50," + NEW_LINE + " \"ετικέτες\": [\"σπίτι\", \"πράσινος\"]" + NEW_LINE + "}", Charsets.UTF_16, MatchType.ONLY_MATCHING_FIELDS)), exactly(2) ) .respond( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body") ); // then // - in http assertEquals( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body"), makeRequest( request() .withPath(calculatePath("some_path")) .withMethod("POST") .withBody(json("{" + NEW_LINE + " \"ταυτότητα\": 1," + NEW_LINE + " \"επιπλέον αγνοούνται τομέα\": \"κάποια αξία\"," + NEW_LINE + " \"όνομα\": \"μια πράσινη πόρτα\"," + NEW_LINE + " \"τιμή\": 12.50," + NEW_LINE + " \"ετικέτες\": [\"σπίτι\", \"πράσινος\"]" + NEW_LINE + "}", Charsets.UTF_16, MatchType.ONLY_MATCHING_FIELDS)), headersToIgnore) ); // - in https assertEquals( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body"), makeRequest( request() .withSecure(true) .withPath(calculatePath("some_path")) .withMethod("POST") .withBody(json("{" + NEW_LINE + " \"ταυτότητα\": 1," + NEW_LINE + " \"επιπλέον αγνοούνται σειρά\": [\"ένας\", \"δυο\"]," + NEW_LINE + " \"όνομα\": \"μια πράσινη πόρτα\"," + NEW_LINE + " \"τιμή\": 12.50," + NEW_LINE + " \"ετικέτες\": [\"σπίτι\", \"πράσινος\"]" + NEW_LINE + "}", Charsets.UTF_16, MatchType.ONLY_MATCHING_FIELDS)), headersToIgnore) ); } @Test public void shouldReturnResponseByMatchingBodyWithJsonWithContentTypeHeader() { // when mockServerClient .when( request() .withBody(json("{" + NEW_LINE + " \"ταυτότητα\": 1," + NEW_LINE + " \"όνομα\": \"μια πράσινη πόρτα\"," + NEW_LINE + " \"τιμή\": 12.50," + NEW_LINE + " \"ετικέτες\": [\"σπίτι\", \"πράσινος\"]" + NEW_LINE + "}", Charsets.UTF_16, MatchType.ONLY_MATCHING_FIELDS)), exactly(2) ) .respond( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body") ); // then // - in http assertEquals( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body"), makeRequest( request() .withHeader(CONTENT_TYPE.toString(), MediaType.create("text", "plain").withCharset(Charsets.UTF_16).toString()) .withPath(calculatePath("some_path")) .withMethod("POST") .withBody(json("{" + NEW_LINE + " \"ταυτότητα\": 1," + NEW_LINE + " \"επιπλέον αγνοούνται τομέα\": \"κάποια αξία\"," + NEW_LINE + " \"όνομα\": \"μια πράσινη πόρτα\"," + NEW_LINE + " \"τιμή\": 12.50," + NEW_LINE + " \"ετικέτες\": [\"σπίτι\", \"πράσινος\"]" + NEW_LINE + "}")), headersToIgnore) ); // - in https assertEquals( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body"), makeRequest( request() .withSecure(true) .withHeader(CONTENT_TYPE.toString(), MediaType.create("text", "plain").withCharset(Charsets.UTF_16).toString()) .withPath(calculatePath("some_path")) .withMethod("POST") .withBody(json("{" + NEW_LINE + " \"ταυτότητα\": 1," + NEW_LINE + " \"επιπλέον αγνοούνται σειρά\": [\"ένας\", \"δυο\"]," + NEW_LINE + " \"όνομα\": \"μια πράσινη πόρτα\"," + NEW_LINE + " \"τιμή\": 12.50," + NEW_LINE + " \"ετικέτες\": [\"σπίτι\", \"πράσινος\"]" + NEW_LINE + "}")), headersToIgnore) ); } @Test public void shouldReturnResponseByMatchingBodyWithJsonWithMatchType() { // when mockServerClient .when( request() .withBody(json("{" + NEW_LINE + " \"id\": 1," + NEW_LINE + " \"name\": \"A green door\"," + NEW_LINE + " \"price\": 12.50," + NEW_LINE + " \"tags\": [\"home\", \"green\"]" + NEW_LINE + "}", MatchType.ONLY_MATCHING_FIELDS)), exactly(2) ) .respond( response() .withBody("some_body") ); // then // - in http assertEquals( response("some_body"), makeRequest( request() .withPath(calculatePath("some_path")) .withMethod("POST") .withBody("{" + NEW_LINE + " \"id\": 1," + NEW_LINE + " \"extra field\": \"some value\"," + NEW_LINE + " \"name\": \"A green door\"," + NEW_LINE + " \"price\": 12.50," + NEW_LINE + " \"tags\": [\"home\", \"green\"]" + NEW_LINE + "}"), headersToIgnore) ); // - in https assertEquals( response("some_body"), makeRequest( request() .withSecure(true) .withPath(calculatePath("some_path")) .withMethod("POST") .withBody("{" + NEW_LINE + " \"id\": 1," + NEW_LINE + " \"extra field\": \"some value\"," + NEW_LINE + " \"name\": \"A green door\"," + NEW_LINE + " \"price\": 12.50," + NEW_LINE + " \"tags\": [\"home\", \"green\"]" + NEW_LINE + "}"), headersToIgnore) ); } @Test public void shouldReturnResponseByMatchingBodyWithJsonSchema() { // when mockServerClient.when(request().withBody(jsonSchema("{" + NEW_LINE + " \"$schema\": \"http://json-schema.org/draft-04/schema#\"," + NEW_LINE + " \"title\": \"Product\"," + NEW_LINE + " \"description\": \"A product from Acme's catalog\"," + NEW_LINE + " \"type\": \"object\"," + NEW_LINE + " \"properties\": {" + NEW_LINE + " \"id\": {" + NEW_LINE + " \"description\": \"The unique identifier for a product\"," + NEW_LINE + " \"type\": \"integer\"" + NEW_LINE + " }," + NEW_LINE + " \"name\": {" + NEW_LINE + " \"description\": \"Name of the product\"," + NEW_LINE + " \"type\": \"string\"" + NEW_LINE + " }," + NEW_LINE + " \"price\": {" + NEW_LINE + " \"type\": \"number\"," + NEW_LINE + " \"minimum\": 0," + NEW_LINE + " \"exclusiveMinimum\": true" + NEW_LINE + " }," + NEW_LINE + " \"tags\": {" + NEW_LINE + " \"type\": \"array\"," + NEW_LINE + " \"items\": {" + NEW_LINE + " \"type\": \"string\"" + NEW_LINE + " }," + NEW_LINE + " \"minItems\": 1," + NEW_LINE + " \"uniqueItems\": true" + NEW_LINE + " }" + NEW_LINE + " }," + NEW_LINE + " \"required\": [\"id\", \"name\", \"price\"]" + NEW_LINE + "}")), exactly(2)).respond(response().withBody("some_body")); // then // - in http assertEquals( response() .withStatusCode(OK_200.code()) .withBody("some_body"), makeRequest( request() .withPath(calculatePath("some_path")) .withMethod("POST") .withBody("{" + NEW_LINE + " \"id\": 1," + NEW_LINE + " \"name\": \"A green door\"," + NEW_LINE + " \"price\": 12.50," + NEW_LINE + " \"tags\": [\"home\", \"green\"]" + NEW_LINE + "}"), headersToIgnore) ); // - in https assertEquals( response() .withStatusCode(OK_200.code()) .withBody("some_body"), makeRequest( request() .withSecure(true) .withPath(calculatePath("some_path")) .withMethod("POST") .withBody("{" + NEW_LINE + " \"id\": 1," + NEW_LINE + " \"name\": \"A green door\"," + NEW_LINE + " \"price\": 12.50," + NEW_LINE + " \"tags\": [\"home\", \"green\"]" + NEW_LINE + "}"), headersToIgnore) ); } @Test public void shouldReturnResponseByMatchingBodyWithXmlSchema() { // when mockServerClient.when(request() .withBody( xmlSchema("<?xml version=\"1.0\" encoding=\"UTF-8\"?>" + NEW_LINE + "<xs:schema xmlns:xs=\"http://www.w3.org/2001/XMLSchema\" elementFormDefault=\"qualified\" attributeFormDefault=\"unqualified\">" + NEW_LINE + " <!-- XML Schema Generated from XML Document on Wed Jun 28 2017 21:52:45 GMT+0100 (BST) -->" + NEW_LINE + " <!-- with XmlGrid.net Free Online Service http://xmlgrid.net -->" + NEW_LINE + " <xs:element name=\"notes\">" + NEW_LINE + " <xs:complexType>" + NEW_LINE + " <xs:sequence>" + NEW_LINE + " <xs:element name=\"note\" maxOccurs=\"unbounded\">" + NEW_LINE + " <xs:complexType>" + NEW_LINE + " <xs:sequence>" + NEW_LINE + " <xs:element name=\"to\" minOccurs=\"1\" maxOccurs=\"1\" type=\"xs:string\"></xs:element>" + NEW_LINE + " <xs:element name=\"from\" minOccurs=\"1\" maxOccurs=\"1\" type=\"xs:string\"></xs:element>" + NEW_LINE + " <xs:element name=\"heading\" minOccurs=\"1\" maxOccurs=\"1\" type=\"xs:string\"></xs:element>" + NEW_LINE + " <xs:element name=\"body\" minOccurs=\"1\" maxOccurs=\"1\" type=\"xs:string\"></xs:element>" + NEW_LINE + " </xs:sequence>" + NEW_LINE + " </xs:complexType>" + NEW_LINE + " </xs:element>" + NEW_LINE + " </xs:sequence>" + NEW_LINE + " </xs:complexType>" + NEW_LINE + " </xs:element>" + NEW_LINE + "</xs:schema>")), exactly(2) ) .respond( response() .withBody("some_body") ); // then // - in http assertEquals( response() .withStatusCode(NOT_FOUND_404.code()), makeRequest( request() .withMethod("POST") .withBody("<?xml version=\"1.0\" encoding=\"utf-8\"?>" + NEW_LINE + "<notes>" + NEW_LINE + " <note>" + NEW_LINE + " <to>Bob</to>" + NEW_LINE + " <heading>Reminder</heading>" + NEW_LINE + " <body>Buy Bread</body>" + NEW_LINE + " </note>" + NEW_LINE + " <note>" + NEW_LINE + " <to>Jack</to>" + NEW_LINE + " <from>Jill</from>" + NEW_LINE + " <heading>Reminder</heading>" + NEW_LINE + " <body>Wash Shirts</body>" + NEW_LINE + " </note>" + NEW_LINE + "</notes>"), headersToIgnore) ); assertEquals( response() .withStatusCode(OK_200.code()) .withBody("some_body"), makeRequest( request() .withPath(calculatePath("some_path")) .withMethod("POST") .withBody("<?xml version=\"1.0\" encoding=\"utf-8\"?>" + NEW_LINE + "<notes>" + NEW_LINE + " <note>" + NEW_LINE + " <to>Bob</to>" + NEW_LINE + " <from>Bill</from>" + NEW_LINE + " <heading>Reminder</heading>" + NEW_LINE + " <body>Buy Bread</body>" + NEW_LINE + " </note>" + NEW_LINE + " <note>" + NEW_LINE + " <to>Jack</to>" + NEW_LINE + " <from>Jill</from>" + NEW_LINE + " <heading>Reminder</heading>" + NEW_LINE + " <body>Wash Shirts</body>" + NEW_LINE + " </note>" + NEW_LINE + "</notes>"), headersToIgnore) ); // - in https assertEquals( response() .withStatusCode(OK_200.code()) .withBody("some_body"), makeRequest( request() .withSecure(true) .withPath(calculatePath("some_path")) .withMethod("POST") .withBody("<?xml version=\"1.0\" encoding=\"utf-8\"?>" + NEW_LINE + "<notes>" + NEW_LINE + " <note>" + NEW_LINE + " <to>Bob</to>" + NEW_LINE + " <from>Bill</from>" + NEW_LINE + " <heading>Reminder</heading>" + NEW_LINE + " <body>Buy Bread</body>" + NEW_LINE + " </note>" + NEW_LINE + " <note>" + NEW_LINE + " <to>Jack</to>" + NEW_LINE + " <from>Jill</from>" + NEW_LINE + " <heading>Reminder</heading>" + NEW_LINE + " <body>Wash Shirts</body>" + NEW_LINE + " </note>" + NEW_LINE + "</notes>"), headersToIgnore) ); } @Test @Ignore public void shouldReturnResponseByMatchingBodyWithXmlSchemaByClasspath() { // when mockServerClient.when(request() .withBody( xmlSchema("org/mockserver/model/testXmlSchema.xsd")), exactly(2) ) .respond( response() .withBody("some_body") ); // then // - in http assertEquals( response() .withStatusCode(NOT_FOUND_404.code()), makeRequest( request() .withMethod("POST") .withBody("<?xml version=\"1.0\" encoding=\"utf-8\"?>" + NEW_LINE + "<notes>" + NEW_LINE + " <note>" + NEW_LINE + " <to>Bob</to>" + NEW_LINE + " <heading>Reminder</heading>" + NEW_LINE + " <body>Buy Bread</body>" + NEW_LINE + " </note>" + NEW_LINE + " <note>" + NEW_LINE + " <to>Jack</to>" + NEW_LINE + " <from>Jill</from>" + NEW_LINE + " <heading>Reminder</heading>" + NEW_LINE + " <body>Wash Shirts</body>" + NEW_LINE + " </note>" + NEW_LINE + "</notes>"), headersToIgnore) ); assertEquals( response() .withStatusCode(OK_200.code()) .withBody("some_body"), makeRequest( request() .withPath(calculatePath("some_path")) .withMethod("POST") .withBody("<?xml version=\"1.0\" encoding=\"utf-8\"?>" + NEW_LINE + "<notes>" + NEW_LINE + " <note>" + NEW_LINE + " <to>Bob</to>" + NEW_LINE + " <from>Bill</from>" + NEW_LINE + " <heading>Reminder</heading>" + NEW_LINE + " <body>Buy Bread</body>" + NEW_LINE + " </note>" + NEW_LINE + " <note>" + NEW_LINE + " <to>Jack</to>" + NEW_LINE + " <from>Jill</from>" + NEW_LINE + " <heading>Reminder</heading>" + NEW_LINE + " <body>Wash Shirts</body>" + NEW_LINE + " </note>" + NEW_LINE + "</notes>"), headersToIgnore) ); // - in https assertEquals( response() .withStatusCode(OK_200.code()) .withBody("some_body"), makeRequest( request() .withSecure(true) .withPath(calculatePath("some_path")) .withMethod("POST") .withBody("<?xml version=\"1.0\" encoding=\"utf-8\"?>" + NEW_LINE + "<notes>" + NEW_LINE + " <note>" + NEW_LINE + " <to>Bob</to>" + NEW_LINE + " <from>Bill</from>" + NEW_LINE + " <heading>Reminder</heading>" + NEW_LINE + " <body>Buy Bread</body>" + NEW_LINE + " </note>" + NEW_LINE + " <note>" + NEW_LINE + " <to>Jack</to>" + NEW_LINE + " <from>Jill</from>" + NEW_LINE + " <heading>Reminder</heading>" + NEW_LINE + " <body>Wash Shirts</body>" + NEW_LINE + " </note>" + NEW_LINE + "</notes>"), headersToIgnore) ); } @Test public void shouldReturnPDFResponseByMatchingPath() throws IOException { // when byte[] pdfBytes = IOUtils.toByteArray(getClass().getClassLoader().getResourceAsStream("test.pdf")); mockServerClient .when( request() .withPath(calculatePath("ws/rest/user/[0-9]+/document/[0-9]+\\.pdf")) ) .respond( response() .withStatusCode(OK_200.code()) .withHeaders( header(CONTENT_TYPE.toString(), MediaType.PDF.toString()), header(CONTENT_DISPOSITION.toString(), "form-data; name=\"test.pdf\"; filename=\"test.pdf\""), header(CACHE_CONTROL.toString(), "must-revalidate, post-check=0, pre-check=0") ) .withBody(binary(pdfBytes)) ); // then // - in http assertEquals( response() .withStatusCode(OK_200.code()) .withHeaders( header(CONTENT_DISPOSITION.toString(), "form-data; name=\"test.pdf\"; filename=\"test.pdf\""), header(CACHE_CONTROL.toString(), "must-revalidate, post-check=0, pre-check=0"), header(CONTENT_TYPE.toString(), MediaType.PDF.toString()) ) .withBody(binary(pdfBytes)), makeRequest( request() .withPath(calculatePath("ws/rest/user/1/document/2.pdf")) .withMethod("GET"), headersToIgnore) ); // - in https assertEquals( response() .withStatusCode(OK_200.code()) .withHeaders( header(CONTENT_DISPOSITION.toString(), "form-data; name=\"test.pdf\"; filename=\"test.pdf\""), header(CACHE_CONTROL.toString(), "must-revalidate, post-check=0, pre-check=0"), header(CONTENT_TYPE.toString(), MediaType.PDF.toString()) ) .withBody(binary(pdfBytes)), makeRequest( request() .withSecure(true) .withPath(calculatePath("ws/rest/user/1/document/2.pdf")) .withMethod("GET"), headersToIgnore) ); } @Test public void shouldReturnPNGResponseByMatchingPath() throws IOException { // when byte[] pngBytes = IOUtils.toByteArray(getClass().getClassLoader().getResourceAsStream("test.png")); mockServerClient .when( request() .withPath(calculatePath("ws/rest/user/[0-9]+/icon/[0-9]+\\.png")) ) .respond( response() .withStatusCode(OK_200.code()) .withHeaders( header(CONTENT_TYPE.toString(), MediaType.PNG.toString()), header(CONTENT_DISPOSITION.toString(), "form-data; name=\"test.png\"; filename=\"test.png\"") ) .withBody(binary(pngBytes)) ); // then // - in http assertEquals( response() .withStatusCode(OK_200.code()) .withHeaders( header(CONTENT_DISPOSITION.toString(), "form-data; name=\"test.png\"; filename=\"test.png\""), header(CONTENT_TYPE.toString(), MediaType.PNG.toString()) ) .withBody(binary(pngBytes)), makeRequest( request() .withPath(calculatePath("ws/rest/user/1/icon/1.png")) .withMethod("GET"), headersToIgnore) ); // - in https assertEquals( response() .withStatusCode(OK_200.code()) .withHeaders( header(CONTENT_DISPOSITION.toString(), "form-data; name=\"test.png\"; filename=\"test.png\""), header(CONTENT_TYPE.toString(), MediaType.PNG.toString()) ) .withBody(binary(pngBytes)), makeRequest( request() .withSecure(true) .withPath(calculatePath("ws/rest/user/1/icon/1.png")) .withMethod("GET"), headersToIgnore) ); } @Test public void shouldReturnPDFResponseByMatchingBinaryPDFBody() throws IOException { // when byte[] pdfBytes = IOUtils.toByteArray(getClass().getClassLoader().getResourceAsStream("test.pdf")); mockServerClient .when( request().withBody(binary(pdfBytes)) ) .respond( response() .withStatusCode(OK_200.code()) .withHeaders( header(CONTENT_TYPE.toString(), MediaType.PDF.toString()), header(CONTENT_DISPOSITION.toString(), "form-data; name=\"test.pdf\"; filename=\"test.pdf\""), header(CACHE_CONTROL.toString(), "must-revalidate, post-check=0, pre-check=0") ) .withBody(binary(pdfBytes)) ); // then // - in http assertEquals( response() .withStatusCode(OK_200.code()) .withHeaders( header(CONTENT_DISPOSITION.toString(), "form-data; name=\"test.pdf\"; filename=\"test.pdf\""), header(CACHE_CONTROL.toString(), "must-revalidate, post-check=0, pre-check=0"), header(CONTENT_TYPE.toString(), MediaType.PDF.toString()) ) .withBody(binary(pdfBytes)), makeRequest( request() .withPath(calculatePath("ws/rest/user/1/document/2.pdf")) .withBody(binary(pdfBytes)) .withMethod("POST"), headersToIgnore) ); // - in https assertEquals( response() .withStatusCode(OK_200.code()) .withHeaders( header(CONTENT_DISPOSITION.toString(), "form-data; name=\"test.pdf\"; filename=\"test.pdf\""), header(CACHE_CONTROL.toString(), "must-revalidate, post-check=0, pre-check=0"), header(CONTENT_TYPE.toString(), MediaType.PDF.toString()) ) .withBody(binary(pdfBytes)), makeRequest( request() .withSecure(true) .withPath(calculatePath("ws/rest/user/1/document/2.pdf")) .withBody(binary(pdfBytes)) .withMethod("POST"), headersToIgnore) ); } @Test public void shouldReturnPNGResponseByMatchingBinaryPNGBody() throws IOException { // when byte[] pngBytes = IOUtils.toByteArray(getClass().getClassLoader().getResourceAsStream("test.png")); mockServerClient .when( request().withBody(binary(pngBytes)) ) .respond( response() .withStatusCode(OK_200.code()) .withHeaders( header(CONTENT_TYPE.toString(), MediaType.PNG.toString()), header(CONTENT_DISPOSITION.toString(), "form-data; name=\"test.png\"; filename=\"test.png\"") ) .withBody(binary(pngBytes)) ); // then // - in http assertEquals( response() .withStatusCode(OK_200.code()) .withHeaders( header(CONTENT_DISPOSITION.toString(), "form-data; name=\"test.png\"; filename=\"test.png\""), header(CONTENT_TYPE.toString(), MediaType.PNG.toString()) ) .withBody(binary(pngBytes)), makeRequest( request() .withPath(calculatePath("ws/rest/user/1/icon/1.png")) .withBody(binary(pngBytes)) .withMethod("POST"), headersToIgnore) ); // - in https assertEquals( response() .withStatusCode(OK_200.code()) .withHeaders( header(CONTENT_DISPOSITION.toString(), "form-data; name=\"test.png\"; filename=\"test.png\""), header(CONTENT_TYPE.toString(), MediaType.PNG.toString()) ) .withBody(binary(pngBytes)), makeRequest( request() .withSecure(true) .withPath(calculatePath("ws/rest/user/1/icon/1.png")) .withBody(binary(pngBytes)) .withMethod("POST"), headersToIgnore) ); } @Test public void shouldReturnResponseForExpectationWithDelay() { // when mockServerClient .when( request() .withPath(calculatePath("some_path1")) ) .respond( response() .withBody("some_body1") .withDelay(new Delay(TimeUnit.MILLISECONDS, 10)) ); mockServerClient .when( request() .withPath(calculatePath("some_path2")) ) .respond( response() .withBody("some_body2") .withDelay(new Delay(TimeUnit.MILLISECONDS, 20)) ); // then // - in http assertEquals( response() .withStatusCode(OK_200.code()) .withBody("some_body2"), makeRequest( request() .withPath(calculatePath("some_path2")), headersToIgnore) ); assertEquals( response() .withStatusCode(OK_200.code()) .withBody("some_body1"), makeRequest( request() .withPath(calculatePath("some_path1")), headersToIgnore) ); // - in https assertEquals( response() .withStatusCode(OK_200.code()) .withBody("some_body2"), makeRequest( request() .withSecure(true) .withPath(calculatePath("some_path2")), headersToIgnore) ); assertEquals( response() .withStatusCode(OK_200.code()) .withBody("some_body1"), makeRequest( request() .withSecure(true) .withPath(calculatePath("some_path1")), headersToIgnore) ); } @Test public void shouldReturnResponseByMatchingPathAndMethod() { // when mockServerClient .when( request() .withMethod("GET") .withPath(calculatePath("some_pathRequest")) ) .respond( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body_response") ); // then // - in http assertEquals( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body_response"), makeRequest( request() .withMethod("GET") .withPath(calculatePath("some_pathRequest")) .withQueryStringParameters( param("queryStringParameterOneName", "queryStringParameterOneValue"), param("queryStringParameterTwoName", "queryStringParameterTwoValue") ) .withHeaders(header("headerNameRequest", "headerValueRequest")) .withCookies(cookie("cookieNameRequest", "cookieValueRequest")), headersToIgnore) ); // - in https assertEquals( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body_response"), makeRequest( request() .withMethod("GET") .withSecure(true) .withPath(calculatePath("some_pathRequest")) .withQueryStringParameters( param("queryStringParameterOneName", "queryStringParameterOneValue"), param("queryStringParameterTwoName", "queryStringParameterTwoValue") ) .withHeaders(header("headerNameRequest", "headerValueRequest")) .withCookies(cookie("cookieNameRequest", "cookieValueRequest")), headersToIgnore) ); } @Test public void shouldReturnResponseByNotMatchingPathWithNotOperator() { // when mockServerClient .when( request() .withPath(not(calculatePath("some_path"))) ) .respond( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body_response") ); // then // - in http assertEquals( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body_response"), makeRequest( request() .withPath(calculatePath("some_other_path")), headersToIgnore) ); // - in https assertEquals( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body_response"), makeRequest( request() .withPath(calculatePath("some_other_path")), headersToIgnore) ); } @Test public void shouldReturnResponseByNotMatchingMethodWithNotOperator() { // when mockServerClient .when( request() .withMethod(not("GET")) ) .respond( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body_response") ); // then // - in http assertEquals( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body_response"), makeRequest( request() .withMethod("POST"), headersToIgnore) ); // - in https assertEquals( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body_response"), makeRequest( request() .withMethod("POST"), headersToIgnore) ); } @Test public void shouldReturnResponseByMatchingPathAndMethodAndBody() { // when mockServerClient .when( request() .withMethod("POST") .withPath(calculatePath("some_pathRequest")) .withBody("some_bodyRequest") ) .respond( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body_response") .withHeaders(header("headerNameResponse", "headerValueResponse")) ); // then // - in http assertEquals( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body_response") .withHeaders( header("headerNameResponse", "headerValueResponse") ), makeRequest( request() .withMethod("POST") .withPath(calculatePath("some_pathRequest")) .withQueryStringParameters( param("queryStringParameterOneName", "queryStringParameterOneValue"), param("queryStringParameterTwoName", "queryStringParameterTwoValue") ) .withBody("some_bodyRequest") .withHeaders(header("headerNameRequest", "headerValueRequest")) .withCookies(cookie("cookieNameRequest", "cookieValueRequest")), headersToIgnore) ); // - in https assertEquals( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body_response") .withHeaders( header("headerNameResponse", "headerValueResponse") ), makeRequest( request() .withMethod("POST") .withSecure(true) .withPath(calculatePath("some_pathRequest")) .withQueryStringParameters( param("queryStringParameterOneName", "queryStringParameterOneValue"), param("queryStringParameterTwoName", "queryStringParameterTwoValue") ) .withBody("some_bodyRequest") .withHeaders(header("headerNameRequest", "headerValueRequest")) .withCookies(cookie("cookieNameRequest", "cookieValueRequest")), headersToIgnore) ); } @Test public void shouldReturnResponseByMatchingPathAndMethodAndQueryStringParameters() { // when mockServerClient .when( request() .withMethod("GET") .withPath(calculatePath("some_pathRequest")) .withQueryStringParameters( param("queryStringParameterOneName", "queryStringParameterOneValue"), param("queryStringParameterTwoName", "queryStringParameterTwoValue") ) ) .respond( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body_response") .withCookies(cookie("cookieNameResponse", "cookieValueResponse")) ); // then // - in http assertEquals( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body_response") .withCookies(cookie("cookieNameResponse", "cookieValueResponse")) .withHeaders( header(SET_COOKIE.toString(), "cookieNameResponse=cookieValueResponse") ), makeRequest( request() .withMethod("GET") .withPath(calculatePath("some_pathRequest")) .withQueryStringParameters( param("queryStringParameterOneName", "queryStringParameterOneValue"), param("queryStringParameterTwoName", "queryStringParameterTwoValue") ) .withHeaders(header("headerNameRequest", "headerValueRequest")) .withCookies(cookie("cookieNameRequest", "cookieValueRequest")), headersToIgnore) ); // - in https assertEquals( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body_response") .withCookies(cookie("cookieNameResponse", "cookieValueResponse")) .withHeaders( header(SET_COOKIE.toString(), "cookieNameResponse=cookieValueResponse") ), makeRequest( request() .withMethod("GET") .withSecure(true) .withPath(calculatePath("some_pathRequest")) .withQueryStringParameters( param("queryStringParameterOneName", "queryStringParameterOneValue"), param("queryStringParameterTwoName", "queryStringParameterTwoValue") ) .withHeaders(header("headerNameRequest", "headerValueRequest")) .withCookies(cookie("cookieNameRequest", "cookieValueRequest")), headersToIgnore) ); } @Test public void shouldReturnResponseByMatchingPathAndMethodAndHeaders() { // when mockServerClient .when( request() .withMethod("GET") .withPath(calculatePath("some_pathRequest")) .withHeaders( header("requestHeaderNameOne", "requestHeaderValueOne_One", "requestHeaderValueOne_Two"), header("requestHeaderNameTwo", "requestHeaderValueTwo") ) ) .respond( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body_response") .withCookies(cookie("cookieNameResponse", "cookieValueResponse")) ); // then // - in http assertEquals( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body_response") .withCookies(cookie("cookieNameResponse", "cookieValueResponse")) .withHeaders( header(SET_COOKIE.toString(), "cookieNameResponse=cookieValueResponse") ), makeRequest( request() .withMethod("GET") .withPath(calculatePath("some_pathRequest")) .withHeaders( header("requestHeaderNameOne", "requestHeaderValueOne_One", "requestHeaderValueOne_Two"), header("requestHeaderNameTwo", "requestHeaderValueTwo") ) .withCookies(cookie("cookieNameRequest", "cookieValueRequest")), headersToIgnore) ); // - in https assertEquals( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body_response") .withCookies(cookie("cookieNameResponse", "cookieValueResponse")) .withHeaders( header(SET_COOKIE.toString(), "cookieNameResponse=cookieValueResponse") ), makeRequest( request() .withMethod("GET") .withSecure(true) .withPath(calculatePath("some_pathRequest")) .withHeaders( header("requestHeaderNameOne", "requestHeaderValueOne_One", "requestHeaderValueOne_Two"), header("requestHeaderNameTwo", "requestHeaderValueTwo") ) .withCookies(cookie("cookieNameRequest", "cookieValueRequest")), headersToIgnore) ); } @Test public void shouldReturnResponseByMatchingPathAndMethodAndCookies() { // when mockServerClient .when( request() .withMethod("GET") .withPath(calculatePath("some_pathRequest")) .withCookies( cookie("requestCookieNameOne", "requestCookieValueOne"), cookie("requestCookieNameTwo", "requestCookieValueTwo") ) ) .respond( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body_response") .withCookies( cookie("responseCookieNameOne", "responseCookieValueOne"), cookie("responseCookieNameTwo", "responseCookieValueTwo") ) ); // then // - in http - cookie objects assertEquals( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body_response") .withCookies( cookie("responseCookieNameOne", "responseCookieValueOne"), cookie("responseCookieNameTwo", "responseCookieValueTwo") ) .withHeaders( header(SET_COOKIE.toString(), "responseCookieNameOne=responseCookieValueOne", "responseCookieNameTwo=responseCookieValueTwo") ), makeRequest( request() .withMethod("GET") .withPath(calculatePath("some_pathRequest")) .withHeaders( header("headerNameRequest", "headerValueRequest"), header(CONTENT_TYPE.toString(), TEXT_PLAIN) ) .withCookies( cookie("requestCookieNameOne", "requestCookieValueOne"), cookie("requestCookieNameTwo", "requestCookieValueTwo") ), headersToIgnore) ); // - in http - cookie header assertEquals( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body_response") .withCookies( cookie("responseCookieNameOne", "responseCookieValueOne"), cookie("responseCookieNameTwo", "responseCookieValueTwo") ) .withHeaders( header(SET_COOKIE.toString(), "responseCookieNameOne=responseCookieValueOne", "responseCookieNameTwo=responseCookieValueTwo") ), makeRequest( request() .withMethod("GET") .withPath(calculatePath("some_pathRequest")) .withHeaders( header("headerNameRequest", "headerValueRequest"), header("Cookie", "requestCookieNameOne=requestCookieValueOne; requestCookieNameTwo=requestCookieValueTwo") ), headersToIgnore) ); // - in https - cookie objects assertEquals( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body_response") .withCookies( cookie("responseCookieNameOne", "responseCookieValueOne"), cookie("responseCookieNameTwo", "responseCookieValueTwo") ) .withHeaders( header(SET_COOKIE.toString(), "responseCookieNameOne=responseCookieValueOne", "responseCookieNameTwo=responseCookieValueTwo") ), makeRequest( request() .withMethod("GET") .withSecure(true) .withPath(calculatePath("some_pathRequest")) .withHeaders( header("headerNameRequest", "headerValueRequest") ) .withCookies( cookie("requestCookieNameOne", "requestCookieValueOne"), cookie("requestCookieNameTwo", "requestCookieValueTwo") ), headersToIgnore) ); // - in https - cookie header assertEquals( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body_response") .withCookies( cookie("responseCookieNameOne", "responseCookieValueOne"), cookie("responseCookieNameTwo", "responseCookieValueTwo") ) .withHeaders( header(SET_COOKIE.toString(), "responseCookieNameOne=responseCookieValueOne", "responseCookieNameTwo=responseCookieValueTwo") ), makeRequest( request() .withMethod("GET") .withSecure(true) .withPath(calculatePath("some_pathRequest")) .withHeaders( header("headerNameRequest", "headerValueRequest"), header("Cookie", "requestCookieNameOne=requestCookieValueOne; requestCookieNameTwo=requestCookieValueTwo") ), headersToIgnore) ); } @Test public void shouldReturnResponseByMatchingPathAndMethodAndQueryStringParametersAndBodyParameters() { // when mockServerClient .when( request() .withMethod("POST") .withPath(calculatePath("some_pathRequest")) .withQueryStringParameters( param("queryStringParameterOneName", "queryStringParameterOneValueOne", "queryStringParameterOneValueTwo"), param("queryStringParameterTwoName", "queryStringParameterTwoValue") ) .withBody(params(param("bodyParameterName", "bodyParameterValue"))) ) .respond( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body") ); // then // - in http - url query string assertEquals( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body"), makeRequest( request() .withMethod("POST") .withPath(calculatePath("some_pathRequest")) .withQueryStringParameters( param("queryStringParameterOneName", "queryStringParameterOneValueOne", "queryStringParameterOneValueTwo"), param("queryStringParameterTwoName", "queryStringParameterTwoValue") ) .withBody(params(param("bodyParameterName", "bodyParameterValue"))), headersToIgnore) ); // - in https - query string parameter objects assertEquals( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body"), makeRequest( request() .withSecure(true) .withMethod("POST") .withPath(calculatePath("some_pathRequest")) .withQueryStringParameters( param("queryStringParameterOneName", "queryStringParameterOneValueOne", "queryStringParameterOneValueTwo"), param("queryStringParameterTwoName", "queryStringParameterTwoValue") ) .withBody(params(param("bodyParameterName", "bodyParameterValue"))), headersToIgnore) ); } @Test public void shouldReturnResponseByMatchingPathAndMethodAndQueryStringParametersAndBody() { // when mockServerClient .when( request() .withMethod("POST") .withPath(calculatePath("some_pathRequest")) .withQueryStringParameters( param("queryStringParameterOneName", "queryStringParameterOneValueOne", "queryStringParameterOneValueTwo"), param("queryStringParameterTwoName", "queryStringParameterTwoValue") ) .withBody("some_bodyRequest") ) .respond( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body_response") .withHeaders(header("headerNameResponse", "headerValueResponse")) .withCookies(cookie("cookieNameResponse", "cookieValueResponse")) ); // then // - in http - url query string assertEquals( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body_response") .withCookies(cookie("cookieNameResponse", "cookieValueResponse")) .withHeaders( header("headerNameResponse", "headerValueResponse"), header(SET_COOKIE.toString(), "cookieNameResponse=cookieValueResponse") ), makeRequest( request() .withMethod("POST") .withPath(calculatePath("some_pathRequest")) .withQueryStringParameters( param("queryStringParameterOneName", "queryStringParameterOneValueOne", "queryStringParameterOneValueTwo"), param("queryStringParameterTwoName", "queryStringParameterTwoValue") ) .withBody("some_bodyRequest") .withHeaders(header("headerNameRequest", "headerValueRequest")) .withCookies(cookie("cookieNameRequest", "cookieValueRequest")), headersToIgnore) ); // - in http - query string parameter objects assertEquals( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body_response") .withCookies(cookie("cookieNameResponse", "cookieValueResponse")) .withHeaders( header("headerNameResponse", "headerValueResponse"), header(SET_COOKIE.toString(), "cookieNameResponse=cookieValueResponse") ), makeRequest( request() .withMethod("POST") .withPath(calculatePath("some_pathRequest")) .withQueryStringParameters( param("queryStringParameterOneName", "queryStringParameterOneValueOne", "queryStringParameterOneValueTwo"), param("queryStringParameterTwoName", "queryStringParameterTwoValue") ) .withBody("some_bodyRequest") .withHeaders(header("headerNameRequest", "headerValueRequest")) .withCookies(cookie("cookieNameRequest", "cookieValueRequest")), headersToIgnore) ); // - in https - url string and query string parameter objects assertEquals( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body_response") .withCookies(cookie("cookieNameResponse", "cookieValueResponse")) .withHeaders( header("headerNameResponse", "headerValueResponse"), header(SET_COOKIE.toString(), "cookieNameResponse=cookieValueResponse") ), makeRequest( request() .withMethod("POST") .withPath(calculatePath("some_pathRequest")) .withQueryStringParameters( param("queryStringParameterOneName", "queryStringParameterOneValueOne", "queryStringParameterOneValueTwo"), param("queryStringParameterTwoName", "queryStringParameterTwoValue") ) .withBody("some_bodyRequest") .withHeaders(header("headerNameRequest", "headerValueRequest")) .withCookies(cookie("cookieNameRequest", "cookieValueRequest")), headersToIgnore) ); } @Test public void shouldReturnResponseByMatchingPathAndMethodAndBodyParameters() { // when mockServerClient .when( request() .withMethod("POST") .withPath(calculatePath("some_pathRequest")) .withBody(params( param("bodyParameterOneName", "Parameter One Value One", "Parameter One Value Two"), param("bodyParameterTwoName", "Parameter Two") )) ) .respond( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body_response") .withHeaders(header("headerNameResponse", "headerValueResponse")) .withCookies(cookie("cookieNameResponse", "cookieValueResponse")) ); // then // - in http - body string assertEquals( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body_response") .withCookies(cookie("cookieNameResponse", "cookieValueResponse")) .withHeaders( header("headerNameResponse", "headerValueResponse"), header(SET_COOKIE.toString(), "cookieNameResponse=cookieValueResponse") ), makeRequest( request() .withMethod("POST") .withPath(calculatePath("some_pathRequest")) .withBody(new StringBody("bodyParameterOneName=Parameter+One+Value+One" + "&bodyParameterOneName=Parameter+One+Value+Two" + "&bodyParameterTwoName=Parameter+Two")) .withHeaders(header("headerNameRequest", "headerValueRequest")) .withCookies(cookie("cookieNameRequest", "cookieValueRequest")), headersToIgnore) ); // - in http - body parameter objects assertEquals( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body_response") .withCookies(cookie("cookieNameResponse", "cookieValueResponse")) .withHeaders( header("headerNameResponse", "headerValueResponse"), header(SET_COOKIE.toString(), "cookieNameResponse=cookieValueResponse") ), makeRequest( request() .withMethod("POST") .withPath(calculatePath("some_pathRequest")) .withBody(params( param("bodyParameterOneName", "Parameter One Value One", "Parameter One Value Two"), param("bodyParameterTwoName", "Parameter Two") )) .withHeaders(header("headerNameRequest", "headerValueRequest")) .withCookies(cookie("cookieNameRequest", "cookieValueRequest")), headersToIgnore) ); // - in https - url string and query string parameter objects assertEquals( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body_response") .withCookies(cookie("cookieNameResponse", "cookieValueResponse")) .withHeaders( header("headerNameResponse", "headerValueResponse"), header(SET_COOKIE.toString(), "cookieNameResponse=cookieValueResponse") ), makeRequest( request() .withMethod("POST") .withPath(calculatePath("some_pathRequest")) .withBody(params( param("bodyParameterOneName", "Parameter One Value One", "Parameter One Value Two"), param("bodyParameterTwoName", "Parameter Two") )) .withHeaders(header("headerNameRequest", "headerValueRequest")) .withCookies(cookie("cookieNameRequest", "cookieValueRequest")), headersToIgnore) ); } @Test public void shouldReturnResponseByMatchingPathAndMethodAndParametersAndHeadersAndCookies() { // when mockServerClient .when( request() .withMethod("PUT") .withPath(calculatePath("some_pathRequest")) .withBody(new StringBody("bodyParameterOneName=Parameter+One+Value+One" + "&bodyParameterOneName=Parameter+One+Value+Two" + "&bodyParameterTwoName=Parameter+Two")) .withHeaders(header("headerNameRequest", "headerValueRequest")) .withCookies(cookie("cookieNameRequest", "cookieValueRequest")) ) .respond( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body_response") .withHeaders(header("headerNameResponse", "headerValueResponse")) .withCookies(cookie("cookieNameResponse", "cookieValueResponse")) ); // then // - in http - body string assertEquals( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body_response") .withCookies(cookie("cookieNameResponse", "cookieValueResponse")) .withHeaders( header("headerNameResponse", "headerValueResponse"), header(SET_COOKIE.toString(), "cookieNameResponse=cookieValueResponse") ), makeRequest( request() .withMethod("PUT") .withPath(calculatePath("some_pathRequest")) .withBody(new StringBody("bodyParameterOneName=Parameter+One+Value+One" + "&bodyParameterOneName=Parameter+One+Value+Two" + "&bodyParameterTwoName=Parameter+Two")) .withHeaders( header("headerNameRequest", "headerValueRequest"), header("Cookie", "cookieNameRequest=cookieValueRequest") ), headersToIgnore) ); // - in http - body parameter objects assertEquals( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body_response") .withCookies(cookie("cookieNameResponse", "cookieValueResponse")) .withHeaders( header("headerNameResponse", "headerValueResponse"), header(SET_COOKIE.toString(), "cookieNameResponse=cookieValueResponse") ), makeRequest( request() .withMethod("PUT") .withPath(calculatePath("some_pathRequest")) .withBody(params( param("bodyParameterOneName", "Parameter One Value One", "Parameter One Value Two"), param("bodyParameterTwoName", "Parameter Two") )) .withHeaders(header("headerNameRequest", "headerValueRequest")) .withCookies(cookie("cookieNameRequest", "cookieValueRequest")), headersToIgnore) ); } @Test public void shouldReturnResponseByNotMatchingBodyParameterWithNotOperatorForNameAndValue() { // when mockServerClient .when( request() .withMethod("POST") .withPath(calculatePath("some_pathRequest")) .withBody(params( param(not("bodyParameterOneName"), not("Parameter One Value One"), not("Parameter One Value Two")), param("bodyParameterTwoName", "Parameter Two") )) ) .respond( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body_response") ); // then // wrong query string parameter name assertEquals( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body_response"), makeRequest( request() .withMethod("POST") .withPath(calculatePath("some_pathRequest")) .withBody(params( param("OTHERBodyParameterOneName", "Parameter One Value One", "Parameter One Value Two"), param("bodyParameterTwoName", "Parameter Two") )) .withHeaders(header("headerNameRequest", "headerValueRequest")) .withCookies(cookie("cookieNameRequest", "cookieValueRequest")), headersToIgnore) ); // wrong query string parameter name assertEquals( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body_response"), makeRequest( request() .withMethod("POST") .withPath(calculatePath("some_pathRequest")) .withBody(new StringBody("OTHERBodyParameterOneName=Parameter+One+Value+One" + "&OTHERBodyParameterOneName=Parameter+One+Value+Two" + "&bodyParameterTwoName=Parameter+Two")) .withHeaders(header("headerNameRequest", "headerValueRequest")) .withCookies(cookie("cookieNameRequest", "cookieValueRequest")), headersToIgnore) ); // wrong query string parameter value assertEquals( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body_response"), makeRequest( request() .withMethod("POST") .withPath(calculatePath("some_pathRequest")) .withBody(params( param("bodyParameterOneName", "OTHER Parameter One Value One", "OTHER Parameter One Value Two"), param("bodyParameterTwoName", "Parameter Two") )) .withHeaders(header("headerNameRequest", "headerValueRequest")) .withCookies(cookie("cookieNameRequest", "cookieValueRequest")), headersToIgnore) ); // wrong query string parameter value assertEquals( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body_response"), makeRequest( request() .withMethod("POST") .withPath(calculatePath("some_pathRequest")) .withBody(new StringBody("bodyParameterOneName=OTHER Parameter+One+Value+One" + "&bodyParameterOneName=OTHER Parameter+One+Value+Two" + "&bodyParameterTwoName=Parameter+Two")) .withHeaders(header("headerNameRequest", "headerValueRequest")) .withCookies(cookie("cookieNameRequest", "cookieValueRequest")), headersToIgnore) ); } @Test public void shouldReturnResponseByNotMatchingBodyParameterWithNotOperatorForName() { // when mockServerClient .when( request() .withMethod("POST") .withPath(calculatePath("some_pathRequest")) .withBody(params( param(not("bodyParameterOneName"), string("Parameter One Value One"), string("Parameter One Value Two")), param("bodyParameterTwoName", "Parameter Two") )) ) .respond( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body_response") ); // then // wrong query string parameter name assertEquals( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body_response"), makeRequest( request() .withMethod("POST") .withPath(calculatePath("some_pathRequest")) .withBody(params( param("OTHERBodyParameterOneName", "Parameter One Value One", "Parameter One Value Two"), param("bodyParameterTwoName", "Parameter Two") )) .withHeaders(header("headerNameRequest", "headerValueRequest")) .withCookies(cookie("cookieNameRequest", "cookieValueRequest")), headersToIgnore) ); // wrong query string parameter name assertEquals( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body_response"), makeRequest( request() .withMethod("POST") .withPath(calculatePath("some_pathRequest")) .withBody(new StringBody("OTHERBodyParameterOneName=Parameter+One+Value+One" + "&OTHERBodyParameterOneName=Parameter+One+Value+Two" + "&bodyParameterTwoName=Parameter+Two")) .withHeaders(header("headerNameRequest", "headerValueRequest")) .withCookies(cookie("cookieNameRequest", "cookieValueRequest")), headersToIgnore) ); } @Test public void shouldReturnResponseByNotMatchingBodyParameterWithNotOperatorForValue() { // when mockServerClient .when( request() .withMethod("POST") .withPath(calculatePath("some_pathRequest")) .withBody(params( param(string("bodyParameterOneName"), not("Parameter One Value One"), not("Parameter One Value Two")), param("bodyParameterTwoName", "Parameter Two") )) ) .respond( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body_response") ); // then // wrong query string parameter value assertEquals( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body_response"), makeRequest( request() .withMethod("POST") .withPath(calculatePath("some_pathRequest")) .withBody(params( param("bodyParameterOneName", "OTHER Parameter One Value One", "OTHER Parameter One Value Two"), param("bodyParameterTwoName", "Parameter Two") )) .withHeaders(header("headerNameRequest", "headerValueRequest")) .withCookies(cookie("cookieNameRequest", "cookieValueRequest")), headersToIgnore) ); // wrong query string parameter value assertEquals( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body_response"), makeRequest( request() .withMethod("POST") .withPath(calculatePath("some_pathRequest")) .withBody(new StringBody("bodyParameterOneName=OTHER Parameter+One+Value+One" + "&bodyParameterOneName=OTHER Parameter+One+Value+Two" + "&bodyParameterTwoName=Parameter+Two")) .withHeaders(header("headerNameRequest", "headerValueRequest")) .withCookies(cookie("cookieNameRequest", "cookieValueRequest")), headersToIgnore) ); } @Test public void shouldReturnResponseByNotMatchingQueryStringParameterWithNotOperatorForNameAndValue() { // when mockServerClient .when( request() .withMethod("POST") .withPath(calculatePath("some_pathRequest")) .withQueryStringParameters( param(not("queryStringParameterOneName"), not("Parameter One Value One"), not("Parameter One Value Two")), param("queryStringParameterTwoName", "Parameter Two") ) ) .respond( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body_response") ); // then // wrong query string parameter name assertEquals( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body_response"), makeRequest( request() .withMethod("POST") .withPath(calculatePath("some_pathRequest")) .withQueryStringParameters( param("OTHERQueryStringParameterOneName", "Parameter One Value One", "Parameter One Value Two"), param("queryStringParameterTwoName", "Parameter Two") ), headersToIgnore) ); // wrong query string parameter value assertEquals( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body_response"), makeRequest( request() .withMethod("POST") .withPath(calculatePath("some_pathRequest")) .withQueryStringParameters( param("queryStringParameterOneName", "OTHER Parameter One Value One", "OTHER Parameter One Value Two"), param("queryStringParameterTwoName", "Parameter Two") ), headersToIgnore) ); } @Test public void shouldReturnResponseByNotMatchingQueryStringParameterWithNotOperatorForName() { // when mockServerClient .when( request() .withMethod("POST") .withPath(calculatePath("some_pathRequest")) .withQueryStringParameters( param(not("queryStringParameterOneName"), string("Parameter One Value One"), string("Parameter One Value Two")), param("queryStringParameterTwoName", "Parameter Two") ) ) .respond( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body_response") ); // then // wrong query string parameter name assertEquals( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body_response"), makeRequest( request() .withMethod("POST") .withPath(calculatePath("some_pathRequest")) .withQueryStringParameters( param("OTHERQueryStringParameterOneName", "Parameter One Value One", "Parameter One Value Two"), param("queryStringParameterTwoName", "Parameter Two") ), headersToIgnore) ); } @Test public void shouldReturnResponseByNotMatchingQueryStringParameterWithNotOperatorForValue() { // when mockServerClient .when( request() .withMethod("POST") .withPath(calculatePath("some_pathRequest")) .withQueryStringParameters( param(string("queryStringParameterOneName"), not("Parameter One Value One"), not("Parameter One Value Two")), param("queryStringParameterTwoName", "Parameter Two") ) ) .respond( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body_response") ); // then // wrong query string parameter value assertEquals( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body_response"), makeRequest( request() .withMethod("POST") .withPath(calculatePath("some_pathRequest")) .withQueryStringParameters( param("queryStringParameterOneName", "OTHER Parameter One Value One", "OTHER Parameter One Value Two"), param("queryStringParameterTwoName", "Parameter Two") ), headersToIgnore) ); } @Test public void shouldReturnResponseByNotMatchingCookieWithNotOperatorForNameAndValue() { // when mockServerClient .when( request() .withMethod("GET") .withPath(calculatePath("some_pathRequest")) .withCookies( cookie(not("requestCookieNameOne"), not("requestCookieValueOne")), cookie("requestCookieNameTwo", "requestCookieValueTwo") ) ) .respond( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body_response") ); // then // wrong query string cookie name assertEquals( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body_response"), makeRequest( request() .withMethod("GET") .withPath(calculatePath("some_pathRequest")) .withCookies( cookie("OTHERrequestCookieNameOne", "requestCookieValueOne"), cookie("requestCookieNameTwo", "requestCookieValueTwo") ), headersToIgnore) ); // wrong query string cookie value assertEquals( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body_response"), makeRequest( request() .withMethod("GET") .withPath(calculatePath("some_pathRequest")) .withCookies( cookie("requestCookieNameOne", "OTHERrequestCookieValueOne"), cookie("requestCookieNameTwo", "requestCookieValueTwo") ), headersToIgnore) ); } @Test public void shouldReturnResponseByNotMatchingCookieWithNotOperatorForName() { // when mockServerClient .when( request() .withMethod("GET") .withPath(calculatePath("some_pathRequest")) .withCookies( cookie(not("requestCookieNameOne"), string("requestCookieValueOne")), cookie("requestCookieNameTwo", "requestCookieValueTwo") ) ) .respond( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body_response") ); // then // wrong query string cookie name assertEquals( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body_response"), makeRequest( request() .withMethod("GET") .withPath(calculatePath("some_pathRequest")) .withCookies( cookie("OTHERrequestCookieNameOne", "requestCookieValueOne"), cookie("requestCookieNameTwo", "requestCookieValueTwo") ), headersToIgnore) ); } @Test public void shouldReturnResponseByNotMatchingCookieWithNotOperatorForValue() { // when mockServerClient .when( request() .withMethod("GET") .withPath(calculatePath("some_pathRequest")) .withCookies( cookie(string("requestCookieNameOne"), not("requestCookieValueOne")), cookie("requestCookieNameTwo", "requestCookieValueTwo") ) ) .respond( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body_response") ); // then // wrong query string cookie value assertEquals( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body_response"), makeRequest( request() .withMethod("GET") .withPath(calculatePath("some_pathRequest")) .withCookies( cookie("requestCookieNameOne", "OTHERrequestCookieValueOne"), cookie("requestCookieNameTwo", "requestCookieValueTwo") ), headersToIgnore) ); } @Test public void shouldReturnResponseByNotMatchingHeaderWithNotOperatorForNameAndValue() { // when mockServerClient .when( request() .withMethod("GET") .withPath(calculatePath("some_pathRequest")) .withHeaders( header(not("requestHeaderNameOne"), not("requestHeaderValueOne")), header("requestHeaderNameTwo", "requestHeaderValueTwo") ) ) .respond( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body_response") ); // then // wrong query string header name assertEquals( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body_response"), makeRequest( request() .withMethod("GET") .withPath(calculatePath("some_pathRequest")) .withHeaders( header("OTHERrequestHeaderNameOne", "requestHeaderValueOne"), header("requestHeaderNameTwo", "requestHeaderValueTwo") ), headersToIgnore) ); // wrong query string header value assertEquals( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body_response"), makeRequest( request() .withMethod("GET") .withPath(calculatePath("some_pathRequest")) .withHeaders( header("requestHeaderNameOne", "OTHERrequestHeaderValueOne"), header("requestHeaderNameTwo", "requestHeaderValueTwo") ), headersToIgnore) ); } @Test public void shouldReturnResponseByNotMatchingHeaderWithNotOperatorForName() { // when mockServerClient .when( request() .withMethod("GET") .withPath(calculatePath("some_pathRequest")) .withHeaders( header(not("requestHeaderNameOne"), string("requestHeaderValueOne")), header("requestHeaderNameTwo", "requestHeaderValueTwo") ) ) .respond( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body_response") ); // then // wrong query string header name assertEquals( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body_response"), makeRequest( request() .withMethod("GET") .withPath(calculatePath("some_pathRequest")) .withHeaders( header("OTHERrequestHeaderNameOne", "requestHeaderValueOne"), header("requestHeaderNameTwo", "requestHeaderValueTwo") ), headersToIgnore) ); } @Test public void shouldReturnResponseByNotMatchingHeaderWithNotOperatorForValue() { // when mockServerClient .when( request() .withMethod("GET") .withPath(calculatePath("some_pathRequest")) .withHeaders( header(string("requestHeaderNameOne"), not("requestHeaderValueOne")), header("requestHeaderNameTwo", "requestHeaderValueTwo") ) ) .respond( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body_response") ); // then // wrong query string header value assertEquals( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body_response"), makeRequest( request() .withMethod("GET") .withPath(calculatePath("some_pathRequest")) .withHeaders( header("requestHeaderNameOne", "OTHERrequestHeaderValueOne"), header("requestHeaderNameTwo", "requestHeaderValueTwo") ), headersToIgnore) ); } @Test public void shouldNotReturnResponseForWhenTimeToLiveExpired() { // when mockServerClient .when( request().withPath(calculatePath("some_path")), exactly(2), TimeToLive.exactly(TimeUnit.SECONDS, 3L) ) .respond( response().withBody("some_body").withDelay(TimeUnit.SECONDS, 3L) ); // then assertEquals( response() .withStatusCode(OK_200.code()) .withBody("some_body"), makeRequest( request() .withPath(calculatePath("some_path")), headersToIgnore) ); // - in http assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()), makeRequest( request() .withPath(calculatePath("some_path")), headersToIgnore) ); // - in https assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()), makeRequest( request() .withSecure(true) .withPath(calculatePath("some_path")), headersToIgnore) ); } @Test public void shouldNotReturnResponseForNonMatchingBody() { // when mockServerClient .when( request() .withMethod("GET") .withPath(calculatePath("some_path")) .withQueryStringParameters( param("queryStringParameterOneName", "queryStringParameterOneValue"), param("queryStringParameterTwoName", "queryStringParameterTwoValue") ) .withBody(exact("some_body")) .withHeaders(header("headerName", "headerValue")) .withCookies(cookie("cookieName", "cookieValue")) ) .respond( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body") .withHeaders(header("headerName", "headerValue")) .withCookies(cookie("cookieName", "cookieValue")) ); // then // - in http assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()), makeRequest( request() .withMethod("GET") .withPath(calculatePath("some_path")) .withQueryStringParameters( param("queryStringParameterOneName", "queryStringParameterOneValue"), param("queryStringParameterTwoName", "queryStringParameterTwoValue") ) .withBody(exact("some_other_body")) .withHeaders(header("headerName", "headerValue")) .withCookies(cookie("cookieName", "cookieValue")), headersToIgnore) ); // - in https assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()), makeRequest( request() .withMethod("GET") .withSecure(true) .withPath(calculatePath("some_path")) .withQueryStringParameters( param("queryStringParameterOneName", "queryStringParameterOneValue"), param("queryStringParameterTwoName", "queryStringParameterTwoValue") ) .withBody(exact("some_other_body")) .withHeaders(header("headerName", "headerValue")) .withCookies(cookie("cookieName", "cookieValue")), headersToIgnore) ); } @Test public void shouldNotReturnResponseForMatchingBodyWithNotOperator() { // when mockServerClient .when( request() .withBody(Not.not(json("{" + NEW_LINE + " \"id\": 1," + NEW_LINE + " \"name\": \"A green door\"," + NEW_LINE + " \"price\": 12.50," + NEW_LINE + " \"tags\": [\"home\", \"green\"]" + NEW_LINE + "}"))), exactly(2) ) .respond( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body") ); // then // - in http assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()), makeRequest( request() .withPath(calculatePath("some_path")) .withMethod("POST") .withBody("{" + NEW_LINE + " \"id\": 1," + NEW_LINE + " \"extra_ignored_field\": \"some value\"," + NEW_LINE + " \"name\": \"A green door\"," + NEW_LINE + " \"price\": 12.50," + NEW_LINE + " \"tags\": [\"home\", \"green\"]" + NEW_LINE + "}"), headersToIgnore) ); // - in https assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()), makeRequest( request() .withSecure(true) .withPath(calculatePath("some_path")) .withMethod("POST") .withBody("{" + NEW_LINE + " \"id\": 1," + NEW_LINE + " \"extra_ignored_array\": [\"one\", \"two\"]," + NEW_LINE + " \"name\": \"A green door\"," + NEW_LINE + " \"price\": 12.50," + NEW_LINE + " \"tags\": [\"home\", \"green\"]" + NEW_LINE + "}"), headersToIgnore) ); } @Test public void shouldNotReturnResponseForNonMatchingXPathBody() { // when mockServerClient.when(request().withBody(new XPathBody("/bookstore/book[price>35]/price")), exactly(2)).respond(response().withBody("some_body")); // then // - in http assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()), makeRequest( request() .withSecure(true) .withPath(calculatePath("some_path")) .withMethod("POST") .withBody(new StringBody("" + "<?xml version=\"1.0\" encoding=\"ISO-8859-1\"?>" + NEW_LINE + "<bookstore>" + NEW_LINE + " <book category=\"COOKING\">" + NEW_LINE + " <title lang=\"en\">Everyday Italian</title>" + NEW_LINE + " <author>Giada De Laurentiis</author>" + NEW_LINE + " <year>2005</year>" + NEW_LINE + " <price>30.00</price>" + NEW_LINE + " </book>" + NEW_LINE + " <book category=\"CHILDREN\">" + NEW_LINE + " <title lang=\"en\">Harry Potter</title>" + NEW_LINE + " <author>J K. Rowling</author>" + NEW_LINE + " <year>2005</year>" + NEW_LINE + " <price>29.99</price>" + NEW_LINE + " </book>" + NEW_LINE + " <book category=\"WEB\">" + NEW_LINE + " <title lang=\"en\">Learning XML</title>" + NEW_LINE + " <author>Erik T. Ray</author>" + NEW_LINE + " <year>2003</year>" + NEW_LINE + " <price>31.95</price>" + NEW_LINE + " </book>" + NEW_LINE + "</bookstore>")), headersToIgnore) ); // - in https assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()), makeRequest( request() .withSecure(true) .withPath(calculatePath("some_path")) .withMethod("POST") .withBody(new StringBody("" + "<?xml version=\"1.0\" encoding=\"ISO-8859-1\"?>" + NEW_LINE + "<bookstore>" + NEW_LINE + " <book category=\"COOKING\">" + NEW_LINE + " <title lang=\"en\">Everyday Italian</title>" + NEW_LINE + " <author>Giada De Laurentiis</author>" + NEW_LINE + " <year>2005</year>" + NEW_LINE + " <price>30.00</price>" + NEW_LINE + " </book>" + NEW_LINE + " <book category=\"CHILDREN\">" + NEW_LINE + " <title lang=\"en\">Harry Potter</title>" + NEW_LINE + " <author>J K. Rowling</author>" + NEW_LINE + " <year>2005</year>" + NEW_LINE + " <price>29.99</price>" + NEW_LINE + " </book>" + NEW_LINE + " <book category=\"WEB\">" + NEW_LINE + " <title lang=\"en\">Learning XML</title>" + NEW_LINE + " <author>Erik T. Ray</author>" + NEW_LINE + " <year>2003</year>" + NEW_LINE + " <price>31.95</price>" + NEW_LINE + " </book>" + NEW_LINE + "</bookstore>")), headersToIgnore) ); } @Test public void shouldNotReturnResponseForNonMatchingXmlBody() { // when mockServerClient.when(request().withBody(xml("" + "<?xml version=\"1.0\" encoding=\"ISO-8859-1\"?>" + NEW_LINE + "<bookstore>" + NEW_LINE + " <book category=\"COOKING\" nationality=\"ITALIAN\">" + NEW_LINE + " <title lang=\"en\">Everyday Italian</title>" + NEW_LINE + " <author>Giada De Laurentiis</author>" + NEW_LINE + " <year>2005</year>" + NEW_LINE + " <price>30.00</price>" + NEW_LINE + " </book>" + NEW_LINE + "</bookstore>")), exactly(2)).respond(response().withBody("some_body")); // then // - in http assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()), makeRequest( request() .withSecure(true) .withPath(calculatePath("some_path")) .withMethod("POST") .withBody(new StringBody("" + "<?xml version=\"1.0\" encoding=\"ISO-8859-1\"?>" + NEW_LINE + "<bookstore>" + NEW_LINE + " <book category=\"COOKING\">" + NEW_LINE + " <title lang=\"en\">Everyday Italian</title>" + NEW_LINE + " <author>Giada De Laurentiis</author>" + NEW_LINE + " <year>2005</year>" + NEW_LINE + " <price>30.00</price>" + NEW_LINE + " </book>" + NEW_LINE + "</bookstore>")), headersToIgnore) ); // - in https assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()), makeRequest( request() .withSecure(true) .withPath(calculatePath("some_path")) .withMethod("POST") .withBody(new StringBody("" + "<?xml version=\"1.0\" encoding=\"ISO-8859-1\"?>" + NEW_LINE + "<bookstore>" + NEW_LINE + " <book category=\"COOKING\">" + NEW_LINE + " <title lang=\"en\">Everyday Italian</title>" + NEW_LINE + " <author>Giada De Laurentiis</author>" + NEW_LINE + " <year>2005</year>" + NEW_LINE + " <price>30.00</price>" + NEW_LINE + " </book>" + NEW_LINE + "</bookstore>")), headersToIgnore) ); } @Test public void shouldNotReturnResponseForNonMatchingJsonBody() { // when mockServerClient.when(request().withBody(json("{" + NEW_LINE + " \"id\": 1," + NEW_LINE + " \"name\": \"A green door\"," + NEW_LINE + " \"price\": 12.50," + NEW_LINE + " \"tags\": [\"home\", \"green\"]" + NEW_LINE + "}")), exactly(2)).respond(response().withBody("some_body")); // then // - in http assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()), makeRequest( request() .withPath(calculatePath("some_path")) .withMethod("POST") .withBody("{" + NEW_LINE + " \"id\": 1," + NEW_LINE + " \"name\": \"---- XXXX WRONG VALUE XXXX ----\"," + NEW_LINE + " \"price\": 12.50," + NEW_LINE + " \"tags\": [\"home\", \"green\"]" + NEW_LINE + "}"), headersToIgnore) ); // - in https assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()), makeRequest( request() .withSecure(true) .withPath(calculatePath("some_path")) .withMethod("POST") .withBody("{" + NEW_LINE + " \"id\": 1," + NEW_LINE + " \"name\": \"---- XXXX WRONG VALUE XXXX ----\"," + NEW_LINE + " \"price\": 12.50," + NEW_LINE + " \"tags\": [\"home\", \"green\"]" + NEW_LINE + "}"), headersToIgnore) ); } @Test public void shouldNotReturnResponseForNonMatchingJsonBodyWithMatchType() { // when mockServerClient .when( request() .withBody(json("{" + NEW_LINE + " \"id\": 1," + NEW_LINE + " \"name\": \"A green door\"," + NEW_LINE + " \"price\": 12.50," + NEW_LINE + " \"tags\": [\"home\", \"green\"]" + NEW_LINE + "}", MatchType.STRICT)), exactly(2)) .respond( response() .withBody("some_body") ); // then // - in http assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()), makeRequest( request() .withPath(calculatePath("some_path")) .withMethod("POST") .withBody("{" + NEW_LINE + " \"id\": 1," + NEW_LINE + " \"extra field\": \"some value\"," + NEW_LINE + " \"name\": \"A green door\"," + NEW_LINE + " \"price\": 12.50," + NEW_LINE + " \"tags\": [\"home\", \"green\"]" + NEW_LINE + "}"), headersToIgnore) ); // - in https assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()), makeRequest( request() .withSecure(true) .withPath(calculatePath("some_path")) .withMethod("POST") .withBody("{" + NEW_LINE + " \"id\": 1," + NEW_LINE + " \"extra field\": \"some value\"," + NEW_LINE + " \"name\": \"A green door\"," + NEW_LINE + " \"price\": 12.50," + NEW_LINE + " \"tags\": [\"home\", \"green\"]" + NEW_LINE + "}"), headersToIgnore) ); } @Test public void shouldNotReturnResponseForNonMatchingJsonSchema() { // when mockServerClient.when(request().withBody(jsonSchema("{" + NEW_LINE + " \"$schema\": \"http://json-schema.org/draft-04/schema#\"," + NEW_LINE + " \"title\": \"Product\"," + NEW_LINE + " \"description\": \"A product from Acme's catalog\"," + NEW_LINE + " \"type\": \"object\"," + NEW_LINE + " \"properties\": {" + NEW_LINE + " \"id\": {" + NEW_LINE + " \"description\": \"The unique identifier for a product\"," + NEW_LINE + " \"type\": \"integer\"" + NEW_LINE + " }," + NEW_LINE + " \"name\": {" + NEW_LINE + " \"description\": \"Name of the product\"," + NEW_LINE + " \"type\": \"string\"" + NEW_LINE + " }," + NEW_LINE + " \"price\": {" + NEW_LINE + " \"type\": \"number\"," + NEW_LINE + " \"minimum\": 0," + NEW_LINE + " \"exclusiveMinimum\": true" + NEW_LINE + " }," + NEW_LINE + " \"tags\": {" + NEW_LINE + " \"type\": \"array\"," + NEW_LINE + " \"items\": {" + NEW_LINE + " \"type\": \"string\"" + NEW_LINE + " }," + NEW_LINE + " \"minItems\": 1," + NEW_LINE + " \"uniqueItems\": true" + NEW_LINE + " }" + NEW_LINE + " }," + NEW_LINE + " \"required\": [\"id\", \"name\", \"price\"]" + NEW_LINE + "}")), exactly(2)).respond(response().withBody("some_body")); // then // - in http assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()), makeRequest( request() .withPath(calculatePath("some_path")) .withMethod("POST") .withBody("{" + NEW_LINE + " \"id\": 1," + NEW_LINE + " \"wrong field name\": \"A green door\"," + NEW_LINE + " \"price\": 12.50," + NEW_LINE + " \"tags\": [\"home\", \"green\"]" + NEW_LINE + "}"), headersToIgnore) ); // - in https assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()), makeRequest( request() .withSecure(true) .withPath(calculatePath("some_path")) .withMethod("POST") .withBody("{" + NEW_LINE + " \"id\": 1," + NEW_LINE + " \"name\": \"A green door\"," + NEW_LINE + " \"wrong field name\": 12.50," + NEW_LINE + " \"tags\": [\"home\", \"green\"]" + NEW_LINE + "}"), headersToIgnore) ); } @Test public void shouldNotReturnResponseForNonMatchingPath() { // when mockServerClient .when( request() .withMethod("GET") .withPath(calculatePath("some_path")) .withQueryStringParameters( param("queryStringParameterOneName", "queryStringParameterOneValue"), param("queryStringParameterTwoName", "queryStringParameterTwoValue") ) .withBody(exact("some_body")) .withHeaders(header("headerName", "headerValue")) .withCookies(cookie("cookieName", "cookieValue")) ) .respond( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body") .withHeaders(header("headerName", "headerValue")) .withCookies(cookie("cookieName", "cookieValue")) ); // then // - in http assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()), makeRequest( request() .withMethod("GET") .withPath(calculatePath("some_other_path")) .withQueryStringParameters( param("queryStringParameterOneName", "queryStringParameterOneValue"), param("queryStringParameterTwoName", "queryStringParameterTwoValue") ) .withBody(exact("some_body")) .withHeaders(header("headerName", "headerValue")) .withCookies(cookie("cookieName", "cookieValue")), headersToIgnore) ); // - in https assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()), makeRequest( request() .withMethod("GET") .withSecure(true) .withPath(calculatePath("some_other_path")) .withQueryStringParameters( param("queryStringParameterOneName", "queryStringParameterOneValue"), param("queryStringParameterTwoName", "queryStringParameterTwoValue") ) .withBody(exact("some_body")) .withHeaders(header("headerName", "headerValue")) .withCookies(cookie("cookieName", "cookieValue")), headersToIgnore) ); } @Test public void shouldNotReturnResponseForMatchingPathWithNotOperator() { // when mockServerClient .when( request() .withPath(not(calculatePath("some_path"))) ) .respond( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body_response") ); // then // - in http assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()), makeRequest( request() .withPath(calculatePath("some_path")), headersToIgnore) ); // - in https assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()), makeRequest( request() .withPath(calculatePath("some_path")), headersToIgnore) ); } @Test public void shouldNotReturnResponseForMatchingMethodWithNotOperator() { // when mockServerClient .when( request() .withMethod(not("GET")) ) .respond( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body_response") ); // then // - in http assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()), makeRequest( request() .withMethod("GET"), headersToIgnore) ); // - in https assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()), makeRequest( request() .withMethod("GET"), headersToIgnore) ); } @Test public void shouldNotReturnResponseForNonMatchingBodyParameterName() { // when mockServerClient .when( request() .withMethod("POST") .withPath(calculatePath("some_pathRequest")) .withBody(params( param("bodyParameterOneName", "Parameter One Value One", "Parameter One Value Two"), param("bodyParameterTwoName", "Parameter Two") )) ) .respond( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body_response") .withHeaders(header("headerNameResponse", "headerValueResponse")) .withCookies(cookie("cookieNameResponse", "cookieValueResponse")) ); // then // wrong query string parameter name assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()), makeRequest( request() .withMethod("POST") .withPath(calculatePath("some_pathRequest")) .withBody(params( param("OTHERBodyParameterOneName", "Parameter One Value One", "Parameter One Value Two"), param("bodyParameterTwoName", "Parameter Two") )) .withHeaders(header("headerNameRequest", "headerValueRequest")) .withCookies(cookie("cookieNameRequest", "cookieValueRequest")), headersToIgnore) ); // wrong query string parameter name assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()), makeRequest( request() .withMethod("POST") .withPath(calculatePath("some_pathRequest")) .withBody(new StringBody("OTHERBodyParameterOneName=Parameter+One+Value+One" + "&bodyParameterOneName=Parameter+One+Value+Two" + "&bodyParameterTwoName=Parameter+Two")) .withHeaders(header("headerNameRequest", "headerValueRequest")) .withCookies(cookie("cookieNameRequest", "cookieValueRequest")), headersToIgnore) ); } @Test public void shouldNotReturnResponseForMatchingBodyParameterWithNotOperator() { // when mockServerClient .when( request() .withMethod("POST") .withPath(calculatePath("some_pathRequest")) .withBody(params( param(not("bodyParameterOneName"), not("Parameter One Value One"), not("Parameter One Value Two")), param("bodyParameterTwoName", "Parameter Two") )) ) .respond( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body_response") ); // then // wrong query string parameter name assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()), makeRequest( request() .withMethod("POST") .withPath(calculatePath("some_pathRequest")) .withBody(params( param("bodyParameterOneName", "Parameter One Value One", "Parameter One Value Two"), param("bodyParameterTwoName", "Parameter Two") )) .withHeaders(header("headerNameRequest", "headerValueRequest")) .withCookies(cookie("cookieNameRequest", "cookieValueRequest")), headersToIgnore) ); // wrong query string parameter name assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()), makeRequest( request() .withMethod("POST") .withPath(calculatePath("some_pathRequest")) .withBody(new StringBody("bodyParameterOneName=Other Parameter+One+Value+One" + "&bodyParameterOneName=Parameter+One+Value+Two" + "&bodyParameterTwoName=Parameter+Two")) .withHeaders(header("headerNameRequest", "headerValueRequest")) .withCookies(cookie("cookieNameRequest", "cookieValueRequest")), headersToIgnore) ); } @Test public void shouldNotReturnResponseForNonMatchingBodyParameterValue() { // when mockServerClient .when( request() .withMethod("POST") .withPath(calculatePath("some_pathRequest")) .withBody(params( param("bodyParameterOneName", "Parameter One Value One", "Parameter One Value Two"), param("bodyParameterTwoName", "Parameter Two") )) ) .respond( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body_response") .withHeaders(header("headerNameResponse", "headerValueResponse")) .withCookies(cookie("cookieNameResponse", "cookieValueResponse")) ); // then // wrong body parameter value assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()), makeRequest( request() .withMethod("POST") .withPath(calculatePath("some_pathRequest")) .withBody(params( param("bodyParameterOneName", "Other Parameter One Value One", "Parameter One Value Two"), param("bodyParameterTwoName", "Parameter Two") )) .withHeaders(header("headerNameRequest", "headerValueRequest")) .withCookies(cookie("cookieNameRequest", "cookieValueRequest")), headersToIgnore) ); // wrong body parameter value assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()), makeRequest( request() .withMethod("POST") .withPath(calculatePath("some_pathRequest")) .withBody(new StringBody("bodyParameterOneName=Other Parameter+One+Value+One" + "&bodyParameterOneName=Parameter+One+Value+Two" + "&bodyParameterTwoName=Parameter+Two")) .withHeaders(header("headerNameRequest", "headerValueRequest")) .withCookies(cookie("cookieNameRequest", "cookieValueRequest")), headersToIgnore) ); } @Test public void shouldNotReturnResponseForNonMatchingQueryStringParameterName() { // when mockServerClient .when( request() .withMethod("POST") .withPath(calculatePath("some_pathRequest")) .withQueryStringParameters( param("queryStringParameterOneName", "queryStringParameterOneValueOne", "queryStringParameterOneValueTwo"), param("queryStringParameterTwoName", "queryStringParameterTwoValue") ) .withBody("some_bodyRequest") ) .respond( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body_response") .withHeaders(header("headerNameResponse", "headerValueResponse")) .withCookies(cookie("cookieNameResponse", "cookieValueResponse")) ); // then // wrong query string parameter name assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()), makeRequest( request() .withMethod("POST") .withPath(calculatePath("some_pathRequest")) .withQueryStringParameters( param("OTHERQueryStringParameterOneName", "queryStringParameterOneValueOne", "queryStringParameterOneValueTwo"), param("queryStringParameterTwoName", "queryStringParameterTwoValue") ) .withBody("some_bodyRequest") .withHeaders( header("headerNameRequest", "headerValueRequest") ) .withCookies(cookie("cookieNameRequest", "cookieValueRequest")), headersToIgnore) ); } @Test public void shouldNotReturnResponseForNonMatchingQueryStringParameterValue() { // when mockServerClient .when( request() .withMethod("POST") .withPath(calculatePath("some_pathRequest")) .withQueryStringParameters( param("queryStringParameterOneName", "queryStringParameterOneValueOne", "queryStringParameterOneValueTwo"), param("queryStringParameterTwoName", "queryStringParameterTwoValue") ) .withBody("some_bodyRequest") ) .respond( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body_response") .withHeaders(header("headerNameResponse", "headerValueResponse")) .withCookies(cookie("cookieNameResponse", "cookieValueResponse")) ); // then // wrong query string parameter value assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()), makeRequest( request() .withMethod("POST") .withPath(calculatePath("some_pathRequest")) .withQueryStringParameters( param("queryStringParameterOneName", "OTHERqueryStringParameterOneValueOne", "queryStringParameterOneValueTwo"), param("queryStringParameterTwoName", "queryStringParameterTwoValue") ) .withBody("some_bodyRequest") .withHeaders(header("headerNameRequest", "headerValueRequest")) .withCookies(cookie("cookieNameRequest", "cookieValueRequest")), headersToIgnore) ); } @Test public void shouldNotReturnResponseForMatchingQueryStringParameterWithNotOperator() { // when mockServerClient .when( request() .withMethod("POST") .withPath(calculatePath("some_pathRequest")) .withQueryStringParameters( param(not("queryStringParameterOneName"), not("Parameter One Value One"), not("Parameter One Value Two")), param("queryStringParameterTwoName", "Parameter Two") ) ) .respond( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body_response") ); // then // wrong query string parameter name assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()), makeRequest( request() .withMethod("POST") .withPath(calculatePath("some_pathRequest")) .withQueryStringParameters( param("queryStringParameterOneName", "Parameter One Value One", "Parameter One Value Two"), param("queryStringParameterTwoName", "Parameter Two") ), headersToIgnore) ); // wrong query string parameter name assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()), makeRequest( request() .withMethod("POST") .withPath(calculatePath("some_pathRequest")) .withQueryStringParameters( param("queryStringParameterOneName", "Parameter One Value One", "Parameter One Value Two"), param("queryStringParameterTwoName", "Parameter Two") ), headersToIgnore) ); } @Test public void shouldNotReturnResponseForNonMatchingCookieName() { // when mockServerClient .when( request() .withMethod("GET") .withPath(calculatePath("some_path")) .withQueryStringParameters( param("queryStringParameterOneName", "queryStringParameterOneValue"), param("queryStringParameterTwoName", "queryStringParameterTwoValue") ) .withBody(exact("some_body")) .withHeaders(header("headerName", "headerValue")) .withCookies(cookie("cookieName", "cookieValue")) ) .respond( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body") .withHeaders(header("headerName", "headerValue")) .withCookies(cookie("cookieName", "cookieValue")) ); // then // - in http assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()), makeRequest( request() .withMethod("GET") .withPath(calculatePath("some_path")) .withQueryStringParameters( param("queryStringParameterOneName", "queryStringParameterOneValue"), param("queryStringParameterTwoName", "queryStringParameterTwoValue") ) .withBody(exact("some_body")) .withHeaders(header("headerName", "headerValue")) .withCookies(cookie("cookieOtherName", "cookieValue")), headersToIgnore) ); // - in https assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()), makeRequest( request() .withMethod("GET") .withSecure(true) .withPath(calculatePath("some_path")) .withQueryStringParameters( param("queryStringParameterOneName", "queryStringParameterOneValue"), param("queryStringParameterTwoName", "queryStringParameterTwoValue") ) .withBody(exact("some_body")) .withHeaders(header("headerName", "headerValue")) .withCookies(cookie("cookieOtherName", "cookieValue")), headersToIgnore) ); } @Test public void shouldNotReturnResponseForNonMatchingCookieValue() { // when mockServerClient .when( request() .withMethod("GET") .withPath(calculatePath("some_path")) .withQueryStringParameters( param("queryStringParameterOneName", "queryStringParameterOneValue"), param("queryStringParameterTwoName", "queryStringParameterTwoValue") ) .withBody(exact("some_body")) .withHeaders(header("headerName", "headerValue")) .withCookies(cookie("cookieName", "cookieValue")) ) .respond( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body") .withHeaders(header("headerName", "headerValue")) .withCookies(cookie("cookieName", "cookieValue")) ); // then // - in http assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()), makeRequest( request() .withMethod("GET") .withPath(calculatePath("some_path")) .withQueryStringParameters( param("queryStringParameterOneName", "queryStringParameterOneValue"), param("queryStringParameterTwoName", "queryStringParameterTwoValue") ) .withBody(exact("some_body")) .withHeaders(header("headerName", "headerValue")) .withCookies(cookie("cookieName", "cookieOtherValue")), headersToIgnore) ); // - in https assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()), makeRequest( request() .withMethod("GET") .withSecure(true) .withPath(calculatePath("some_path")) .withQueryStringParameters( param("queryStringParameterOneName", "queryStringParameterOneValue"), param("queryStringParameterTwoName", "queryStringParameterTwoValue") ) .withBody(exact("some_body")) .withHeaders(header("headerName", "headerValue")) .withCookies(cookie("cookieName", "cookieOtherValue")), headersToIgnore) ); } @Test public void shouldNotReturnResponseForMatchingCookieWithNotOperator() { // when mockServerClient .when( request() .withMethod("GET") .withPath(calculatePath("some_pathRequest")) .withCookies( cookie(not("requestCookieNameOne"), not("requestCookieValueOne")), cookie("requestCookieNameTwo", "requestCookieValueTwo") ) ) .respond( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body_response") ); // then // wrong query string parameter name assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()), makeRequest( request() .withMethod("GET") .withPath(calculatePath("some_pathRequest")) .withCookies( cookie("requestCookieNameOne", "requestCookieValueOne"), cookie("requestCookieNameTwo", "requestCookieValueTwo") ), headersToIgnore) ); // wrong query string parameter name assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()), makeRequest( request() .withMethod("GET") .withPath(calculatePath("some_pathRequest")) .withCookies( cookie("requestCookieNameOne", "requestCookieValueOne"), cookie("requestCookieNameTwo", "requestCookieValueTwo") ), headersToIgnore) ); } @Test public void shouldNotReturnResponseForNonMatchingHeaderName() { // when mockServerClient .when( request() .withMethod("GET") .withPath(calculatePath("some_path")) .withQueryStringParameters( param("queryStringParameterOneName", "queryStringParameterOneValue"), param("queryStringParameterTwoName", "queryStringParameterTwoValue") ) .withBody(exact("some_body")) .withHeaders(header("headerName", "headerValue")) .withCookies(cookie("cookieName", "cookieValue")) ) .respond( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body") .withHeaders(header("headerName", "headerValue")) .withCookies(cookie("cookieName", "cookieValue")) ); // then // - in http assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()), makeRequest( request() .withMethod("GET") .withPath(calculatePath("some_path")) .withQueryStringParameters( param("queryStringParameterOneName", "queryStringParameterOneValue"), param("queryStringParameterTwoName", "queryStringParameterTwoValue") ) .withBody(exact("some_body")) .withHeaders(header("headerOtherName", "headerValue")) .withCookies(cookie("cookieName", "cookieValue")), headersToIgnore) ); // - in https assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()), makeRequest( request() .withMethod("GET") .withSecure(true) .withPath(calculatePath("some_path")) .withQueryStringParameters( param("queryStringParameterOneName", "queryStringParameterOneValue"), param("queryStringParameterTwoName", "queryStringParameterTwoValue") ) .withBody(exact("some_body")) .withHeaders(header("headerOtherName", "headerValue")) .withCookies(cookie("cookieName", "cookieValue")), headersToIgnore) ); } @Test public void shouldNotReturnResponseForNonMatchingHeaderValue() { // when mockServerClient .when( request() .withMethod("GET") .withPath(calculatePath("some_path")) .withQueryStringParameters( param("queryStringParameterOneName", "queryStringParameterOneValue"), param("queryStringParameterTwoName", "queryStringParameterTwoValue") ) .withBody(exact("some_body")) .withHeaders(header("headerName", "headerValue")) .withCookies(cookie("cookieName", "cookieValue")) ) .respond( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body") .withHeaders(header("headerName", "headerValue")) .withCookies(cookie("cookieName", "cookieValue")) ); // then // - in http assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()), makeRequest( request() .withMethod("GET") .withPath(calculatePath("some_path")) .withQueryStringParameters( param("queryStringParameterOneName", "queryStringParameterOneValue"), param("queryStringParameterTwoName", "queryStringParameterTwoValue") ) .withBody(exact("some_body")) .withHeaders(header("headerName", "headerOtherValue")) .withCookies(cookie("cookieName", "cookieValue")), headersToIgnore) ); // - in https assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()), makeRequest( request() .withMethod("GET") .withSecure(true) .withPath(calculatePath("some_path")) .withQueryStringParameters( param("queryStringParameterOneName", "queryStringParameterOneValue"), param("queryStringParameterTwoName", "queryStringParameterTwoValue") ) .withBody(exact("some_body")) .withHeaders(header("headerName", "headerOtherValue")) .withCookies(cookie("cookieName", "cookieValue")), headersToIgnore) ); } @Test public void shouldNotReturnResponseForMatchingHeaderWithNotOperator() { // when mockServerClient .when( request() .withMethod("GET") .withPath(calculatePath("some_pathRequest")) .withHeaders( header(not("requestHeaderNameOne"), not("requestHeaderValueOne")), header("requestHeaderNameTwo", "requestHeaderValueTwo") ) ) .respond( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body_response") ); // then // wrong query string parameter name assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()), makeRequest( request() .withMethod("GET") .withPath(calculatePath("some_pathRequest")) .withHeaders( header("requestHeaderNameOne", "requestHeaderValueOne"), header("requestHeaderNameTwo", "requestHeaderValueTwo") ), headersToIgnore) ); // wrong query string parameter name assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()), makeRequest( request() .withMethod("GET") .withPath(calculatePath("some_pathRequest")) .withHeaders( header("requestHeaderNameOne", "requestHeaderValueOne"), header("requestHeaderNameTwo", "requestHeaderValueTwo") ), headersToIgnore) ); } @Test public void shouldVerifyReceivedRequests() { // when mockServerClient .when( request() .withPath(calculatePath("some_path")), exactly(2) ) .respond( response() .withBody("some_body") ); // then // - in http assertEquals( response() .withStatusCode(OK_200.code()) .withBody("some_body"), makeRequest( request() .withPath(calculatePath("some_path")), headersToIgnore) ); mockServerClient.verify(request() .withPath(calculatePath("some_path"))); mockServerClient.verify(request() .withPath(calculatePath("some_path")), VerificationTimes.exactly(1)); // - in https assertEquals( response() .withStatusCode(OK_200.code()) .withBody("some_body"), makeRequest( request() .withSecure(true) .withPath(calculatePath("some_path")), headersToIgnore) ); mockServerClient.verify(request().withPath(calculatePath("some_path")), VerificationTimes.atLeast(1)); mockServerClient.verify(request().withPath(calculatePath("some_path")), VerificationTimes.exactly(2)); } @Test public void shouldVerifyReceivedRequestInSsl() { // when mockServerClient .when( request() .withPath(calculatePath("some.*path")), exactly(2) ) .respond( response() .withBody("some_body") ); // then // - in http assertEquals( response() .withStatusCode(OK_200.code()) .withBody("some_body"), makeRequest( request() .withPath(calculatePath("some_path")), headersToIgnore) ); mockServerClient.verify(request() .withPath(calculatePath("some_path")) .withSecure(false)); mockServerClient.verify(request() .withPath(calculatePath("some_path")) .withSecure(false), VerificationTimes.exactly(1)); // - in https assertEquals( response() .withStatusCode(OK_200.code()) .withBody("some_body"), makeRequest( request() .withPath(calculatePath("some_secure_path")) .withSecure(true), headersToIgnore) ); mockServerClient.verify(request() .withPath(calculatePath("some_secure_path")) .withSecure(true)); mockServerClient.verify(request() .withPath(calculatePath("some_secure_path")) .withSecure(true), VerificationTimes.exactly(1)); } @Test public void shouldVerifyReceivedRequestsWithRegexBody() { // when mockServerClient .when( request() .withMethod("POST") .withPath(calculatePath("some_path")) .withBody("{type: 'some_random_type', value: 'some_random_value'}"), exactly(2) ) .respond( response() .withBody("some_response") ); // then // - in http assertEquals( response() .withStatusCode(OK_200.code()) .withBody("some_response"), makeRequest( request() .withMethod("POST") .withPath(calculatePath("some_path")) .withBody("{type: 'some_random_type', value: 'some_random_value'}"), headersToIgnore) ); mockServerClient.verify( request() .withBody(regex("\\{type\\: \\'some_random_type\\'\\, value\\: \\'some_random_value\\'\\}")) ); mockServerClient.verify( request() .withBody(regex("\\{type\\: \\'some_random_type\\'\\, value\\: \\'some_random_value\\'\\}")), VerificationTimes.exactly(1) ); // - in https assertEquals( response() .withStatusCode(OK_200.code()) .withBody("some_response"), makeRequest( request() .withSecure(true) .withMethod("POST") .withPath(calculatePath("some_path")) .withBody("{type: 'some_random_type', value: 'some_random_value'}"), headersToIgnore) ); mockServerClient.verify( request() .withSecure(true) .withBody(regex("\\{type\\: \\'some_random_type\\'\\, value\\: \\'some_random_value\\'\\}")) ); mockServerClient.verify( request() .withSecure(true) .withBody(regex("\\{type\\: \\'some_random_type\\'\\, value\\: \\'some_random_value\\'\\}")), VerificationTimes.atLeast(1) ); } @Test public void shouldVerifyReceivedRequestsWithNoBody() { // when mockServerClient.when(request().withPath(calculatePath("some_path")), exactly(2)).respond(response()); // then // - in http assertEquals( response() .withStatusCode(OK_200.code()), makeRequest( request() .withPath(calculatePath("some_path")), headersToIgnore) ); mockServerClient.verify(request() .withPath(calculatePath("some_path"))); mockServerClient.verify(request() .withPath(calculatePath("some_path")), VerificationTimes.exactly(1)); } @Test public void shouldVerifyNotEnoughRequestsReceived() { // when mockServerClient.when(request().withPath(calculatePath("some_path")), exactly(2)).respond(response().withBody("some_body")); // then assertEquals( response() .withStatusCode(OK_200.code()) .withBody("some_body"), makeRequest( request() .withPath(calculatePath("some_path")), headersToIgnore) ); try { mockServerClient.verify(request() .withPath(calculatePath("some_path")), VerificationTimes.atLeast(2)); fail(); } catch (AssertionError ae) { assertThat(ae.getMessage(), startsWith("Request not found at least 2 times, expected:<{" + NEW_LINE + " \"path\" : \"" + calculatePath("some_path") + "\"" + NEW_LINE + "}> but was:<{" + NEW_LINE + " \"method\" : \"GET\"," + NEW_LINE + " \"path\" : \"" + calculatePath("some_path") + "\"," + NEW_LINE)); } } @Test public void shouldVerifyTooManyRequestsReceived() { // when mockServerClient.when(request().withPath(calculatePath("some_path")), exactly(2)).respond(response().withBody("some_body")); // then assertEquals( response() .withStatusCode(OK_200.code()) .withBody("some_body"), makeRequest( request() .withPath(calculatePath("some_path")), headersToIgnore) ); try { mockServerClient.verify(request() .withPath(calculatePath("some_path")), VerificationTimes.exactly(0)); fail(); } catch (AssertionError ae) { assertThat(ae.getMessage(), startsWith("Request not found exactly 0 times, expected:<{" + NEW_LINE + " \"path\" : \"" + calculatePath("some_path") + "\"" + NEW_LINE + "}> but was:<{" + NEW_LINE + " \"method\" : \"GET\"," + NEW_LINE + " \"path\" : \"" + calculatePath("some_path") + "\"," + NEW_LINE)); } } @Test public void shouldVerifyNoMatchingRequestsReceived() { // when mockServerClient.when(request().withPath(calculatePath("some_path")), exactly(2)).respond(response().withBody("some_body")); // then assertEquals( response() .withStatusCode(OK_200.code()) .withBody("some_body"), makeRequest( request() .withPath(calculatePath("some_path")), headersToIgnore) ); try { mockServerClient.verify(request() .withPath(calculatePath("some_other_path")), VerificationTimes.exactly(2)); fail(); } catch (AssertionError ae) { assertThat(ae.getMessage(), startsWith("Request not found exactly 2 times, expected:<{" + NEW_LINE + " \"path\" : \"" + calculatePath("some_other_path") + "\"" + NEW_LINE + "}> but was:<{" + NEW_LINE + " \"method\" : \"GET\"," + NEW_LINE + " \"path\" : \"" + calculatePath("some_path") + "\"," + NEW_LINE)); } } @Test public void shouldVerifyNoRequestsReceived() { // when mockServerClient.reset(); // then mockServerClient.verifyZeroInteractions(); } @Test public void shouldNotVerifyNoRequestsReceived() { // when mockServerClient.when(request().withPath(calculatePath("some_path")), exactly(2)).respond(response().withBody("some_body")); // then assertEquals( response() .withStatusCode(OK_200.code()) .withBody("some_body"), makeRequest( request() .withPath(calculatePath("some_path")), headersToIgnore) ); try { mockServerClient.verifyZeroInteractions(); fail(); } catch (AssertionError ae) { assertThat(ae.getMessage(), startsWith("Request not found exactly 0 times, expected:<{ }> but was:<{" + NEW_LINE + " \"method\" : \"GET\"," + NEW_LINE + " \"path\" : \"" + calculatePath("some_path") + "\"," + NEW_LINE)); } } @Test public void shouldVerifyNoMatchingRequestsReceivedInSsl() { // when mockServerClient.when(request().withPath(calculatePath("some.*path")), exactly(2)).respond(response().withBody("some_body")); // then // - in http assertEquals( response() .withStatusCode(OK_200.code()) .withBody("some_body"), makeRequest( request() .withPath(calculatePath("some_path")), headersToIgnore) ); try { mockServerClient.verify( request() .withPath(calculatePath("some_path")) .withSecure(true), VerificationTimes.atLeast(1) ); fail(); } catch (AssertionError ae) { assertThat(ae.getMessage(), startsWith("Request not found at least once, expected:<{" + NEW_LINE + " \"path\" : \"" + calculatePath("some_path") + "\"," + NEW_LINE + " \"secure\" : true" + NEW_LINE + "}> but was:<{" + NEW_LINE + " \"method\" : \"GET\"," + NEW_LINE + " \"path\" : \"" + calculatePath("some_path") + "\"," + NEW_LINE)); } // - in https assertEquals( response() .withStatusCode(OK_200.code()) .withBody("some_body"), makeRequest( request() .withPath(calculatePath("some_secure_path")) .withSecure(true), headersToIgnore) ); try { mockServerClient.verify( request() .withPath(calculatePath("some_secure_path")) .withSecure(false), VerificationTimes.atLeast(1) ); fail(); } catch (AssertionError ae) { assertThat(ae.getMessage(), startsWith("Request not found at least once, expected:<{" + NEW_LINE + " \"path\" : \"" + calculatePath("some_secure_path") + "\"," + NEW_LINE + " \"secure\" : false" + NEW_LINE + "}> but was:<[ {" + NEW_LINE + " \"method\" : \"GET\"," + NEW_LINE + " \"path\" : \"" + calculatePath("some_path") + "\"," + NEW_LINE)); } } @Test public void shouldVerifySequenceOfRequestsReceived() { // when mockServerClient.when(request().withPath(calculatePath("some_path.*")), exactly(6)).respond(response().withBody("some_body")); // then assertEquals( response("some_body"), makeRequest( request().withPath(calculatePath("some_path_one")), headersToIgnore) ); assertEquals( response("some_body"), makeRequest( request().withPath(calculatePath("some_path_two")), headersToIgnore) ); assertEquals( response("some_body"), makeRequest( request().withPath(calculatePath("some_path_three")), headersToIgnore) ); mockServerClient.verify(request(calculatePath("some_path_one")), request(calculatePath("some_path_three"))); mockServerClient.verify(request(calculatePath("some_path_one")), request(calculatePath("some_path_two"))); mockServerClient.verify(request(calculatePath("some_path_one")), request(calculatePath("some_path_two")), request(calculatePath("some_path_three"))); } @Test public void shouldVerifySequenceOfRequestsReceivedIncludingThoseNotMatchingAnException() { // when mockServerClient.when(request().withPath(calculatePath("some_path.*")), exactly(4)).respond(response().withBody("some_body")); // then assertEquals( response("some_body"), makeRequest( request().withPath(calculatePath("some_path_one")), headersToIgnore) ); assertEquals( notFoundResponse(), makeRequest( request().withPath(calculatePath("not_found")), headersToIgnore) ); assertEquals( response("some_body"), makeRequest( request().withPath(calculatePath("some_path_three")), headersToIgnore) ); mockServerClient.verify(request(calculatePath("some_path_one")), request(calculatePath("some_path_three"))); mockServerClient.verify(request(calculatePath("some_path_one")), request(calculatePath("not_found"))); mockServerClient.verify(request(calculatePath("some_path_one")), request(calculatePath("not_found")), request(calculatePath("some_path_three"))); mockServerClient.verify(request(calculatePath("some_path_one")), request(calculatePath("not_found")), request(calculatePath("some_path_three"))); } @Test public void shouldRetrieveSequenceOfRequestsReceivedIncludingThoseNotMatchingAnException() { // when mockServerClient.when(request().withPath(calculatePath("some_path.*")), exactly(4)).respond(response().withBody("some_body")); assertEquals( response("some_body"), makeRequest( request().withPath(calculatePath("some_path_one")), headersToIgnore) ); assertEquals( notFoundResponse(), makeRequest( request().withPath(calculatePath("not_found")), headersToIgnore) ); assertEquals( response("some_body"), makeRequest( request().withPath(calculatePath("some_path_three")), headersToIgnore) ); // then verifyRequestMatches( mockServerClient.retrieveRecordedRequests(request().withPath(calculatePath("some_path.*"))), request(calculatePath("some_path_one")), request(calculatePath("some_path_three")) ); verifyRequestMatches( mockServerClient.retrieveRecordedRequests(request()), request(calculatePath("some_path_one")), request(calculatePath("not_found")), request(calculatePath("some_path_three")) ); verifyRequestMatches( mockServerClient.retrieveRecordedRequests(null), request(calculatePath("some_path_one")), request(calculatePath("not_found")), request(calculatePath("some_path_three")) ); } @Test public void shouldRetrieveSequenceOfExpectationsSetup() { // when mockServerClient.when(request().withPath(calculatePath("some_path.*")), exactly(4)) .respond(response().withBody("some_body")); mockServerClient.when(request().withPath(calculatePath("some_path.*"))) .respond(response().withBody("some_body")); mockServerClient.when(request().withPath(calculatePath("some_other_path"))) .respond(response().withBody("some_other_body")); mockServerClient.when(request().withPath(calculatePath("some_forward_path"))) .forward(forward()); // then assertThat( mockServerClient.retrieveExistingExpectations(request().withPath(calculatePath("some_path.*"))), arrayContaining( new Expectation(request().withPath(calculatePath("some_path.*")), exactly(4), TimeToLive.unlimited()) .thenRespond(response().withBody("some_body")), expectation(request().withPath(calculatePath("some_path.*"))) .thenRespond(response().withBody("some_body")) ) ); assertThat( mockServerClient.retrieveExistingExpectations(null), arrayContaining( new Expectation(request().withPath(calculatePath("some_path.*")), exactly(4), TimeToLive.unlimited()) .thenRespond(response().withBody("some_body")), expectation(request().withPath(calculatePath("some_path.*"))) .thenRespond(response().withBody("some_body")), expectation(request().withPath(calculatePath("some_other_path"))) .thenRespond(response().withBody("some_other_body")), expectation(request().withPath(calculatePath("some_forward_path"))) .thenForward(forward()) ) ); assertThat( mockServerClient.retrieveExistingExpectations(request()), arrayContaining( new Expectation(request().withPath(calculatePath("some_path.*")), exactly(4), TimeToLive.unlimited()) .thenRespond(response().withBody("some_body")), expectation(request().withPath(calculatePath("some_path.*"))) .thenRespond(response().withBody("some_body")), expectation(request().withPath(calculatePath("some_other_path"))) .thenRespond(response().withBody("some_other_body")), expectation(request().withPath(calculatePath("some_forward_path"))) .thenForward(forward()) ) ); } @Test public void shouldVerifySequenceOfRequestsNotReceived() { // when mockServerClient.when(request().withPath(calculatePath("some_path.*")), exactly(6)).respond(response().withBody("some_body")); // then assertEquals( response("some_body"), makeRequest( request().withPath(calculatePath("some_path_one")), headersToIgnore) ); assertEquals( response("some_body"), makeRequest( request().withPath(calculatePath("some_path_two")), headersToIgnore) ); assertEquals( response("some_body"), makeRequest( request().withPath(calculatePath("some_path_three")), headersToIgnore) ); try { mockServerClient.verify(request(calculatePath("some_path_two")), request(calculatePath("some_path_one"))); fail(); } catch (AssertionError ae) { assertThat(ae.getMessage(), startsWith("Request sequence not found, expected:<[ {" + NEW_LINE + " \"path\" : \"" + calculatePath("some_path_two") + "\"" + NEW_LINE + "}, {" + NEW_LINE + " \"path\" : \"" + calculatePath("some_path_one") + "\"" + NEW_LINE + "} ]> but was:<[ {" + NEW_LINE + " \"method\" : \"GET\"," + NEW_LINE + " \"path\" : \"" + calculatePath("some_path_one") + "\"," + NEW_LINE)); } try { mockServerClient.verify(request(calculatePath("some_path_three")), request(calculatePath("some_path_two"))); fail(); } catch (AssertionError ae) { assertThat(ae.getMessage(), startsWith("Request sequence not found, expected:<[ {" + NEW_LINE + " \"path\" : \"" + calculatePath("some_path_three") + "\"" + NEW_LINE + "}, {" + NEW_LINE + " \"path\" : \"" + calculatePath("some_path_two") + "\"" + NEW_LINE + "} ]> but was:<[ {" + NEW_LINE + " \"method\" : \"GET\"," + NEW_LINE + " \"path\" : \"" + calculatePath("some_path_one") + "\"," + NEW_LINE)); } try { mockServerClient.verify(request(calculatePath("some_path_four"))); fail(); } catch (AssertionError ae) { assertThat(ae.getMessage(), startsWith("Request sequence not found, expected:<[ {" + NEW_LINE + " \"path\" : \"" + calculatePath("some_path_four") + "\"" + NEW_LINE + "} ]> but was:<[ {" + NEW_LINE + " \"method\" : \"GET\"," + NEW_LINE + " \"path\" : \"" + calculatePath("some_path_one") + "\"," + NEW_LINE)); } } @Test public void shouldClearExpectationsAndLogs() { // given - some expectations mockServerClient .when( request() .withPath(calculatePath("some_path1")) ) .respond( response() .withBody("some_body1") ); mockServerClient .when( request() .withPath(calculatePath("some_path2")) ) .respond( response() .withBody("some_body2") ); // and - some matching requests assertEquals( response() .withStatusCode(OK_200.code()) .withBody("some_body1"), makeRequest( request() .withPath(calculatePath("some_path1")), headersToIgnore) ); assertEquals( response() .withStatusCode(OK_200.code()) .withBody("some_body2"), makeRequest( request() .withPath(calculatePath("some_path2")), headersToIgnore) ); // when mockServerClient .clear( request() .withPath(calculatePath("some_path1")) ); // then - expectations cleared assertThat( mockServerClient.retrieveExistingExpectations(null), arrayContaining( expectation( request() .withPath(calculatePath("some_path2")) ) .thenRespond( response() .withBody("some_body2") ) ) ); // and then - request log cleared verifyRequestMatches( mockServerClient.retrieveRecordedRequests(null), request(calculatePath("some_path2")) ); // and then - remaining expectations not cleared assertEquals( response() .withStatusCode(OK_200.code()) .withBody("some_body2"), makeRequest( request() .withPath(calculatePath("some_path2")), headersToIgnore) ); assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()), makeRequest( request() .withPath(calculatePath("some_path1")), headersToIgnore) ); } @Test public void shouldClearExpectationsOnly() { // given - some expectations mockServerClient .when( request() .withPath(calculatePath("some_path1")) ) .respond( response() .withBody("some_body1") ); mockServerClient .when( request() .withPath(calculatePath("some_path2")) ) .respond( response() .withBody("some_body2") ); // and - some matching requests assertEquals( response() .withStatusCode(OK_200.code()) .withBody("some_body1"), makeRequest( request() .withPath(calculatePath("some_path1")), headersToIgnore) ); assertEquals( response() .withStatusCode(OK_200.code()) .withBody("some_body2"), makeRequest( request() .withPath(calculatePath("some_path2")), headersToIgnore) ); // when mockServerClient .clear( request() .withPath(calculatePath("some_path1")), MockServerClient.TYPE.EXPECTATION ); // then - expectations cleared assertThat( mockServerClient.retrieveExistingExpectations(null), arrayContaining( expectation( request() .withPath(calculatePath("some_path2")) ) .thenRespond( response() .withBody("some_body2") ) ) ); // and then - request log not cleared verifyRequestMatches( mockServerClient.retrieveRecordedRequests(null), request(calculatePath("some_path1")), request(calculatePath("some_path2")) ); } @Test public void shouldClearLogsOnly() { // given - some expectations mockServerClient .when( request() .withPath(calculatePath("some_path1")) ) .respond( response() .withBody("some_body1") ); mockServerClient .when( request() .withPath(calculatePath("some_path2")) ) .respond( response() .withBody("some_body2") ); // and - some matching requests assertEquals( response() .withStatusCode(OK_200.code()) .withBody("some_body1"), makeRequest( request() .withPath(calculatePath("some_path1")), headersToIgnore) ); assertEquals( response() .withStatusCode(OK_200.code()) .withBody("some_body2"), makeRequest( request() .withPath(calculatePath("some_path2")), headersToIgnore) ); // when mockServerClient .clear( request() .withPath(calculatePath("some_path1")), MockServerClient.TYPE.LOG ); // then - expectations cleared assertThat( mockServerClient.retrieveExistingExpectations(null), arrayContaining( expectation( request() .withPath(calculatePath("some_path1")) ) .thenRespond( response() .withBody("some_body1") ), expectation( request() .withPath(calculatePath("some_path2")) ) .thenRespond( response() .withBody("some_body2") ) ) ); // and then - request log cleared verifyRequestMatches( mockServerClient.retrieveRecordedRequests(null), request(calculatePath("some_path2")) ); } @Test public void shouldClearAllExpectationsWithNull() { // given mockServerClient .when( request() .withPath(calculatePath("some_path1")) ) .respond( response() .withBody("some_body1") ); mockServerClient .when( request() .withPath(calculatePath("some_path2")) ) .respond( response() .withBody("some_body2") ); assertEquals( response() .withStatusCode(OK_200.code()) .withBody("some_body2"), makeRequest( request() .withPath(calculatePath("some_path2")), headersToIgnore) ); // when mockServerClient.clear(null); // then assertThat(mockServerClient.retrieveExistingExpectations(null), emptyArray()); assertThat(mockServerClient.retrieveRecordedRequests(null), emptyArray()); } @Test public void shouldClearAllExpectationsWithEmptyRequest() { // given mockServerClient .when( request() .withPath(calculatePath("some_path1")) ) .respond( response() .withBody("some_body1") ); mockServerClient .when( request() .withPath(calculatePath("some_path2")) ) .respond( response() .withBody("some_body2") ); assertEquals( response() .withStatusCode(OK_200.code()) .withBody("some_body2"), makeRequest( request() .withPath(calculatePath("some_path2")), headersToIgnore) ); // when mockServerClient.clear(request()); // then assertThat(mockServerClient.retrieveExistingExpectations(null), emptyArray()); assertThat(mockServerClient.retrieveRecordedRequests(null), emptyArray()); } @Test public void shouldClearExpectationsWithXPathBody() { // given mockServerClient .when( request() .withBody(xpath("/bookstore/book[year=2005]/price")) ) .respond( response() .withBody("some_body1") ); mockServerClient .when( request() .withBody(xpath("/bookstore/book[year=2006]/price")) ) .respond( response() .withBody("some_body2") ); // and StringBody xmlBody = new StringBody("" + "<?xml version=\"1.0\" encoding=\"ISO-8859-1\"?>" + NEW_LINE + "<bookstore>" + NEW_LINE + " <book category=\"COOKING\">" + NEW_LINE + " <title lang=\"en\">Everyday Italian</title>" + NEW_LINE + " <author>Giada De Laurentiis</author>" + NEW_LINE + " <year>2005</year>" + NEW_LINE + " <price>30.00</price>" + NEW_LINE + " </book>" + NEW_LINE + " <book category=\"CHILDREN\">" + NEW_LINE + " <title lang=\"en\">Harry Potter</title>" + NEW_LINE + " <author>J K. Rowling</author>" + NEW_LINE + " <year>2006</year>" + NEW_LINE + " <price>29.99</price>" + NEW_LINE + " </book>" + NEW_LINE + " <book category=\"WEB\">" + NEW_LINE + " <title lang=\"en\">Learning XML</title>" + NEW_LINE + " <author>Erik T. Ray</author>" + NEW_LINE + " <year>2003</year>" + NEW_LINE + " <price>31.95</price>" + NEW_LINE + " </book>" + NEW_LINE + "</bookstore>"); // then assertEquals( response() .withStatusCode(OK_200.code()) .withBody("some_body1"), makeRequest( request() .withBody(xmlBody), headersToIgnore) ); // when mockServerClient .clear( request() .withBody(xpath("/bookstore/book[year=2005]/price")) ); // then assertThat( mockServerClient.retrieveExistingExpectations(null), arrayContaining( expectation( request() .withBody(xpath("/bookstore/book[year=2006]/price")) ) .thenRespond( response() .withBody("some_body2") ) ) ); // - in http assertEquals( response() .withStatusCode(OK_200.code()) .withBody("some_body2"), makeRequest( request() .withBody(xmlBody), headersToIgnore) ); // - in https assertEquals( response() .withStatusCode(OK_200.code()) .withBody("some_body2"), makeRequest( request() .withSecure(true) .withBody(xmlBody), headersToIgnore) ); } @Test public void shouldClearExpectationsWithJsonSchemaBody() { // given JsonSchemaBody jsonSchemaBodyOne = jsonSchema("{" + NEW_LINE + " \"$schema\": \"http://json-schema.org/draft-04/schema#\"," + NEW_LINE + " \"title\": \"Product\"," + NEW_LINE + " \"description\": \"A product from Acme's catalog\"," + NEW_LINE + " \"type\": \"object\"," + NEW_LINE + " \"properties\": {" + NEW_LINE + " \"id\": {" + NEW_LINE + " \"description\": \"The unique identifier for a product\"," + NEW_LINE + " \"type\": \"integer\"" + NEW_LINE + " }," + NEW_LINE + " \"name\": {" + NEW_LINE + " \"description\": \"Name of the product\"," + NEW_LINE + " \"type\": \"string\"" + NEW_LINE + " }," + NEW_LINE + " \"price\": {" + NEW_LINE + " \"type\": \"number\"," + NEW_LINE + " \"minimum\": 0," + NEW_LINE + " \"exclusiveMinimum\": true" + NEW_LINE + " }," + NEW_LINE + " \"tags\": {" + NEW_LINE + " \"type\": \"array\"," + NEW_LINE + " \"items\": {" + NEW_LINE + " \"type\": \"string\"" + NEW_LINE + " }," + NEW_LINE + " \"minItems\": 1," + NEW_LINE + " \"uniqueItems\": true" + NEW_LINE + " }" + NEW_LINE + " }," + NEW_LINE + " \"required\": [\"id\", \"name\", \"price\"]" + NEW_LINE + "}"); JsonSchemaBody jsonSchemaBodyTwo = jsonSchema("{" + NEW_LINE + " \"$schema\": \"http://json-schema.org/draft-04/schema#\"," + NEW_LINE + " \"title\": \"Product\"," + NEW_LINE + " \"description\": \"A product from Acme's catalog\"," + NEW_LINE + " \"type\": \"object\"," + NEW_LINE + " \"properties\": {" + NEW_LINE + " \"id\": {" + NEW_LINE + " \"description\": \"The unique identifier for a product\"," + NEW_LINE + " \"type\": \"integer\"" + NEW_LINE + " }," + NEW_LINE + " \"name\": {" + NEW_LINE + " \"description\": \"Name of the product\"," + NEW_LINE + " \"type\": \"string\"" + NEW_LINE + " }," + NEW_LINE + " \"price\": {" + NEW_LINE + " \"type\": \"number\"," + NEW_LINE + " \"minimum\": 10," + NEW_LINE + " \"exclusiveMinimum\": true" + NEW_LINE + " }," + NEW_LINE + " \"tags\": {" + NEW_LINE + " \"type\": \"array\"," + NEW_LINE + " \"items\": {" + NEW_LINE + " \"type\": \"string\"" + NEW_LINE + " }," + NEW_LINE + " \"minItems\": 1," + NEW_LINE + " \"uniqueItems\": true" + NEW_LINE + " }" + NEW_LINE + " }," + NEW_LINE + " \"required\": [\"id\", \"name\", \"price\"]" + NEW_LINE + "}"); mockServerClient .when( request() .withBody(jsonSchemaBodyOne) ) .respond( response() .withBody("some_body1") ); mockServerClient .when( request() .withBody(jsonSchemaBodyTwo) ) .respond( response() .withBody("some_body2") ); // then assertEquals( response() .withStatusCode(OK_200.code()) .withBody("some_body1"), makeRequest( request() .withBody("{" + NEW_LINE + " \"id\": 1," + NEW_LINE + " \"name\": \"A green door\"," + NEW_LINE + " \"price\": 12.50," + NEW_LINE + " \"tags\": [\"home\", \"green\"]" + NEW_LINE + "}"), headersToIgnore) ); // when mockServerClient .clear( request() .withBody(jsonSchemaBodyOne) ); // then assertThat( mockServerClient.retrieveExistingExpectations(null), arrayContaining( expectation( request() .withBody(jsonSchemaBodyTwo) ) .thenRespond( response() .withBody("some_body2") ) ) ); // - in http assertEquals( response() .withStatusCode(OK_200.code()) .withBody("some_body2"), makeRequest( request() .withBody("{" + NEW_LINE + " \"id\": 1," + NEW_LINE + " \"name\": \"A green door\"," + NEW_LINE + " \"price\": 12.50," + NEW_LINE + " \"tags\": [\"home\", \"green\"]" + NEW_LINE + "}"), headersToIgnore) ); // - in https assertEquals( response() .withStatusCode(OK_200.code()) .withBody("some_body2"), makeRequest( request() .withSecure(true) .withBody("{" + NEW_LINE + " \"id\": 1," + NEW_LINE + " \"name\": \"A green door\"," + NEW_LINE + " \"price\": 12.50," + NEW_LINE + " \"tags\": [\"home\", \"green\"]" + NEW_LINE + "}"), headersToIgnore) ); } @Test public void shouldClearExpectationsWithParameterBody() { // given mockServerClient .when( request() .withBody(params(param("bodyParameterNameOne", "bodyParameterValueOne"))) ) .respond( response() .withBody("some_body1") ); mockServerClient .when( request() .withBody(params(param("bodyParameterNameTwo", "bodyParameterValueTwo"))) ) .respond( response() .withBody("some_body2") ); // then assertEquals( response() .withStatusCode(OK_200.code()) .withBody("some_body1"), makeRequest( request() .withBody(params(param("bodyParameterName.*", "bodyParameterValue.*"))), headersToIgnore) ); // when mockServerClient .clear( request() .withBody(params(param("bodyParameterNameOne", "bodyParameterValueOne"))) ); // then assertThat( mockServerClient.retrieveExistingExpectations(null), arrayContaining( expectation( request() .withBody(params(param("bodyParameterNameTwo", "bodyParameterValueTwo"))) ) .thenRespond( response() .withBody("some_body2") ) ) ); // - in http assertEquals( response() .withStatusCode(OK_200.code()) .withBody("some_body2"), makeRequest( request() .withBody(params(param("bodyParameterName.*", "bodyParameterValue.*"))), headersToIgnore) ); // - in https assertEquals( response() .withStatusCode(OK_200.code()) .withBody("some_body2"), makeRequest( request() .withSecure(true) .withBody(params(param("bodyParameterName.*", "bodyParameterValue.*"))), headersToIgnore) ); } @Test public void shouldReset() { // given mockServerClient .when( request() .withPath(calculatePath("some_path1")) ) .respond( response() .withBody("some_body1") ); mockServerClient .when( request() .withPath(calculatePath("some_path2")) ) .respond( response() .withBody("some_body2") ); // when mockServerClient.reset(); // then // - in http assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()), makeRequest( request() .withPath(calculatePath("some_path1")), headersToIgnore) ); assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()), makeRequest( request() .withPath(calculatePath("some_path2")), headersToIgnore) ); // - in https assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()), makeRequest( request() .withSecure(true) .withPath(calculatePath("some_path1")), headersToIgnore) ); assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()), makeRequest( request() .withSecure(true) .withPath(calculatePath("some_path2")), headersToIgnore) ); } @Test public void shouldEnsureThatInterruptedRequestsAreVerifiable() throws Exception { mockServerClient .when( request(calculatePath("delayed")) ) .respond( response("delayed data") .withDelay(new Delay(TimeUnit.SECONDS, 3)) ); Future<HttpResponse> delayedFuture = Executors.newSingleThreadExecutor().submit(new Callable<HttpResponse>() { @Override public HttpResponse call() throws Exception { return httpClient.sendRequest( request(addContextToPath(calculatePath("delayed"))) .withHeader(HOST.toString(), "localhost:" + getMockServerPort()) ); } }); Uninterruptibles.sleepUninterruptibly(1, TimeUnit.SECONDS); // Let request reach server delayedFuture.cancel(true); // Then interrupt requesting thread mockServerClient.verify(request(calculatePath("delayed"))); // We should be able to verify request that reached server even though its later interrupted } @Test public void shouldEnsureThatRequestDelaysDoNotAffectOtherRequests() throws Exception { mockServerClient .when( request("/slow") ) .respond( response("super slow") .withDelay(new Delay(TimeUnit.SECONDS, 5)) ); mockServerClient .when( request("/fast") ) .respond( response("quite fast") ); ExecutorService executorService = Executors.newFixedThreadPool(2); Future<Long> slowFuture = executorService.submit(new Callable<Long>() { @Override public Long call() throws Exception { long start = System.currentTimeMillis(); makeRequest(request("/slow")); return System.currentTimeMillis() - start; } }); // Let fast request come to the server slightly after slow request Uninterruptibles.sleepUninterruptibly(1, TimeUnit.SECONDS); Future<Long> fastFuture = executorService.submit(new Callable<Long>() { @Override public Long call() throws Exception { long start = System.currentTimeMillis(); makeRequest(request("/fast")); return System.currentTimeMillis() - start; } }); Long slowRequestElapsedMillis = slowFuture.get(); Long fastRequestElapsedMillis = fastFuture.get(); assertThat("Slow request takes less than expected", slowRequestElapsedMillis, is(greaterThan(5 * 1000L))); assertThat("Fast request takes longer than expected", fastRequestElapsedMillis, is(lessThan(3 * 1000L))); } protected void verifyRequestMatches(HttpRequest[] httpRequests, HttpRequest... httpRequestMatchers) { if (httpRequests.length != httpRequestMatchers.length) { throw new AssertionError("Number of request matchers does not match number of requests, expected:<" + httpRequestMatchers.length + "> but was:<" + httpRequests.length + ">"); } else { for (int i = 0; i < httpRequestMatchers.length; i++) { if (!new HttpRequestMatcher(httpRequestMatchers[i]).matches(httpRequests[i])) { throw new AssertionError("Request does not match request matcher, expected:<" + httpRequestMatchers[i] + "> but was:<" + httpRequests[i] + ">"); } } } } protected HttpResponse makeRequest(HttpRequest httpRequest) { return makeRequest(httpRequest, Collections.<String>emptySet()); } protected String calculatePath(String path) { return (!path.startsWith("/") ? "/" : "") + path; } protected String addContextToPath(String path) { String cleanedPath = path; if (!Strings.isNullOrEmpty(servletContext)) { cleanedPath = (!servletContext.startsWith("/") ? "/" : "") + servletContext + (!servletContext.endsWith("/") ? "/" : "") + (cleanedPath.startsWith("/") ? cleanedPath.substring(1) : cleanedPath); } return (!cleanedPath.startsWith("/") ? "/" : "") + cleanedPath; } protected HttpResponse makeRequest(HttpRequest httpRequest, Collection<String> headersToIgnore) { int attemptsRemaining = 10; while (attemptsRemaining > 0) { try { boolean isSsl = httpRequest.isSecure() != null && httpRequest.isSecure(); int port = (isSsl ? getMockServerSecurePort() : getMockServerPort()); httpRequest.withPath(addContextToPath(httpRequest.getPath().getValue())); httpRequest.withHeader(HOST.toString(), "localhost:" + port); HttpResponse httpResponse = httpClient.sendRequest(httpRequest, new InetSocketAddress("localhost", port)); List<Header> headers = new ArrayList<Header>(); for (Header header : httpResponse.getHeaders()) { if (!headersToIgnore.contains(header.getName().getValue().toLowerCase())) { if (header.getName().getValue().equalsIgnoreCase(CONTENT_TYPE.toString())) { // this fixes Tomcat which removes the space between // media type and charset in the Content-Type header for (NottableString value : new ArrayList<NottableString>(header.getValues())) { header.getValues().clear(); header.addValues(value.getValue().replace(";charset", "; charset")); } header = header(header.getName().lowercase(), header.getValues()); } headers.add(header); } } httpResponse.withHeaders(headers); return httpResponse; } catch (SocketConnectionException caught) { attemptsRemaining--; logger.info("Retrying connection to mock server, attempts remaining: " + attemptsRemaining); try { TimeUnit.MILLISECONDS.sleep(50); } catch (InterruptedException e) { // do nothing } } } throw new RuntimeException("Failed to send request:" + NEW_LINE + httpRequest); } }
khmarbaise/mockserver
mockserver-integration-testing/src/main/java/org/mockserver/integration/server/AbstractClientServerIntegrationTest.java
920
package api; import java.io.*; import java.util.ArrayList; public class FileHandler { /** * Μέθοδος που κάνει serialize την λίστα που περιέχει όλους τους Customer και την γράφει στο αρχείο: "Customers.txt". * Κάνει επίσης serialize την λίστα που περιέχει όλους τους Provider και την γράφει στο αρχείο: "Providers.txt". * Καλείται όταν κλείνει το LoginFrame, και όταν εγγράφεται ένας νέος User. */ public static void serializeUsers() { ArrayList<Customer> listOfCustomers = new ArrayList<>(); ArrayList<Provider> listOfProviders = new ArrayList<>(); for(int i=0;i<User.getAllUsers().size();i++) { if( User.getAllUsers().get(i) instanceof Provider) { listOfProviders.add((Provider)User.getAllUsers().get(i)); } else { listOfCustomers.add((Customer)User.getAllUsers().get(i)); } } try(ObjectOutputStream outputStream = new ObjectOutputStream(new FileOutputStream("Providers.txt"))) { outputStream.flush(); outputStream.writeObject(listOfProviders); } catch (IOException e) { System.out.println(e.getMessage()); } try(ObjectOutputStream outputStream = new ObjectOutputStream(new FileOutputStream("Customers.txt"))) { outputStream.flush(); outputStream.writeObject(listOfCustomers); } catch (IOException e) { System.out.println(e.getMessage()); } } /** * Μέθοδος που κάνει deserialize την λίστα που περιέχει όλους τους Customer από το αρχείο: "Customers.txt". * Κάνει επίσης deserialize την λίστα που περιέχει όλους τους Provider από το αρχείο: "Providers.txt". * * Στην συνέχεια προσθέτει τους providers στην λίστα με όλους τους providers της {@link api.Provider}, * προσθέτει τους Customers στην λίστα με όλους τους Customers της {@link api.Customer}. * * Τέλος, αρχικοποιείται η λίστα με όλα τα Accommodation της εφαρμογής. */ public static void deserializationOfUsers() { ArrayList<Provider> tempList = null; try (ObjectInputStream inputStream = new ObjectInputStream(new FileInputStream("Providers.txt"))) { tempList = ((ArrayList<Provider>) inputStream.readObject()); } catch (IOException | ClassNotFoundException e) { System.out.println(e.getMessage()); } ArrayList<Customer> tempList2 = null; try (ObjectInputStream inputStream = new ObjectInputStream(new FileInputStream("Customers.txt"))) { tempList2 = ((ArrayList<Customer>) inputStream.readObject()); } catch (IOException | ClassNotFoundException e) { System.out.println(e.getMessage()); } for (int i = 0; i < tempList.size(); i++) { User.getAllUsers().add(tempList.get(i)); User.addUser(tempList.get(i).getUsername(), tempList.get(i).getPassword()); } for (int i = 0; i < tempList2.size(); i++) { User.getAllUsers().add(tempList2.get(i)); User.addUser(tempList2.get(i).getUsername(), tempList2.get(i).getPassword()); } Provider.getListOfProviders().addAll(tempList);//Τα γεμίζω απο με τα deserialized Customer.getListOfCustomers().addAll(tempList2); ArrayList<Accommodation> allAccommodations = new ArrayList<>(); for (int i = 0; i < Provider.getListOfProviders().size(); i++) { allAccommodations.addAll(Provider.getListOfProviders().get(i).getMyAccommodations());//Βάζω όλα τα Accommodation των Provider } for (int i = 0; i < allAccommodations.size(); i++) { allAccommodations.get(i).getReviews().clear();//Διαγράφω τα Reviews που είχαν για να βάλω αυτά των Customer } //Λόγω προβλήματος με τις θέσης μνήμης που δημιουργήθηκε με serialization. Customer temp; Review temp2; for (int i = 0; i < Customer.getListOfCustomers().size(); i++) { temp = Customer.getListOfCustomers().get(i); for (int j = 0; j < temp.getMyReviews().size(); j++) { temp2 = temp.getMyReviews().get(j); if(allAccommodations.contains(temp2.getReviewedAcc())) { int index = allAccommodations.indexOf(temp2.getReviewedAcc()); allAccommodations.get(index).addReview(temp2);//Αρχικοποίηση των Reviews στα Accommodations temp2.setReviewedAcc(allAccommodations.get(index)); } } } Accommodation.getAccommodations().addAll(allAccommodations);//Αρχικοποίηση της λίστας με όλα τα Accommodations } }
StylianosBairamis/oop-myreviews-project
src/api/FileHandler.java
921
package rabbitminer.Cluster.StratumClient; import Extasys.DataFrame; import Extasys.ManualResetEvent; import Extasys.Network.TCP.Client.Connectors.TCPConnector; import Extasys.Network.TCP.Client.Exceptions.ConnectorCannotSendPacketException; import Extasys.Network.TCP.Client.Exceptions.ConnectorDisconnectedException; import rabbitminer.Cluster.RabbitCluster; import rabbitminer.Cluster.StratumClient.StratumParsers.*; /** * * @author Nikos Siatras */ public class StratumClient extends Extasys.Network.TCP.Client.ExtasysTCPClient { private final RabbitCluster fMyCluster; private final StratumPoolSettings fStratumPoolSettings; private StratumParser fMyStratumParser; private String fStatus = ""; private boolean fTCPConnectionIsEstablished = false; private Thread fKeepClientConnectedToPoolThread = null; private ManualResetEvent fWaitToEstablishTCPConnection = new ManualResetEvent(false); public StratumClient(RabbitCluster myCluster, StratumPoolSettings poolSettings) { super("", "", 4, 6); super.AddConnector("PoolConnector", poolSettings.getIPAddress(), poolSettings.getPort(), 10240, "\n"); fStratumPoolSettings = poolSettings; fMyCluster = myCluster; switch (poolSettings.getCryptoAlgorithm()) { case SCrypt: fMyStratumParser = new Parser_SCrypt(this); break; case RandomX: fMyStratumParser = new Parser_RandomX(this); break; } } @Override public void OnDataReceive(TCPConnector connector, DataFrame data) { try { System.out.println("Stratum Client incoming data:"); System.out.println(new String(data.getBytes())); System.out.println("\n"); StratumToken token = new StratumToken(new String(data.getBytes())); try { fMyStratumParser.Parse(token); } catch (ConnectorDisconnectedException | ConnectorCannotSendPacketException ex) { this.Stop(); } } catch (Exception ex) { } } @Override public void OnConnect(TCPConnector connector) { // Με το που το mining pool δεχθεί το Connection // ζήτα, ΣΕ ΝΕΟ THREAD, απο τον fMyStratumParser // να τρέξει το method ClientConnectedToPool Thread th = new Thread(() -> { try { fMyStratumParser.ClientEstablishedTCPConnectionWithThePool(); fStatus = "Connected"; fTCPConnectionIsEstablished = true; fWaitToEstablishTCPConnection.Set(); } catch (ConnectorDisconnectedException | ConnectorCannotSendPacketException ex) { if (fMyStratumParser == null) { System.err.println("Stratum Parser is Null!!!"); fStatus = "Disconnected"; fTCPConnectionIsEstablished = false; fWaitToEstablishTCPConnection.Set(); } } }); th.start(); } @Override public void OnDisconnect(TCPConnector connector) { fTCPConnectionIsEstablished = false; fStatus = "Disconnected"; fMyCluster.setCurrentStratumJob(null, true); try { fMyStratumParser.ClientDisconnectedFromPool(); } catch (Exception ex) { } } @Override public void Start() throws Exception { if (fKeepClientConnectedToPoolThread == null) { // Το παρακάτω Thread ελέγχει αν ο Stratum Client // είναι συνδεδεμένος με το Mining Pool. // Στην περίπτωση που δέν ειναι συνδεδεμένος κάνει σύνδεση fKeepClientConnectedToPoolThread = new Thread(() -> { while (true) { if (!isClientConnectedAndAuthorizedByThePool()) { fStatus = "Connecting to pool..."; // Κάνε Stop τον Client try { ForceStop(); } catch (Exception ex) { System.err.println(ex.getMessage()); } // Κάνε remove τον παλιό TCPConnector και δημιούργησε έναν νέο RemoveConnector("PoolConnector"); AddConnector("PoolConnector", fStratumPoolSettings.getIPAddress(), fStratumPoolSettings.getPort(), 10240, "\n"); // Κάνε Start τον client try { fWaitToEstablishTCPConnection.Reset(); StratumClient.super.Start(); fWaitToEstablishTCPConnection.WaitOne(6000); } catch (Exception ex) { fTCPConnectionIsEstablished = false; fStatus = "Error while trying to connect to pool"; } } try { Thread.sleep(1000); } catch (Exception ex) { } } }); fKeepClientConnectedToPoolThread.start(); } } /** * Για να είναι ένας Stratum Client σωστά συνδεδεμένος με το Pool θα πρέπει * να έχει ενεργό TCP Connection και ο Miner να είναι Subscribed και * Authorized * * @return */ public boolean isClientConnectedAndAuthorizedByThePool() { return fTCPConnectionIsEstablished && fMyStratumParser.isMinerSubscribed() && fMyStratumParser.isMinerAuthorized(); } public RabbitCluster getMyCluster() { return fMyCluster; } public StratumParser getMyParser() { return fMyStratumParser; } public String getStatus() { return fStatus; } public void setStatus(String status) { fStatus = status; } }
SourceRabbit/Rabbit_Miner
RabbitMiner/src/rabbitminer/Cluster/StratumClient/StratumClient.java
922
package org.mockserver.integration.server; import com.google.common.net.MediaType; import com.google.common.util.concurrent.Uninterruptibles; import org.apache.commons.io.IOUtils; import org.junit.Test; import org.mockserver.client.serialization.ExpectationSerializer; import org.mockserver.client.serialization.HttpRequestSerializer; import org.mockserver.client.serialization.java.ExpectationToJavaSerializer; import org.mockserver.echo.http.EchoServer; import org.mockserver.logging.MockServerLogger; import org.mockserver.matchers.MatchType; import org.mockserver.matchers.TimeToLive; import org.mockserver.mock.Expectation; import org.mockserver.model.*; import org.mockserver.verify.VerificationTimes; import java.io.IOException; import java.nio.charset.StandardCharsets; import java.util.Arrays; import java.util.Collections; import java.util.concurrent.*; import static io.netty.handler.codec.http.HttpHeaderNames.*; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.*; import static org.hamcrest.core.Is.is; import static org.hamcrest.core.StringStartsWith.startsWith; import static org.hamcrest.number.OrderingComparison.greaterThan; import static org.junit.Assert.assertEquals; import static org.junit.Assert.fail; import static org.mockserver.character.Character.NEW_LINE; import static org.mockserver.matchers.Times.exactly; import static org.mockserver.model.BinaryBody.binary; import static org.mockserver.model.Cookie.cookie; import static org.mockserver.model.Header.header; import static org.mockserver.model.HttpForward.forward; import static org.mockserver.model.HttpRequest.request; import static org.mockserver.model.HttpResponse.notFoundResponse; import static org.mockserver.model.HttpResponse.response; import static org.mockserver.model.HttpStatusCode.NOT_FOUND_404; import static org.mockserver.model.HttpStatusCode.OK_200; import static org.mockserver.model.JsonBody.json; import static org.mockserver.model.JsonSchemaBody.jsonSchema; import static org.mockserver.model.NottableString.not; import static org.mockserver.model.NottableString.string; import static org.mockserver.model.Parameter.param; import static org.mockserver.model.ParameterBody.params; import static org.mockserver.model.RegexBody.regex; import static org.mockserver.model.StringBody.exact; import static org.mockserver.model.StringBody.subString; import static org.mockserver.model.XPathBody.xpath; import static org.mockserver.model.XmlBody.xml; import static org.mockserver.model.XmlSchemaBody.xmlSchema; import static org.mockserver.model.XmlSchemaBody.xmlSchemaFromResource; /** * @author jamesdbloom */ public abstract class AbstractExtendedMockingIntegrationTest extends AbstractBasicMockingIntegrationTest { @Test public void shouldReturnResponseForRequestInSsl() { // when mockServerClient.when(request().withSecure(true)).respond(response().withBody("some_body")); // then // - in http assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()) .withReasonPhrase(HttpStatusCode.NOT_FOUND_404.reasonPhrase()), makeRequest( request() .withPath(calculatePath("")), headersToIgnore) ); // - in https assertEquals( response() .withStatusCode(OK_200.code()) .withReasonPhrase(OK_200.reasonPhrase()) .withBody("some_body"), makeRequest( request() .withSecure(true) .withPath(calculatePath("")), headersToIgnore) ); } @Test public void shouldReturnResponseForRequestNotInSsl() { // when mockServerClient.when(request().withSecure(false)).respond(response().withBody("some_body")); // then // - in http assertEquals( response() .withStatusCode(OK_200.code()) .withReasonPhrase(OK_200.reasonPhrase()) .withBody("some_body"), makeRequest( request() .withPath(calculatePath("")), headersToIgnore) ); // - in https assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()) .withReasonPhrase(HttpStatusCode.NOT_FOUND_404.reasonPhrase()), makeRequest( request() .withSecure(true) .withPath(calculatePath("")), headersToIgnore) ); } @Test public void shouldReturnResponseByMatchingPath() { // when mockServerClient .when( request() .withPath(calculatePath("some_path1")) ) .respond( response() .withBody("some_body1") ); mockServerClient .when( request() .withPath(calculatePath("some_path2")) ) .respond( response() .withBody("some_body2") ); // then // - in http assertEquals( response() .withStatusCode(OK_200.code()) .withReasonPhrase(OK_200.reasonPhrase()) .withBody("some_body2"), makeRequest( request() .withPath(calculatePath("some_path2")), headersToIgnore) ); assertEquals( response() .withStatusCode(OK_200.code()) .withReasonPhrase(OK_200.reasonPhrase()) .withBody("some_body1"), makeRequest( request() .withPath(calculatePath("some_path1")), headersToIgnore) ); // - in https assertEquals( response() .withStatusCode(OK_200.code()) .withReasonPhrase(OK_200.reasonPhrase()) .withBody("some_body2"), makeRequest( request() .withSecure(true) .withPath(calculatePath("some_path2")), headersToIgnore) ); assertEquals( response() .withStatusCode(OK_200.code()) .withReasonPhrase(OK_200.reasonPhrase()) .withBody("some_body1"), makeRequest( request() .withSecure(true) .withPath(calculatePath("some_path1")), headersToIgnore) ); } @Test public void shouldReturnResponseByMatchingPathExactTimes() { // when mockServerClient .when( request() .withPath(calculatePath("some_path")), exactly(2) ) .respond( response() .withBody("some_body") ); // then // - in http assertEquals( response() .withStatusCode(OK_200.code()) .withReasonPhrase(OK_200.reasonPhrase()) .withBody("some_body"), makeRequest( request() .withPath(calculatePath("some_path")), headersToIgnore) ); // - in https assertEquals( response() .withStatusCode(OK_200.code()) .withReasonPhrase(OK_200.reasonPhrase()) .withBody("some_body"), makeRequest( request() .withSecure(true) .withPath(calculatePath("some_path")), headersToIgnore) ); // - in http assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()) .withReasonPhrase(HttpStatusCode.NOT_FOUND_404.reasonPhrase()), makeRequest( request() .withPath(calculatePath("some_path")), headersToIgnore) ); // - in https assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()) .withReasonPhrase(HttpStatusCode.NOT_FOUND_404.reasonPhrase()), makeRequest( request() .withSecure(true) .withPath(calculatePath("some_path")), headersToIgnore) ); } @Test public void shouldReturnResponseWhenTimeToLiveHasNotExpired() { // when mockServerClient .when( request().withPath(calculatePath("some_path")), exactly(2), TimeToLive.exactly(TimeUnit.HOURS, 1L) ) .respond( response().withBody("some_body") ); // then // - in http assertEquals( response() .withStatusCode(OK_200.code()) .withReasonPhrase(OK_200.reasonPhrase()) .withBody("some_body"), makeRequest( request() .withPath(calculatePath("some_path")), headersToIgnore) ); // - in https assertEquals( response() .withStatusCode(OK_200.code()) .withReasonPhrase(OK_200.reasonPhrase()) .withBody("some_body"), makeRequest( request() .withSecure(true) .withPath(calculatePath("some_path")), headersToIgnore) ); // - in http assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()) .withReasonPhrase(HttpStatusCode.NOT_FOUND_404.reasonPhrase()), makeRequest( request() .withPath(calculatePath("some_path")), headersToIgnore) ); // - in https assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()) .withReasonPhrase(HttpStatusCode.NOT_FOUND_404.reasonPhrase()), makeRequest( request() .withSecure(true) .withPath(calculatePath("some_path")), headersToIgnore) ); } @Test public void shouldReturnMatchRequestWithBodyInUTF16() { // when String body = "我说中国话"; mockServerClient.when(request().withBody(body, StandardCharsets.UTF_16)).respond(response().withBody(body, StandardCharsets.UTF_8)); // then // - in http assertEquals( response() .withHeader(CONTENT_TYPE.toString(), MediaType.create("text", "plain").withCharset(StandardCharsets.UTF_8).toString()) .withStatusCode(OK_200.code()) .withReasonPhrase(OK_200.reasonPhrase()) .withBody(body), makeRequest( request() .withPath(calculatePath("")) .withBody(body, StandardCharsets.UTF_16), headersToIgnore) ); // - in https assertEquals( response() .withHeader(CONTENT_TYPE.toString(), MediaType.create("text", "plain").withCharset(StandardCharsets.UTF_8).toString()) .withStatusCode(OK_200.code()) .withReasonPhrase(OK_200.reasonPhrase()) .withBody(body), makeRequest( request() .withSecure(true) .withPath(calculatePath("")) .withBody(body, StandardCharsets.UTF_16), headersToIgnore) ); } @Test public void shouldReturnMatchRequestWithBodyInUTF8WithContentTypeHeader() { // when String body = "我说中国话"; mockServerClient .when( request() .withHeader(CONTENT_TYPE.toString(), MediaType.create("text", "plain").withCharset(StandardCharsets.UTF_8).toString()) .withBody(body) ) .respond( response() .withBody(body, StandardCharsets.UTF_8) ); // then // - in http assertEquals( response() .withHeader(CONTENT_TYPE.toString(), MediaType.create("text", "plain").withCharset(StandardCharsets.UTF_8).toString()) .withStatusCode(OK_200.code()) .withReasonPhrase(OK_200.reasonPhrase()) .withBody(body), makeRequest( request() .withHeader(CONTENT_TYPE.toString(), MediaType.create("text", "plain").withCharset(StandardCharsets.UTF_8).toString()) .withPath(calculatePath("")) .withBody(body), headersToIgnore) ); // - in https assertEquals( response() .withHeader(CONTENT_TYPE.toString(), MediaType.create("text", "plain").withCharset(StandardCharsets.UTF_8).toString()) .withStatusCode(OK_200.code()) .withReasonPhrase(OK_200.reasonPhrase()) .withBody(body), makeRequest( request() .withHeader(CONTENT_TYPE.toString(), MediaType.create("text", "plain").withCharset(StandardCharsets.UTF_8).toString()) .withSecure(true) .withPath(calculatePath("")) .withBody(body), headersToIgnore) ); } @Test public void shouldReturnResponseWithBodyInUTF16() { // when String body = "我说中国话"; mockServerClient.when(request()).respond(response().withBody(body, StandardCharsets.UTF_16)); // then // - in http assertEquals( response() .withHeader(CONTENT_TYPE.toString(), MediaType.create("text", "plain").withCharset(StandardCharsets.UTF_16).toString()) .withStatusCode(OK_200.code()) .withReasonPhrase(OK_200.reasonPhrase()) .withBody(body), makeRequest( request() .withPath(calculatePath("")), headersToIgnore) ); // - in https assertEquals( response() .withHeader(CONTENT_TYPE.toString(), MediaType.create("text", "plain").withCharset(StandardCharsets.UTF_16).toString()) .withStatusCode(OK_200.code()) .withReasonPhrase(OK_200.reasonPhrase()) .withBody(body), makeRequest( request() .withSecure(true) .withPath(calculatePath("")), headersToIgnore) ); } @Test public void shouldReturnResponseWithBodyInUTF8WithContentTypeHeader() { // when String body = "我说中国话"; mockServerClient .when( request() ) .respond( response() .withHeader(CONTENT_TYPE.toString(), MediaType.create("text", "plain").withCharset(StandardCharsets.UTF_8).toString()) .withBody(body) ); // then // - in http assertEquals( response() .withHeader(CONTENT_TYPE.toString(), MediaType.create("text", "plain").withCharset(StandardCharsets.UTF_8).toString()) .withStatusCode(OK_200.code()) .withReasonPhrase(OK_200.reasonPhrase()) .withBody(body), makeRequest( request() .withPath(calculatePath("")), headersToIgnore) ); // - in https assertEquals( response() .withHeader(CONTENT_TYPE.toString(), MediaType.create("text", "plain").withCharset(StandardCharsets.UTF_8).toString()) .withStatusCode(OK_200.code()) .withReasonPhrase(OK_200.reasonPhrase()) .withBody(body), makeRequest( request() .withSecure(true) .withPath(calculatePath("")), headersToIgnore) ); } @Test public void shouldReturnResponseByMatchingSubStringBody() { // when mockServerClient .when( request() .withBody( subString("random") ), exactly(2) ) .respond( response() .withBody("some_sub_string_body_response") ); // then // - in http assertEquals( response() .withStatusCode(OK_200.code()) .withReasonPhrase(OK_200.reasonPhrase()) .withBody("some_sub_string_body_response"), makeRequest( request() .withMethod("POST") .withPath(calculatePath("some_path")) .withBody("some_random_body"), headersToIgnore) ); // - in https assertEquals( response() .withStatusCode(OK_200.code()) .withReasonPhrase(OK_200.reasonPhrase()) .withBody("some_sub_string_body_response"), makeRequest( request() .withSecure(true) .withMethod("POST") .withPath(calculatePath("some_path")) .withBody("some_random_body"), headersToIgnore) ); } @Test public void shouldReturnResponseByMatchingBodyWithXPath() { // when mockServerClient.when(request().withBody(xpath("/bookstore/book[price>30]/price")), exactly(2)).respond(response().withBody("some_body")); // then // - in http assertEquals( response() .withStatusCode(OK_200.code()) .withReasonPhrase(OK_200.reasonPhrase()) .withBody("some_body"), makeRequest( request() .withPath(calculatePath("some_path")) .withMethod("POST") .withBody(new StringBody("" + "<?xml version=\"1.0\" encoding=\"ISO-8859-1\"?>" + NEW_LINE + "<bookstore>" + NEW_LINE + " <book category=\"COOKING\">" + NEW_LINE + " <title lang=\"en\">Everyday Italian</title>" + NEW_LINE + " <author>Giada De Laurentiis</author>" + NEW_LINE + " <year>2005</year>" + NEW_LINE + " <price>30.00</price>" + NEW_LINE + " </book>" + NEW_LINE + " <book category=\"CHILDREN\">" + NEW_LINE + " <title lang=\"en\">Harry Potter</title>" + NEW_LINE + " <author>J K. Rowling</author>" + NEW_LINE + " <year>2005</year>" + NEW_LINE + " <price>29.99</price>" + NEW_LINE + " </book>" + NEW_LINE + " <book category=\"WEB\">" + NEW_LINE + " <title lang=\"en\">Learning XML</title>" + NEW_LINE + " <author>Erik T. Ray</author>" + NEW_LINE + " <year>2003</year>" + NEW_LINE + " <price>31.95</price>" + NEW_LINE + " </book>" + NEW_LINE + "</bookstore>")), headersToIgnore) ); // - in https assertEquals( response() .withStatusCode(OK_200.code()) .withReasonPhrase(OK_200.reasonPhrase()) .withBody("some_body"), makeRequest( request() .withSecure(true) .withPath(calculatePath("some_path")) .withMethod("POST") .withBody(new StringBody("" + "<?xml version=\"1.0\" encoding=\"ISO-8859-1\"?>" + NEW_LINE + "<bookstore>" + NEW_LINE + " <book category=\"COOKING\">" + NEW_LINE + " <title lang=\"en\">Everyday Italian</title>" + NEW_LINE + " <author>Giada De Laurentiis</author>" + NEW_LINE + " <year>2005</year>" + NEW_LINE + " <price>30.00</price>" + NEW_LINE + " </book>" + NEW_LINE + " <book category=\"CHILDREN\">" + NEW_LINE + " <title lang=\"en\">Harry Potter</title>" + NEW_LINE + " <author>J K. Rowling</author>" + NEW_LINE + " <year>2005</year>" + NEW_LINE + " <price>29.99</price>" + NEW_LINE + " </book>" + NEW_LINE + " <book category=\"WEB\">" + NEW_LINE + " <title lang=\"en\">Learning XML</title>" + NEW_LINE + " <author>Erik T. Ray</author>" + NEW_LINE + " <year>2003</year>" + NEW_LINE + " <price>31.95</price>" + NEW_LINE + " </book>" + NEW_LINE + "</bookstore>")), headersToIgnore) ); } @Test public void shouldReturnResponseByMatchingBodyWithXml() { // when mockServerClient.when(request().withBody(xml("" + "<bookstore>" + NEW_LINE + " <book nationality=\"ITALIAN\" category=\"COOKING\"><title lang=\"en\">Everyday Italian</title><author>Giada De Laurentiis</author><year>2005</year><price>30.00</price></book>" + NEW_LINE + "</bookstore>")), exactly(2)).respond(response().withBody("some_body")); // then // - in http assertEquals( response() .withStatusCode(OK_200.code()) .withReasonPhrase(OK_200.reasonPhrase()) .withBody("some_body"), makeRequest( request() .withPath(calculatePath("some_path")) .withMethod("POST") .withBody(new StringBody("" + "<?xml version=\"1.0\" encoding=\"ISO-8859-1\"?>" + NEW_LINE + "<bookstore>" + NEW_LINE + " <book category=\"COOKING\" nationality=\"ITALIAN\">" + NEW_LINE + " <title lang=\"en\">Everyday Italian</title>" + NEW_LINE + " <author>Giada De Laurentiis</author>" + NEW_LINE + " <year>2005</year>" + NEW_LINE + " <price>30.00</price>" + NEW_LINE + " </book>" + NEW_LINE + "</bookstore>")), headersToIgnore) ); // - in https assertEquals( response() .withStatusCode(OK_200.code()) .withReasonPhrase(OK_200.reasonPhrase()) .withBody("some_body"), makeRequest( request() .withSecure(true) .withPath(calculatePath("some_path")) .withMethod("POST") .withBody(new StringBody("" + "<?xml version=\"1.0\" encoding=\"ISO-8859-1\"?>" + NEW_LINE + "<bookstore>" + NEW_LINE + " <book category=\"COOKING\" nationality=\"ITALIAN\">" + NEW_LINE + " <title lang=\"en\">Everyday Italian</title>" + NEW_LINE + " <author>Giada De Laurentiis</author>" + NEW_LINE + " <year>2005</year>" + NEW_LINE + " <price>30.00</price>" + NEW_LINE + " </book>" + NEW_LINE + "</bookstore>")), headersToIgnore) ); } @Test public void shouldReturnResponseByMatchingBodyWithJson() { // when mockServerClient .when( request() .withBody(json("{" + NEW_LINE + " \"id\": 1," + NEW_LINE + " \"name\": \"A green door\"," + NEW_LINE + " \"price\": 12.50," + NEW_LINE + " \"tags\": [\"home\", \"green\"]" + NEW_LINE + "}")), exactly(2) ) .respond( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withReasonPhrase(HttpStatusCode.ACCEPTED_202.reasonPhrase()) .withBody("some_body") ); // then // - in http assertEquals( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withReasonPhrase(HttpStatusCode.ACCEPTED_202.reasonPhrase()) .withBody("some_body"), makeRequest( request() .withPath(calculatePath("some_path")) .withMethod("POST") .withBody("{" + NEW_LINE + " \"id\": 1," + NEW_LINE + " \"extra ignored field\": \"some value\"," + NEW_LINE + " \"name\": \"A green door\"," + NEW_LINE + " \"price\": 12.50," + NEW_LINE + " \"tags\": [\"home\", \"green\"]" + NEW_LINE + "}"), headersToIgnore) ); // - in https assertEquals( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withReasonPhrase(HttpStatusCode.ACCEPTED_202.reasonPhrase()) .withBody("some_body"), makeRequest( request() .withSecure(true) .withPath(calculatePath("some_path")) .withMethod("POST") .withBody("{" + NEW_LINE + " \"id\": 1," + NEW_LINE + " \"extra ignored array\": [\"one\", \"two\"]," + NEW_LINE + " \"name\": \"A green door\"," + NEW_LINE + " \"price\": 12.50," + NEW_LINE + " \"tags\": [\"home\", \"green\"]" + NEW_LINE + "}"), headersToIgnore) ); } @Test public void shouldReturnResponseByMatchingBodyWithJsonWithCharsetUTF8() { // when mockServerClient .when( request() .withBody(json("{" + NEW_LINE + " \"ταυτότητα\": 1," + NEW_LINE + " \"όνομα\": \"μια πράσινη πόρτα\"," + NEW_LINE + " \"τιμή\": 12.50," + NEW_LINE + " \"ετικέτες\": [\"σπίτι\", \"πράσινος\"]" + NEW_LINE + "}", StandardCharsets.UTF_16, MatchType.ONLY_MATCHING_FIELDS)), exactly(2) ) .respond( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withReasonPhrase(HttpStatusCode.ACCEPTED_202.reasonPhrase()) .withBody("some_body") ); // then // - in http assertEquals( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withReasonPhrase(HttpStatusCode.ACCEPTED_202.reasonPhrase()) .withBody("some_body"), makeRequest( request() .withPath(calculatePath("some_path")) .withMethod("POST") .withBody(json("{" + NEW_LINE + " \"ταυτότητα\": 1," + NEW_LINE + " \"επιπλέον αγνοούνται τομέα\": \"κάποια αξία\"," + NEW_LINE + " \"όνομα\": \"μια πράσινη πόρτα\"," + NEW_LINE + " \"τιμή\": 12.50," + NEW_LINE + " \"ετικέτες\": [\"σπίτι\", \"πράσινος\"]" + NEW_LINE + "}", StandardCharsets.UTF_16, MatchType.ONLY_MATCHING_FIELDS)), headersToIgnore) ); // - in https assertEquals( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withReasonPhrase(HttpStatusCode.ACCEPTED_202.reasonPhrase()) .withBody("some_body"), makeRequest( request() .withSecure(true) .withPath(calculatePath("some_path")) .withMethod("POST") .withBody(json("{" + NEW_LINE + " \"ταυτότητα\": 1," + NEW_LINE + " \"επιπλέον αγνοούνται σειρά\": [\"ένας\", \"δυο\"]," + NEW_LINE + " \"όνομα\": \"μια πράσινη πόρτα\"," + NEW_LINE + " \"τιμή\": 12.50," + NEW_LINE + " \"ετικέτες\": [\"σπίτι\", \"πράσινος\"]" + NEW_LINE + "}", StandardCharsets.UTF_16, MatchType.ONLY_MATCHING_FIELDS)), headersToIgnore) ); } @Test public void shouldReturnResponseByMatchingBodyWithJsonWithContentTypeHeader() { // when mockServerClient .when( request() .withBody(json("{" + NEW_LINE + " \"ταυτότητα\": 1," + NEW_LINE + " \"όνομα\": \"μια πράσινη πόρτα\"," + NEW_LINE + " \"τιμή\": 12.50," + NEW_LINE + " \"ετικέτες\": [\"σπίτι\", \"πράσινος\"]" + NEW_LINE + "}", StandardCharsets.UTF_16, MatchType.ONLY_MATCHING_FIELDS)), exactly(2) ) .respond( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withReasonPhrase(HttpStatusCode.ACCEPTED_202.reasonPhrase()) .withBody("some_body") ); // then // - in http assertEquals( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withReasonPhrase(HttpStatusCode.ACCEPTED_202.reasonPhrase()) .withBody("some_body"), makeRequest( request() .withHeader(CONTENT_TYPE.toString(), MediaType.create("text", "plain").withCharset(StandardCharsets.UTF_16).toString()) .withPath(calculatePath("some_path")) .withMethod("POST") .withBody(json("{" + NEW_LINE + " \"ταυτότητα\": 1," + NEW_LINE + " \"επιπλέον αγνοούνται τομέα\": \"κάποια αξία\"," + NEW_LINE + " \"όνομα\": \"μια πράσινη πόρτα\"," + NEW_LINE + " \"τιμή\": 12.50," + NEW_LINE + " \"ετικέτες\": [\"σπίτι\", \"πράσινος\"]" + NEW_LINE + "}")), headersToIgnore) ); // - in https assertEquals( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withReasonPhrase(HttpStatusCode.ACCEPTED_202.reasonPhrase()) .withBody("some_body"), makeRequest( request() .withSecure(true) .withHeader(CONTENT_TYPE.toString(), MediaType.create("text", "plain").withCharset(StandardCharsets.UTF_16).toString()) .withPath(calculatePath("some_path")) .withMethod("POST") .withBody(json("{" + NEW_LINE + " \"ταυτότητα\": 1," + NEW_LINE + " \"επιπλέον αγνοούνται σειρά\": [\"ένας\", \"δυο\"]," + NEW_LINE + " \"όνομα\": \"μια πράσινη πόρτα\"," + NEW_LINE + " \"τιμή\": 12.50," + NEW_LINE + " \"ετικέτες\": [\"σπίτι\", \"πράσινος\"]" + NEW_LINE + "}")), headersToIgnore) ); } @Test public void shouldReturnResponseByMatchingBodyWithJsonWithMatchType() { // when mockServerClient .when( request() .withBody(json("{" + NEW_LINE + " \"id\": 1," + NEW_LINE + " \"name\": \"A green door\"," + NEW_LINE + " \"price\": 12.50," + NEW_LINE + " \"tags\": [\"home\", \"green\"]" + NEW_LINE + "}", MatchType.ONLY_MATCHING_FIELDS)), exactly(2) ) .respond( response() .withBody("some_body") ); // then // - in http assertEquals( response("some_body"), makeRequest( request() .withPath(calculatePath("some_path")) .withMethod("POST") .withBody("{" + NEW_LINE + " \"id\": 1," + NEW_LINE + " \"extra field\": \"some value\"," + NEW_LINE + " \"name\": \"A green door\"," + NEW_LINE + " \"price\": 12.50," + NEW_LINE + " \"tags\": [\"home\", \"green\"]" + NEW_LINE + "}"), headersToIgnore) ); // - in https assertEquals( response("some_body"), makeRequest( request() .withSecure(true) .withPath(calculatePath("some_path")) .withMethod("POST") .withBody("{" + NEW_LINE + " \"id\": 1," + NEW_LINE + " \"extra field\": \"some value\"," + NEW_LINE + " \"name\": \"A green door\"," + NEW_LINE + " \"price\": 12.50," + NEW_LINE + " \"tags\": [\"home\", \"green\"]" + NEW_LINE + "}"), headersToIgnore) ); } @Test public void shouldReturnResponseByMatchingBodyWithJsonSchema() { // when mockServerClient.when(request().withBody(jsonSchema("{" + NEW_LINE + " \"$schema\": \"http://json-schema.org/draft-04/schema#\"," + NEW_LINE + " \"title\": \"Product\"," + NEW_LINE + " \"description\": \"A product from Acme's catalog\"," + NEW_LINE + " \"type\": \"object\"," + NEW_LINE + " \"properties\": {" + NEW_LINE + " \"id\": {" + NEW_LINE + " \"description\": \"The unique identifier for a product\"," + NEW_LINE + " \"type\": \"integer\"" + NEW_LINE + " }," + NEW_LINE + " \"name\": {" + NEW_LINE + " \"description\": \"Name of the product\"," + NEW_LINE + " \"type\": \"string\"" + NEW_LINE + " }," + NEW_LINE + " \"price\": {" + NEW_LINE + " \"type\": \"number\"," + NEW_LINE + " \"minimum\": 0," + NEW_LINE + " \"exclusiveMinimum\": true" + NEW_LINE + " }," + NEW_LINE + " \"tags\": {" + NEW_LINE + " \"type\": \"array\"," + NEW_LINE + " \"items\": {" + NEW_LINE + " \"type\": \"string\"" + NEW_LINE + " }," + NEW_LINE + " \"minItems\": 1," + NEW_LINE + " \"uniqueItems\": true" + NEW_LINE + " }" + NEW_LINE + " }," + NEW_LINE + " \"required\": [\"id\", \"name\", \"price\"]" + NEW_LINE + "}")), exactly(2)).respond(response().withBody("some_body")); // then // - in http assertEquals( response() .withStatusCode(OK_200.code()) .withReasonPhrase(OK_200.reasonPhrase()) .withBody("some_body"), makeRequest( request() .withPath(calculatePath("some_path")) .withMethod("POST") .withBody("{" + NEW_LINE + " \"id\": 1," + NEW_LINE + " \"name\": \"A green door\"," + NEW_LINE + " \"price\": 12.50," + NEW_LINE + " \"tags\": [\"home\", \"green\"]" + NEW_LINE + "}"), headersToIgnore) ); // - in https assertEquals( response() .withStatusCode(OK_200.code()) .withReasonPhrase(OK_200.reasonPhrase()) .withBody("some_body"), makeRequest( request() .withSecure(true) .withPath(calculatePath("some_path")) .withMethod("POST") .withBody("{" + NEW_LINE + " \"id\": 1," + NEW_LINE + " \"name\": \"A green door\"," + NEW_LINE + " \"price\": 12.50," + NEW_LINE + " \"tags\": [\"home\", \"green\"]" + NEW_LINE + "}"), headersToIgnore) ); } @Test public void shouldReturnResponseByMatchingBodyWithXmlSchema() { // when mockServerClient.when(request() .withBody( xmlSchema("<?xml version=\"1.0\" encoding=\"UTF-8\"?>" + NEW_LINE + "<xs:schema xmlns:xs=\"http://www.w3.org/2001/XMLSchema\" elementFormDefault=\"qualified\" attributeFormDefault=\"unqualified\">" + NEW_LINE + " <!-- XML Schema Generated from XML Document on Wed Jun 28 2017 21:52:45 GMT+0100 (BST) -->" + NEW_LINE + " <!-- with XmlGrid.net Free Online Service http://xmlgrid.net -->" + NEW_LINE + " <xs:element name=\"notes\">" + NEW_LINE + " <xs:complexType>" + NEW_LINE + " <xs:sequence>" + NEW_LINE + " <xs:element name=\"note\" maxOccurs=\"unbounded\">" + NEW_LINE + " <xs:complexType>" + NEW_LINE + " <xs:sequence>" + NEW_LINE + " <xs:element name=\"to\" minOccurs=\"1\" maxOccurs=\"1\" type=\"xs:string\"></xs:element>" + NEW_LINE + " <xs:element name=\"from\" minOccurs=\"1\" maxOccurs=\"1\" type=\"xs:string\"></xs:element>" + NEW_LINE + " <xs:element name=\"heading\" minOccurs=\"1\" maxOccurs=\"1\" type=\"xs:string\"></xs:element>" + NEW_LINE + " <xs:element name=\"body\" minOccurs=\"1\" maxOccurs=\"1\" type=\"xs:string\"></xs:element>" + NEW_LINE + " </xs:sequence>" + NEW_LINE + " </xs:complexType>" + NEW_LINE + " </xs:element>" + NEW_LINE + " </xs:sequence>" + NEW_LINE + " </xs:complexType>" + NEW_LINE + " </xs:element>" + NEW_LINE + "</xs:schema>")), exactly(2) ) .respond( response() .withBody("some_body") ); // then // - in http assertEquals( response() .withStatusCode(NOT_FOUND_404.code()) .withReasonPhrase(NOT_FOUND_404.reasonPhrase()), makeRequest( request() .withMethod("POST") .withBody("<?xml version=\"1.0\" encoding=\"utf-8\"?>" + NEW_LINE + "<notes>" + NEW_LINE + " <note>" + NEW_LINE + " <to>Bob</to>" + NEW_LINE + " <heading>Reminder</heading>" + NEW_LINE + " <body>Buy Bread</body>" + NEW_LINE + " </note>" + NEW_LINE + " <note>" + NEW_LINE + " <to>Jack</to>" + NEW_LINE + " <from>Jill</from>" + NEW_LINE + " <heading>Reminder</heading>" + NEW_LINE + " <body>Wash Shirts</body>" + NEW_LINE + " </note>" + NEW_LINE + "</notes>"), headersToIgnore) ); assertEquals( response() .withStatusCode(OK_200.code()) .withReasonPhrase(OK_200.reasonPhrase()) .withBody("some_body"), makeRequest( request() .withPath(calculatePath("some_path")) .withMethod("POST") .withBody("<?xml version=\"1.0\" encoding=\"utf-8\"?>" + NEW_LINE + "<notes>" + NEW_LINE + " <note>" + NEW_LINE + " <to>Bob</to>" + NEW_LINE + " <from>Bill</from>" + NEW_LINE + " <heading>Reminder</heading>" + NEW_LINE + " <body>Buy Bread</body>" + NEW_LINE + " </note>" + NEW_LINE + " <note>" + NEW_LINE + " <to>Jack</to>" + NEW_LINE + " <from>Jill</from>" + NEW_LINE + " <heading>Reminder</heading>" + NEW_LINE + " <body>Wash Shirts</body>" + NEW_LINE + " </note>" + NEW_LINE + "</notes>"), headersToIgnore) ); // - in https assertEquals( response() .withStatusCode(OK_200.code()) .withReasonPhrase(OK_200.reasonPhrase()) .withBody("some_body"), makeRequest( request() .withSecure(true) .withPath(calculatePath("some_path")) .withMethod("POST") .withBody("<?xml version=\"1.0\" encoding=\"utf-8\"?>" + NEW_LINE + "<notes>" + NEW_LINE + " <note>" + NEW_LINE + " <to>Bob</to>" + NEW_LINE + " <from>Bill</from>" + NEW_LINE + " <heading>Reminder</heading>" + NEW_LINE + " <body>Buy Bread</body>" + NEW_LINE + " </note>" + NEW_LINE + " <note>" + NEW_LINE + " <to>Jack</to>" + NEW_LINE + " <from>Jill</from>" + NEW_LINE + " <heading>Reminder</heading>" + NEW_LINE + " <body>Wash Shirts</body>" + NEW_LINE + " </note>" + NEW_LINE + "</notes>"), headersToIgnore) ); } @Test public void shouldReturnResponseByMatchingBodyWithXmlSchemaByClasspath() { // when mockServerClient.when(request() .withBody( xmlSchemaFromResource("org/mockserver/model/testXmlSchema.xsd")), exactly(2) ) .respond( response() .withBody("some_body") ); // then // - in http assertEquals( response() .withStatusCode(NOT_FOUND_404.code()) .withReasonPhrase(NOT_FOUND_404.reasonPhrase()), makeRequest( request() .withMethod("POST") .withBody("<?xml version=\"1.0\" encoding=\"utf-8\"?>" + NEW_LINE + "<notes>" + NEW_LINE + " <note>" + NEW_LINE + " <to>Bob</to>" + NEW_LINE + " <heading>Reminder</heading>" + NEW_LINE + " <body>Buy Bread</body>" + NEW_LINE + " </note>" + NEW_LINE + " <note>" + NEW_LINE + " <to>Jack</to>" + NEW_LINE + " <from>Jill</from>" + NEW_LINE + " <heading>Reminder</heading>" + NEW_LINE + " <body>Wash Shirts</body>" + NEW_LINE + " </note>" + NEW_LINE + "</notes>"), headersToIgnore) ); assertEquals( response() .withStatusCode(OK_200.code()) .withReasonPhrase(OK_200.reasonPhrase()) .withBody("some_body"), makeRequest( request() .withPath(calculatePath("some_path")) .withMethod("POST") .withBody("<?xml version=\"1.0\" encoding=\"utf-8\"?>" + NEW_LINE + "<notes>" + NEW_LINE + " <note>" + NEW_LINE + " <to>Bob</to>" + NEW_LINE + " <from>Bill</from>" + NEW_LINE + " <heading>Reminder</heading>" + NEW_LINE + " <body>Buy Bread</body>" + NEW_LINE + " </note>" + NEW_LINE + " <note>" + NEW_LINE + " <to>Jack</to>" + NEW_LINE + " <from>Jill</from>" + NEW_LINE + " <heading>Reminder</heading>" + NEW_LINE + " <body>Wash Shirts</body>" + NEW_LINE + " </note>" + NEW_LINE + "</notes>"), headersToIgnore) ); // - in https assertEquals( response() .withStatusCode(OK_200.code()) .withReasonPhrase(OK_200.reasonPhrase()) .withBody("some_body"), makeRequest( request() .withSecure(true) .withPath(calculatePath("some_path")) .withMethod("POST") .withBody("<?xml version=\"1.0\" encoding=\"utf-8\"?>" + NEW_LINE + "<notes>" + NEW_LINE + " <note>" + NEW_LINE + " <to>Bob</to>" + NEW_LINE + " <from>Bill</from>" + NEW_LINE + " <heading>Reminder</heading>" + NEW_LINE + " <body>Buy Bread</body>" + NEW_LINE + " </note>" + NEW_LINE + " <note>" + NEW_LINE + " <to>Jack</to>" + NEW_LINE + " <from>Jill</from>" + NEW_LINE + " <heading>Reminder</heading>" + NEW_LINE + " <body>Wash Shirts</body>" + NEW_LINE + " </note>" + NEW_LINE + "</notes>"), headersToIgnore) ); } @Test public void shouldReturnPDFResponseByMatchingPath() throws IOException { // when byte[] pdfBytes = IOUtils.toByteArray(getClass().getClassLoader().getResourceAsStream("test.pdf")); mockServerClient .when( request() .withPath(calculatePath("ws/rest/user/[0-9]+/document/[0-9]+\\.pdf")) ) .respond( response() .withStatusCode(OK_200.code()) .withReasonPhrase(OK_200.reasonPhrase()) .withHeaders( header(CONTENT_TYPE.toString(), MediaType.PDF.toString()), header(CONTENT_DISPOSITION.toString(), "form-data; name=\"test.pdf\"; filename=\"test.pdf\""), header(CACHE_CONTROL.toString(), "must-revalidate, post-check=0, pre-check=0") ) .withBody(binary(pdfBytes)) ); // then // - in http assertEquals( response() .withStatusCode(OK_200.code()) .withReasonPhrase(OK_200.reasonPhrase()) .withHeaders( header(CONTENT_DISPOSITION.toString(), "form-data; name=\"test.pdf\"; filename=\"test.pdf\""), header(CACHE_CONTROL.toString(), "must-revalidate, post-check=0, pre-check=0"), header(CONTENT_TYPE.toString(), MediaType.PDF.toString()) ) .withBody(binary(pdfBytes)), makeRequest( request() .withPath(calculatePath("ws/rest/user/1/document/2.pdf")) .withMethod("GET"), headersToIgnore) ); // - in https assertEquals( response() .withStatusCode(OK_200.code()) .withReasonPhrase(OK_200.reasonPhrase()) .withHeaders( header(CONTENT_DISPOSITION.toString(), "form-data; name=\"test.pdf\"; filename=\"test.pdf\""), header(CACHE_CONTROL.toString(), "must-revalidate, post-check=0, pre-check=0"), header(CONTENT_TYPE.toString(), MediaType.PDF.toString()) ) .withBody(binary(pdfBytes)), makeRequest( request() .withSecure(true) .withPath(calculatePath("ws/rest/user/1/document/2.pdf")) .withMethod("GET"), headersToIgnore) ); } @Test public void shouldReturnPNGResponseByMatchingPath() throws IOException { // when byte[] pngBytes = IOUtils.toByteArray(getClass().getClassLoader().getResourceAsStream("test.png")); mockServerClient .when( request() .withPath(calculatePath("ws/rest/user/[0-9]+/icon/[0-9]+\\.png")) ) .respond( response() .withStatusCode(OK_200.code()) .withReasonPhrase(OK_200.reasonPhrase()) .withHeaders( header(CONTENT_TYPE.toString(), MediaType.PNG.toString()), header(CONTENT_DISPOSITION.toString(), "form-data; name=\"test.png\"; filename=\"test.png\"") ) .withBody(binary(pngBytes)) ); // then // - in http assertEquals( response() .withStatusCode(OK_200.code()) .withReasonPhrase(OK_200.reasonPhrase()) .withHeaders( header(CONTENT_DISPOSITION.toString(), "form-data; name=\"test.png\"; filename=\"test.png\""), header(CONTENT_TYPE.toString(), MediaType.PNG.toString()) ) .withBody(binary(pngBytes)), makeRequest( request() .withPath(calculatePath("ws/rest/user/1/icon/1.png")) .withMethod("GET"), headersToIgnore) ); // - in https assertEquals( response() .withStatusCode(OK_200.code()) .withReasonPhrase(OK_200.reasonPhrase()) .withHeaders( header(CONTENT_DISPOSITION.toString(), "form-data; name=\"test.png\"; filename=\"test.png\""), header(CONTENT_TYPE.toString(), MediaType.PNG.toString()) ) .withBody(binary(pngBytes)), makeRequest( request() .withSecure(true) .withPath(calculatePath("ws/rest/user/1/icon/1.png")) .withMethod("GET"), headersToIgnore) ); } @Test public void shouldReturnPDFResponseByMatchingBinaryPDFBody() throws IOException { // when byte[] pdfBytes = IOUtils.toByteArray(getClass().getClassLoader().getResourceAsStream("test.pdf")); mockServerClient .when( request().withBody(binary(pdfBytes)) ) .respond( response() .withStatusCode(OK_200.code()) .withReasonPhrase(OK_200.reasonPhrase()) .withHeaders( header(CONTENT_TYPE.toString(), MediaType.PDF.toString()), header(CONTENT_DISPOSITION.toString(), "form-data; name=\"test.pdf\"; filename=\"test.pdf\""), header(CACHE_CONTROL.toString(), "must-revalidate, post-check=0, pre-check=0") ) .withBody(binary(pdfBytes)) ); // then // - in http assertEquals( response() .withStatusCode(OK_200.code()) .withReasonPhrase(OK_200.reasonPhrase()) .withHeaders( header(CONTENT_DISPOSITION.toString(), "form-data; name=\"test.pdf\"; filename=\"test.pdf\""), header(CACHE_CONTROL.toString(), "must-revalidate, post-check=0, pre-check=0"), header(CONTENT_TYPE.toString(), MediaType.PDF.toString()) ) .withBody(binary(pdfBytes)), makeRequest( request() .withPath(calculatePath("ws/rest/user/1/document/2.pdf")) .withBody(binary(pdfBytes)) .withMethod("POST"), headersToIgnore) ); // - in https assertEquals( response() .withStatusCode(OK_200.code()) .withReasonPhrase(OK_200.reasonPhrase()) .withHeaders( header(CONTENT_DISPOSITION.toString(), "form-data; name=\"test.pdf\"; filename=\"test.pdf\""), header(CACHE_CONTROL.toString(), "must-revalidate, post-check=0, pre-check=0"), header(CONTENT_TYPE.toString(), MediaType.PDF.toString()) ) .withBody(binary(pdfBytes)), makeRequest( request() .withSecure(true) .withPath(calculatePath("ws/rest/user/1/document/2.pdf")) .withBody(binary(pdfBytes)) .withMethod("POST"), headersToIgnore) ); } @Test public void shouldReturnPNGResponseByMatchingBinaryPNGBody() throws IOException { // when byte[] pngBytes = IOUtils.toByteArray(getClass().getClassLoader().getResourceAsStream("test.png")); mockServerClient .when( request().withBody(binary(pngBytes)) ) .respond( response() .withStatusCode(OK_200.code()) .withReasonPhrase(OK_200.reasonPhrase()) .withHeaders( header(CONTENT_TYPE.toString(), MediaType.PNG.toString()), header(CONTENT_DISPOSITION.toString(), "form-data; name=\"test.png\"; filename=\"test.png\"") ) .withBody(binary(pngBytes)) ); // then // - in http assertEquals( response() .withStatusCode(OK_200.code()) .withReasonPhrase(OK_200.reasonPhrase()) .withHeaders( header(CONTENT_DISPOSITION.toString(), "form-data; name=\"test.png\"; filename=\"test.png\""), header(CONTENT_TYPE.toString(), MediaType.PNG.toString()) ) .withBody(binary(pngBytes)), makeRequest( request() .withPath(calculatePath("ws/rest/user/1/icon/1.png")) .withBody(binary(pngBytes)) .withMethod("POST"), headersToIgnore) ); // - in https assertEquals( response() .withStatusCode(OK_200.code()) .withReasonPhrase(OK_200.reasonPhrase()) .withHeaders( header(CONTENT_DISPOSITION.toString(), "form-data; name=\"test.png\"; filename=\"test.png\""), header(CONTENT_TYPE.toString(), MediaType.PNG.toString()) ) .withBody(binary(pngBytes)), makeRequest( request() .withSecure(true) .withPath(calculatePath("ws/rest/user/1/icon/1.png")) .withBody(binary(pngBytes)) .withMethod("POST"), headersToIgnore) ); } @Test public void shouldReturnResponseByNotMatchingPathWithNotOperator() { // when mockServerClient .when( request() .withPath(not(calculatePath("some_path"))) ) .respond( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withReasonPhrase(HttpStatusCode.ACCEPTED_202.reasonPhrase()) .withBody("some_body_response") ); // then // - in http assertEquals( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withReasonPhrase(HttpStatusCode.ACCEPTED_202.reasonPhrase()) .withBody("some_body_response"), makeRequest( request() .withPath(calculatePath("some_other_path")), headersToIgnore) ); // - in https assertEquals( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withReasonPhrase(HttpStatusCode.ACCEPTED_202.reasonPhrase()) .withBody("some_body_response"), makeRequest( request() .withPath(calculatePath("some_other_path")), headersToIgnore) ); } @Test public void shouldReturnResponseByNotMatchingMethodWithNotOperator() { // when mockServerClient .when( request() .withMethod(not("GET")) ) .respond( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withReasonPhrase(HttpStatusCode.ACCEPTED_202.reasonPhrase()) .withBody("some_body_response") ); // then // - in http assertEquals( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withReasonPhrase(HttpStatusCode.ACCEPTED_202.reasonPhrase()) .withBody("some_body_response"), makeRequest( request() .withMethod("POST"), headersToIgnore) ); // - in https assertEquals( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withReasonPhrase(HttpStatusCode.ACCEPTED_202.reasonPhrase()) .withBody("some_body_response"), makeRequest( request() .withMethod("POST"), headersToIgnore) ); } @Test public void shouldReturnResponseByMatchingPathAndMethodAndBody() { // when mockServerClient .when( request() .withMethod("POST") .withPath(calculatePath("some_pathRequest")) .withBody("some_bodyRequest") ) .respond( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withReasonPhrase(HttpStatusCode.ACCEPTED_202.reasonPhrase()) .withBody("some_body_response") .withHeaders(header("headerNameResponse", "headerValueResponse")) ); // then // - in http assertEquals( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withReasonPhrase(HttpStatusCode.ACCEPTED_202.reasonPhrase()) .withBody("some_body_response") .withHeaders( header("headerNameResponse", "headerValueResponse") ), makeRequest( request() .withMethod("POST") .withPath(calculatePath("some_pathRequest")) .withQueryStringParameters( param("queryStringParameterOneName", "queryStringParameterOneValue"), param("queryStringParameterTwoName", "queryStringParameterTwoValue") ) .withBody("some_bodyRequest") .withHeaders(header("headerNameRequest", "headerValueRequest")) .withCookies(cookie("cookieNameRequest", "cookieValueRequest")), headersToIgnore) ); // - in https assertEquals( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withReasonPhrase(HttpStatusCode.ACCEPTED_202.reasonPhrase()) .withBody("some_body_response") .withHeaders( header("headerNameResponse", "headerValueResponse") ), makeRequest( request() .withMethod("POST") .withSecure(true) .withPath(calculatePath("some_pathRequest")) .withQueryStringParameters( param("queryStringParameterOneName", "queryStringParameterOneValue"), param("queryStringParameterTwoName", "queryStringParameterTwoValue") ) .withBody("some_bodyRequest") .withHeaders(header("headerNameRequest", "headerValueRequest")) .withCookies(cookie("cookieNameRequest", "cookieValueRequest")), headersToIgnore) ); } @Test public void shouldReturnResponseByMatchingPathAndMethodAndQueryStringParameters() { // when mockServerClient .when( request() .withMethod("GET") .withPath(calculatePath("some_pathRequest")) .withQueryStringParameters( param("queryStringParameterOneName", "queryStringParameterOneValue"), param("queryStringParameterTwoName", "queryStringParameterTwoValue") ) ) .respond( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withReasonPhrase(HttpStatusCode.ACCEPTED_202.reasonPhrase()) .withBody("some_body_response") .withCookies(cookie("cookieNameResponse", "cookieValueResponse")) ); // then // - in http assertEquals( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withReasonPhrase(HttpStatusCode.ACCEPTED_202.reasonPhrase()) .withBody("some_body_response") .withCookies(cookie("cookieNameResponse", "cookieValueResponse")) .withHeaders( header(SET_COOKIE.toString(), "cookieNameResponse=cookieValueResponse") ), makeRequest( request() .withMethod("GET") .withPath(calculatePath("some_pathRequest")) .withQueryStringParameters( param("queryStringParameterOneName", "queryStringParameterOneValue"), param("queryStringParameterTwoName", "queryStringParameterTwoValue") ) .withHeaders(header("headerNameRequest", "headerValueRequest")) .withCookies(cookie("cookieNameRequest", "cookieValueRequest")), headersToIgnore) ); // - in https assertEquals( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withReasonPhrase(HttpStatusCode.ACCEPTED_202.reasonPhrase()) .withBody("some_body_response") .withCookies(cookie("cookieNameResponse", "cookieValueResponse")) .withHeaders( header(SET_COOKIE.toString(), "cookieNameResponse=cookieValueResponse") ), makeRequest( request() .withMethod("GET") .withSecure(true) .withPath(calculatePath("some_pathRequest")) .withQueryStringParameters( param("queryStringParameterOneName", "queryStringParameterOneValue"), param("queryStringParameterTwoName", "queryStringParameterTwoValue") ) .withHeaders(header("headerNameRequest", "headerValueRequest")) .withCookies(cookie("cookieNameRequest", "cookieValueRequest")), headersToIgnore) ); } @Test public void shouldReturnResponseByMatchingPathAndMethodAndHeaders() { // when mockServerClient .when( request() .withMethod("GET") .withPath(calculatePath("some_pathRequest")) .withHeaders( header("requestHeaderNameOne", "requestHeaderValueOne_One", "requestHeaderValueOne_Two"), header("requestHeaderNameTwo", "requestHeaderValueTwo") ) ) .respond( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withReasonPhrase(HttpStatusCode.ACCEPTED_202.reasonPhrase()) .withBody("some_body_response") .withCookies(cookie("cookieNameResponse", "cookieValueResponse")) ); // then // - in http assertEquals( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withReasonPhrase(HttpStatusCode.ACCEPTED_202.reasonPhrase()) .withBody("some_body_response") .withCookies(cookie("cookieNameResponse", "cookieValueResponse")) .withHeaders( header(SET_COOKIE.toString(), "cookieNameResponse=cookieValueResponse") ), makeRequest( request() .withMethod("GET") .withPath(calculatePath("some_pathRequest")) .withHeaders( header("requestHeaderNameOne", "requestHeaderValueOne_One", "requestHeaderValueOne_Two"), header("requestHeaderNameTwo", "requestHeaderValueTwo") ) .withCookies(cookie("cookieNameRequest", "cookieValueRequest")), headersToIgnore) ); // - in https assertEquals( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withReasonPhrase(HttpStatusCode.ACCEPTED_202.reasonPhrase()) .withBody("some_body_response") .withCookies(cookie("cookieNameResponse", "cookieValueResponse")) .withHeaders( header(SET_COOKIE.toString(), "cookieNameResponse=cookieValueResponse") ), makeRequest( request() .withMethod("GET") .withSecure(true) .withPath(calculatePath("some_pathRequest")) .withHeaders( header("requestHeaderNameOne", "requestHeaderValueOne_One", "requestHeaderValueOne_Two"), header("requestHeaderNameTwo", "requestHeaderValueTwo") ) .withCookies(cookie("cookieNameRequest", "cookieValueRequest")), headersToIgnore) ); } @Test public void shouldReturnResponseByMatchingPathAndMethodAndCookies() { // when mockServerClient .when( request() .withMethod("GET") .withPath(calculatePath("some_pathRequest")) .withCookies( cookie("requestCookieNameOne", "requestCookieValueOne"), cookie("requestCookieNameTwo", "requestCookieValueTwo") ) ) .respond( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withReasonPhrase(HttpStatusCode.ACCEPTED_202.reasonPhrase()) .withBody("some_body_response") .withCookies( cookie("responseCookieNameOne", "responseCookieValueOne"), cookie("responseCookieNameTwo", "responseCookieValueTwo") ) ); // then // - in http - cookie objects assertEquals( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withReasonPhrase(HttpStatusCode.ACCEPTED_202.reasonPhrase()) .withBody("some_body_response") .withCookies( cookie("responseCookieNameOne", "responseCookieValueOne"), cookie("responseCookieNameTwo", "responseCookieValueTwo") ) .withHeaders( header(SET_COOKIE.toString(), "responseCookieNameOne=responseCookieValueOne", "responseCookieNameTwo=responseCookieValueTwo") ), makeRequest( request() .withMethod("GET") .withPath(calculatePath("some_pathRequest")) .withHeaders( header("headerNameRequest", "headerValueRequest"), header(CONTENT_TYPE.toString(), MediaType.create("text", "plain").toString()) ) .withCookies( cookie("requestCookieNameOne", "requestCookieValueOne"), cookie("requestCookieNameTwo", "requestCookieValueTwo") ), headersToIgnore) ); // - in http - cookie header assertEquals( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withReasonPhrase(HttpStatusCode.ACCEPTED_202.reasonPhrase()) .withBody("some_body_response") .withCookies( cookie("responseCookieNameOne", "responseCookieValueOne"), cookie("responseCookieNameTwo", "responseCookieValueTwo") ) .withHeaders( header(SET_COOKIE.toString(), "responseCookieNameOne=responseCookieValueOne", "responseCookieNameTwo=responseCookieValueTwo") ), makeRequest( request() .withMethod("GET") .withPath(calculatePath("some_pathRequest")) .withHeaders( header("headerNameRequest", "headerValueRequest"), header("Cookie", "requestCookieNameOne=requestCookieValueOne; requestCookieNameTwo=requestCookieValueTwo") ), headersToIgnore) ); // - in https - cookie objects assertEquals( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withReasonPhrase(HttpStatusCode.ACCEPTED_202.reasonPhrase()) .withBody("some_body_response") .withCookies( cookie("responseCookieNameOne", "responseCookieValueOne"), cookie("responseCookieNameTwo", "responseCookieValueTwo") ) .withHeaders( header(SET_COOKIE.toString(), "responseCookieNameOne=responseCookieValueOne", "responseCookieNameTwo=responseCookieValueTwo") ), makeRequest( request() .withMethod("GET") .withSecure(true) .withPath(calculatePath("some_pathRequest")) .withHeaders( header("headerNameRequest", "headerValueRequest") ) .withCookies( cookie("requestCookieNameOne", "requestCookieValueOne"), cookie("requestCookieNameTwo", "requestCookieValueTwo") ), headersToIgnore) ); // - in https - cookie header assertEquals( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withReasonPhrase(HttpStatusCode.ACCEPTED_202.reasonPhrase()) .withBody("some_body_response") .withCookies( cookie("responseCookieNameOne", "responseCookieValueOne"), cookie("responseCookieNameTwo", "responseCookieValueTwo") ) .withHeaders( header(SET_COOKIE.toString(), "responseCookieNameOne=responseCookieValueOne", "responseCookieNameTwo=responseCookieValueTwo") ), makeRequest( request() .withMethod("GET") .withSecure(true) .withPath(calculatePath("some_pathRequest")) .withHeaders( header("headerNameRequest", "headerValueRequest"), header("Cookie", "requestCookieNameOne=requestCookieValueOne; requestCookieNameTwo=requestCookieValueTwo") ), headersToIgnore) ); } @Test public void shouldReturnResponseByMatchingPathAndMethodAndQueryStringParametersAndBodyParameters() { // when mockServerClient .when( request() .withMethod("POST") .withPath(calculatePath("some_pathRequest")) .withQueryStringParameters( param("queryStringParameterOneName", "queryStringParameterOneValueOne", "queryStringParameterOneValueTwo"), param("queryStringParameterTwoName", "queryStringParameterTwoValue") ) .withBody(params(param("bodyParameterName", "bodyParameterValue"))) ) .respond( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withReasonPhrase(HttpStatusCode.ACCEPTED_202.reasonPhrase()) .withBody("some_body") ); // then // - in http - url query string assertEquals( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withReasonPhrase(HttpStatusCode.ACCEPTED_202.reasonPhrase()) .withBody("some_body"), makeRequest( request() .withMethod("POST") .withPath(calculatePath("some_pathRequest")) .withQueryStringParameters( param("queryStringParameterOneName", "queryStringParameterOneValueOne", "queryStringParameterOneValueTwo"), param("queryStringParameterTwoName", "queryStringParameterTwoValue") ) .withBody(params(param("bodyParameterName", "bodyParameterValue"))), headersToIgnore) ); // - in https - query string parameter objects assertEquals( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withReasonPhrase(HttpStatusCode.ACCEPTED_202.reasonPhrase()) .withBody("some_body"), makeRequest( request() .withSecure(true) .withMethod("POST") .withPath(calculatePath("some_pathRequest")) .withQueryStringParameters( param("queryStringParameterOneName", "queryStringParameterOneValueOne", "queryStringParameterOneValueTwo"), param("queryStringParameterTwoName", "queryStringParameterTwoValue") ) .withBody(params(param("bodyParameterName", "bodyParameterValue"))), headersToIgnore) ); } @Test public void shouldReturnResponseByMatchingPathAndMethodAndQueryStringParametersAndBody() { // when mockServerClient .when( request() .withMethod("POST") .withPath(calculatePath("some_pathRequest")) .withQueryStringParameters( param("queryStringParameterOneName", "queryStringParameterOneValueOne", "queryStringParameterOneValueTwo"), param("queryStringParameterTwoName", "queryStringParameterTwoValue") ) .withBody("some_bodyRequest") ) .respond( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withReasonPhrase(HttpStatusCode.ACCEPTED_202.reasonPhrase()) .withBody("some_body_response") .withHeaders(header("headerNameResponse", "headerValueResponse")) .withCookies(cookie("cookieNameResponse", "cookieValueResponse")) ); // then // - in http - url query string assertEquals( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withReasonPhrase(HttpStatusCode.ACCEPTED_202.reasonPhrase()) .withBody("some_body_response") .withCookies(cookie("cookieNameResponse", "cookieValueResponse")) .withHeaders( header("headerNameResponse", "headerValueResponse"), header(SET_COOKIE.toString(), "cookieNameResponse=cookieValueResponse") ), makeRequest( request() .withMethod("POST") .withPath(calculatePath("some_pathRequest")) .withQueryStringParameters( param("queryStringParameterOneName", "queryStringParameterOneValueOne", "queryStringParameterOneValueTwo"), param("queryStringParameterTwoName", "queryStringParameterTwoValue") ) .withBody("some_bodyRequest") .withHeaders(header("headerNameRequest", "headerValueRequest")) .withCookies(cookie("cookieNameRequest", "cookieValueRequest")), headersToIgnore) ); // - in http - query string parameter objects assertEquals( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withReasonPhrase(HttpStatusCode.ACCEPTED_202.reasonPhrase()) .withBody("some_body_response") .withCookies(cookie("cookieNameResponse", "cookieValueResponse")) .withHeaders( header("headerNameResponse", "headerValueResponse"), header(SET_COOKIE.toString(), "cookieNameResponse=cookieValueResponse") ), makeRequest( request() .withMethod("POST") .withPath(calculatePath("some_pathRequest")) .withQueryStringParameters( param("queryStringParameterOneName", "queryStringParameterOneValueOne", "queryStringParameterOneValueTwo"), param("queryStringParameterTwoName", "queryStringParameterTwoValue") ) .withBody("some_bodyRequest") .withHeaders(header("headerNameRequest", "headerValueRequest")) .withCookies(cookie("cookieNameRequest", "cookieValueRequest")), headersToIgnore) ); // - in https - url string and query string parameter objects assertEquals( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withReasonPhrase(HttpStatusCode.ACCEPTED_202.reasonPhrase()) .withBody("some_body_response") .withCookies(cookie("cookieNameResponse", "cookieValueResponse")) .withHeaders( header("headerNameResponse", "headerValueResponse"), header(SET_COOKIE.toString(), "cookieNameResponse=cookieValueResponse") ), makeRequest( request() .withMethod("POST") .withPath(calculatePath("some_pathRequest")) .withQueryStringParameters( param("queryStringParameterOneName", "queryStringParameterOneValueOne", "queryStringParameterOneValueTwo"), param("queryStringParameterTwoName", "queryStringParameterTwoValue") ) .withBody("some_bodyRequest") .withHeaders(header("headerNameRequest", "headerValueRequest")) .withCookies(cookie("cookieNameRequest", "cookieValueRequest")), headersToIgnore) ); } @Test public void shouldReturnResponseByMatchingPathAndMethodAndBodyParameters() { // when mockServerClient .when( request() .withMethod("POST") .withPath(calculatePath("some_pathRequest")) .withBody(params( param("bodyParameterOneName", "Parameter One Value One", "Parameter One Value Two"), param("bodyParameterTwoName", "Parameter Two") )) ) .respond( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withReasonPhrase(HttpStatusCode.ACCEPTED_202.reasonPhrase()) .withBody("some_body_response") .withHeaders(header("headerNameResponse", "headerValueResponse")) .withCookies(cookie("cookieNameResponse", "cookieValueResponse")) ); // then // - in http - body string assertEquals( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withReasonPhrase(HttpStatusCode.ACCEPTED_202.reasonPhrase()) .withBody("some_body_response") .withCookies(cookie("cookieNameResponse", "cookieValueResponse")) .withHeaders( header("headerNameResponse", "headerValueResponse"), header(SET_COOKIE.toString(), "cookieNameResponse=cookieValueResponse") ), makeRequest( request() .withMethod("POST") .withPath(calculatePath("some_pathRequest")) .withBody(new StringBody("bodyParameterOneName=Parameter+One+Value+One" + "&bodyParameterOneName=Parameter+One+Value+Two" + "&bodyParameterTwoName=Parameter+Two")) .withHeaders(header("headerNameRequest", "headerValueRequest")) .withCookies(cookie("cookieNameRequest", "cookieValueRequest")), headersToIgnore) ); // - in http - body parameter objects assertEquals( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withReasonPhrase(HttpStatusCode.ACCEPTED_202.reasonPhrase()) .withBody("some_body_response") .withCookies(cookie("cookieNameResponse", "cookieValueResponse")) .withHeaders( header("headerNameResponse", "headerValueResponse"), header(SET_COOKIE.toString(), "cookieNameResponse=cookieValueResponse") ), makeRequest( request() .withMethod("POST") .withPath(calculatePath("some_pathRequest")) .withBody(params( param("bodyParameterOneName", "Parameter One Value One", "Parameter One Value Two"), param("bodyParameterTwoName", "Parameter Two") )) .withHeaders(header("headerNameRequest", "headerValueRequest")) .withCookies(cookie("cookieNameRequest", "cookieValueRequest")), headersToIgnore) ); // - in https - url string and query string parameter objects assertEquals( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withReasonPhrase(HttpStatusCode.ACCEPTED_202.reasonPhrase()) .withBody("some_body_response") .withCookies(cookie("cookieNameResponse", "cookieValueResponse")) .withHeaders( header("headerNameResponse", "headerValueResponse"), header(SET_COOKIE.toString(), "cookieNameResponse=cookieValueResponse") ), makeRequest( request() .withMethod("POST") .withPath(calculatePath("some_pathRequest")) .withBody(params( param("bodyParameterOneName", "Parameter One Value One", "Parameter One Value Two"), param("bodyParameterTwoName", "Parameter Two") )) .withHeaders(header("headerNameRequest", "headerValueRequest")) .withCookies(cookie("cookieNameRequest", "cookieValueRequest")), headersToIgnore) ); } @Test public void shouldReturnResponseByMatchingPathAndMethodAndParametersAndHeadersAndCookies() { // when mockServerClient .when( request() .withMethod("PUT") .withPath(calculatePath("some_pathRequest")) .withBody(new StringBody("bodyParameterOneName=Parameter+One+Value+One" + "&bodyParameterOneName=Parameter+One+Value+Two" + "&bodyParameterTwoName=Parameter+Two")) .withHeaders(header("headerNameRequest", "headerValueRequest")) .withCookies(cookie("cookieNameRequest", "cookieValueRequest")) ) .respond( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withReasonPhrase(HttpStatusCode.ACCEPTED_202.reasonPhrase()) .withBody("some_body_response") .withHeaders(header("headerNameResponse", "headerValueResponse")) .withCookies(cookie("cookieNameResponse", "cookieValueResponse")) ); // then // - in http - body string assertEquals( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withReasonPhrase(HttpStatusCode.ACCEPTED_202.reasonPhrase()) .withBody("some_body_response") .withCookies(cookie("cookieNameResponse", "cookieValueResponse")) .withHeaders( header("headerNameResponse", "headerValueResponse"), header(SET_COOKIE.toString(), "cookieNameResponse=cookieValueResponse") ), makeRequest( request() .withMethod("PUT") .withPath(calculatePath("some_pathRequest")) .withBody(new StringBody("bodyParameterOneName=Parameter+One+Value+One" + "&bodyParameterOneName=Parameter+One+Value+Two" + "&bodyParameterTwoName=Parameter+Two")) .withHeaders( header("headerNameRequest", "headerValueRequest"), header("Cookie", "cookieNameRequest=cookieValueRequest") ), headersToIgnore) ); // - in http - body parameter objects assertEquals( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withReasonPhrase(HttpStatusCode.ACCEPTED_202.reasonPhrase()) .withBody("some_body_response") .withCookies(cookie("cookieNameResponse", "cookieValueResponse")) .withHeaders( header("headerNameResponse", "headerValueResponse"), header(SET_COOKIE.toString(), "cookieNameResponse=cookieValueResponse") ), makeRequest( request() .withMethod("PUT") .withPath(calculatePath("some_pathRequest")) .withBody(params( param("bodyParameterOneName", "Parameter One Value One", "Parameter One Value Two"), param("bodyParameterTwoName", "Parameter Two") )) .withHeaders(header("headerNameRequest", "headerValueRequest")) .withCookies(cookie("cookieNameRequest", "cookieValueRequest")), headersToIgnore) ); } @Test public void shouldReturnResponseByNotMatchingBodyParameterWithNotOperatorForNameAndValue() { // when mockServerClient .when( request() .withMethod("POST") .withPath(calculatePath("some_pathRequest")) .withBody(params( param(not("bodyParameterOneName"), not("Parameter One Value One"), not("Parameter One Value Two")), param("bodyParameterTwoName", "Parameter Two") )) ) .respond( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withReasonPhrase(HttpStatusCode.ACCEPTED_202.reasonPhrase()) .withBody("some_body_response") ); // then // wrong query string parameter name assertEquals( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withReasonPhrase(HttpStatusCode.ACCEPTED_202.reasonPhrase()) .withBody("some_body_response"), makeRequest( request() .withMethod("POST") .withPath(calculatePath("some_pathRequest")) .withBody(params( param("OTHERBodyParameterOneName", "Parameter One Value One", "Parameter One Value Two"), param("bodyParameterTwoName", "Parameter Two") )) .withHeaders(header("headerNameRequest", "headerValueRequest")) .withCookies(cookie("cookieNameRequest", "cookieValueRequest")), headersToIgnore) ); // wrong query string parameter name assertEquals( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withReasonPhrase(HttpStatusCode.ACCEPTED_202.reasonPhrase()) .withBody("some_body_response"), makeRequest( request() .withMethod("POST") .withPath(calculatePath("some_pathRequest")) .withBody(new StringBody("OTHERBodyParameterOneName=Parameter+One+Value+One" + "&OTHERBodyParameterOneName=Parameter+One+Value+Two" + "&bodyParameterTwoName=Parameter+Two")) .withHeaders(header("headerNameRequest", "headerValueRequest")) .withCookies(cookie("cookieNameRequest", "cookieValueRequest")), headersToIgnore) ); // wrong query string parameter value assertEquals( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withReasonPhrase(HttpStatusCode.ACCEPTED_202.reasonPhrase()) .withBody("some_body_response"), makeRequest( request() .withMethod("POST") .withPath(calculatePath("some_pathRequest")) .withBody(params( param("bodyParameterOneName", "OTHER Parameter One Value One", "OTHER Parameter One Value Two"), param("bodyParameterTwoName", "Parameter Two") )) .withHeaders(header("headerNameRequest", "headerValueRequest")) .withCookies(cookie("cookieNameRequest", "cookieValueRequest")), headersToIgnore) ); // wrong query string parameter value assertEquals( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withReasonPhrase(HttpStatusCode.ACCEPTED_202.reasonPhrase()) .withBody("some_body_response"), makeRequest( request() .withMethod("POST") .withPath(calculatePath("some_pathRequest")) .withBody(new StringBody("bodyParameterOneName=OTHER Parameter+One+Value+One" + "&bodyParameterOneName=OTHER Parameter+One+Value+Two" + "&bodyParameterTwoName=Parameter+Two")) .withHeaders(header("headerNameRequest", "headerValueRequest")) .withCookies(cookie("cookieNameRequest", "cookieValueRequest")), headersToIgnore) ); } @Test public void shouldReturnResponseByNotMatchingBodyParameterWithNotOperatorForName() { // when mockServerClient .when( request() .withMethod("POST") .withPath(calculatePath("some_pathRequest")) .withBody(params( param(not("bodyParameterOneName"), string("Parameter One Value One"), string("Parameter One Value Two")), param("bodyParameterTwoName", "Parameter Two") )) ) .respond( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withReasonPhrase(HttpStatusCode.ACCEPTED_202.reasonPhrase()) .withBody("some_body_response") ); // then // wrong query string parameter name assertEquals( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withReasonPhrase(HttpStatusCode.ACCEPTED_202.reasonPhrase()) .withBody("some_body_response"), makeRequest( request() .withMethod("POST") .withPath(calculatePath("some_pathRequest")) .withBody(params( param("OTHERBodyParameterOneName", "Parameter One Value One", "Parameter One Value Two"), param("bodyParameterTwoName", "Parameter Two") )) .withHeaders(header("headerNameRequest", "headerValueRequest")) .withCookies(cookie("cookieNameRequest", "cookieValueRequest")), headersToIgnore) ); // wrong query string parameter name assertEquals( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withReasonPhrase(HttpStatusCode.ACCEPTED_202.reasonPhrase()) .withBody("some_body_response"), makeRequest( request() .withMethod("POST") .withPath(calculatePath("some_pathRequest")) .withBody(new StringBody("OTHERBodyParameterOneName=Parameter+One+Value+One" + "&OTHERBodyParameterOneName=Parameter+One+Value+Two" + "&bodyParameterTwoName=Parameter+Two")) .withHeaders(header("headerNameRequest", "headerValueRequest")) .withCookies(cookie("cookieNameRequest", "cookieValueRequest")), headersToIgnore) ); } @Test public void shouldReturnResponseByNotMatchingBodyParameterWithNotOperatorForValue() { // when mockServerClient .when( request() .withMethod("POST") .withPath(calculatePath("some_pathRequest")) .withBody(params( param(string("bodyParameterOneName"), not("Parameter One Value One"), not("Parameter One Value Two")), param("bodyParameterTwoName", "Parameter Two") )) ) .respond( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withReasonPhrase(HttpStatusCode.ACCEPTED_202.reasonPhrase()) .withBody("some_body_response") ); // then // wrong query string parameter value assertEquals( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withReasonPhrase(HttpStatusCode.ACCEPTED_202.reasonPhrase()) .withBody("some_body_response"), makeRequest( request() .withMethod("POST") .withPath(calculatePath("some_pathRequest")) .withBody(params( param("bodyParameterOneName", "OTHER Parameter One Value One", "OTHER Parameter One Value Two"), param("bodyParameterTwoName", "Parameter Two") )) .withHeaders(header("headerNameRequest", "headerValueRequest")) .withCookies(cookie("cookieNameRequest", "cookieValueRequest")), headersToIgnore) ); // wrong query string parameter value assertEquals( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withReasonPhrase(HttpStatusCode.ACCEPTED_202.reasonPhrase()) .withBody("some_body_response"), makeRequest( request() .withMethod("POST") .withPath(calculatePath("some_pathRequest")) .withBody(new StringBody("bodyParameterOneName=OTHER Parameter+One+Value+One" + "&bodyParameterOneName=OTHER Parameter+One+Value+Two" + "&bodyParameterTwoName=Parameter+Two")) .withHeaders(header("headerNameRequest", "headerValueRequest")) .withCookies(cookie("cookieNameRequest", "cookieValueRequest")), headersToIgnore) ); } @Test public void shouldReturnResponseByNotMatchingQueryStringParameterWithNotOperatorForNameAndValue() { // when mockServerClient .when( request() .withMethod("POST") .withPath(calculatePath("some_pathRequest")) .withQueryStringParameters( param(not("queryStringParameterOneName"), not("Parameter One Value One"), not("Parameter One Value Two")), param("queryStringParameterTwoName", "Parameter Two") ) ) .respond( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withReasonPhrase(HttpStatusCode.ACCEPTED_202.reasonPhrase()) .withBody("some_body_response") ); // then // wrong query string parameter name assertEquals( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withReasonPhrase(HttpStatusCode.ACCEPTED_202.reasonPhrase()) .withBody("some_body_response"), makeRequest( request() .withMethod("POST") .withPath(calculatePath("some_pathRequest")) .withQueryStringParameters( param("OTHERQueryStringParameterOneName", "Parameter One Value One", "Parameter One Value Two"), param("queryStringParameterTwoName", "Parameter Two") ), headersToIgnore) ); // wrong query string parameter value assertEquals( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withReasonPhrase(HttpStatusCode.ACCEPTED_202.reasonPhrase()) .withBody("some_body_response"), makeRequest( request() .withMethod("POST") .withPath(calculatePath("some_pathRequest")) .withQueryStringParameters( param("queryStringParameterOneName", "OTHER Parameter One Value One", "OTHER Parameter One Value Two"), param("queryStringParameterTwoName", "Parameter Two") ), headersToIgnore) ); } @Test public void shouldReturnResponseByNotMatchingQueryStringParameterWithNotOperatorForName() { // when mockServerClient .when( request() .withMethod("POST") .withPath(calculatePath("some_pathRequest")) .withQueryStringParameters( param(not("queryStringParameterOneName"), string("Parameter One Value One"), string("Parameter One Value Two")), param("queryStringParameterTwoName", "Parameter Two") ) ) .respond( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withReasonPhrase(HttpStatusCode.ACCEPTED_202.reasonPhrase()) .withBody("some_body_response") ); // then // wrong query string parameter name assertEquals( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withReasonPhrase(HttpStatusCode.ACCEPTED_202.reasonPhrase()) .withBody("some_body_response"), makeRequest( request() .withMethod("POST") .withPath(calculatePath("some_pathRequest")) .withQueryStringParameters( param("OTHERQueryStringParameterOneName", "Parameter One Value One", "Parameter One Value Two"), param("queryStringParameterTwoName", "Parameter Two") ), headersToIgnore) ); } @Test public void shouldReturnResponseByNotMatchingQueryStringParameterWithNotOperatorForValue() { // when mockServerClient .when( request() .withMethod("POST") .withPath(calculatePath("some_pathRequest")) .withQueryStringParameters( param(string("queryStringParameterOneName"), not("Parameter One Value One"), not("Parameter One Value Two")), param("queryStringParameterTwoName", "Parameter Two") ) ) .respond( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withReasonPhrase(HttpStatusCode.ACCEPTED_202.reasonPhrase()) .withBody("some_body_response") ); // then // wrong query string parameter value assertEquals( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withReasonPhrase(HttpStatusCode.ACCEPTED_202.reasonPhrase()) .withBody("some_body_response"), makeRequest( request() .withMethod("POST") .withPath(calculatePath("some_pathRequest")) .withQueryStringParameters( param("queryStringParameterOneName", "OTHER Parameter One Value One", "OTHER Parameter One Value Two"), param("queryStringParameterTwoName", "Parameter Two") ), headersToIgnore) ); } @Test public void shouldReturnResponseByNotMatchingCookieWithNotOperatorForNameAndValue() { // when mockServerClient .when( request() .withMethod("GET") .withPath(calculatePath("some_pathRequest")) .withCookies( cookie(not("requestCookieNameOne"), not("requestCookieValueOne")), cookie("requestCookieNameTwo", "requestCookieValueTwo") ) ) .respond( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withReasonPhrase(HttpStatusCode.ACCEPTED_202.reasonPhrase()) .withBody("some_body_response") ); // then // wrong query string cookie name assertEquals( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withReasonPhrase(HttpStatusCode.ACCEPTED_202.reasonPhrase()) .withBody("some_body_response"), makeRequest( request() .withMethod("GET") .withPath(calculatePath("some_pathRequest")) .withCookies( cookie("OTHERrequestCookieNameOne", "requestCookieValueOne"), cookie("requestCookieNameTwo", "requestCookieValueTwo") ), headersToIgnore) ); // wrong query string cookie value assertEquals( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withReasonPhrase(HttpStatusCode.ACCEPTED_202.reasonPhrase()) .withBody("some_body_response"), makeRequest( request() .withMethod("GET") .withPath(calculatePath("some_pathRequest")) .withCookies( cookie("requestCookieNameOne", "OTHERrequestCookieValueOne"), cookie("requestCookieNameTwo", "requestCookieValueTwo") ), headersToIgnore) ); } @Test public void shouldReturnResponseByNotMatchingCookieWithNotOperatorForName() { // when mockServerClient .when( request() .withMethod("GET") .withPath(calculatePath("some_pathRequest")) .withCookies( cookie(not("requestCookieNameOne"), string("requestCookieValueOne")), cookie("requestCookieNameTwo", "requestCookieValueTwo") ) ) .respond( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withReasonPhrase(HttpStatusCode.ACCEPTED_202.reasonPhrase()) .withBody("some_body_response") ); // then // wrong query string cookie name assertEquals( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withReasonPhrase(HttpStatusCode.ACCEPTED_202.reasonPhrase()) .withBody("some_body_response"), makeRequest( request() .withMethod("GET") .withPath(calculatePath("some_pathRequest")) .withCookies( cookie("OTHERrequestCookieNameOne", "requestCookieValueOne"), cookie("requestCookieNameTwo", "requestCookieValueTwo") ), headersToIgnore) ); } @Test public void shouldReturnResponseByNotMatchingCookieWithNotOperatorForValue() { // when mockServerClient .when( request() .withMethod("GET") .withPath(calculatePath("some_pathRequest")) .withCookies( cookie(string("requestCookieNameOne"), not("requestCookieValueOne")), cookie("requestCookieNameTwo", "requestCookieValueTwo") ) ) .respond( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withReasonPhrase(HttpStatusCode.ACCEPTED_202.reasonPhrase()) .withBody("some_body_response") ); // then // wrong query string cookie value assertEquals( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withReasonPhrase(HttpStatusCode.ACCEPTED_202.reasonPhrase()) .withBody("some_body_response"), makeRequest( request() .withMethod("GET") .withPath(calculatePath("some_pathRequest")) .withCookies( cookie("requestCookieNameOne", "OTHERrequestCookieValueOne"), cookie("requestCookieNameTwo", "requestCookieValueTwo") ), headersToIgnore) ); } @Test public void shouldReturnResponseByNotMatchingHeaderWithNotOperatorForNameAndValue() { // when mockServerClient .when( request() .withMethod("GET") .withPath(calculatePath("some_pathRequest")) .withHeaders( header(not("requestHeaderNameOne"), not("requestHeaderValueOne")), header("requestHeaderNameTwo", "requestHeaderValueTwo") ) ) .respond( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withReasonPhrase(HttpStatusCode.ACCEPTED_202.reasonPhrase()) .withBody("some_body_response") ); // then // wrong query string header name assertEquals( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withReasonPhrase(HttpStatusCode.ACCEPTED_202.reasonPhrase()) .withBody("some_body_response"), makeRequest( request() .withMethod("GET") .withPath(calculatePath("some_pathRequest")) .withHeaders( header("OTHERrequestHeaderNameOne", "requestHeaderValueOne"), header("requestHeaderNameTwo", "requestHeaderValueTwo") ), headersToIgnore) ); // wrong query string header value assertEquals( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withReasonPhrase(HttpStatusCode.ACCEPTED_202.reasonPhrase()) .withBody("some_body_response"), makeRequest( request() .withMethod("GET") .withPath(calculatePath("some_pathRequest")) .withHeaders( header("requestHeaderNameOne", "OTHERrequestHeaderValueOne"), header("requestHeaderNameTwo", "requestHeaderValueTwo") ), headersToIgnore) ); } @Test public void shouldReturnResponseByNotMatchingHeaderWithNotOperatorForName() { // when mockServerClient .when( request() .withMethod("GET") .withPath(calculatePath("some_pathRequest")) .withHeaders( header(not("requestHeaderNameOne"), string("requestHeaderValueOne")), header("requestHeaderNameTwo", "requestHeaderValueTwo") ) ) .respond( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withReasonPhrase(HttpStatusCode.ACCEPTED_202.reasonPhrase()) .withBody("some_body_response") ); // then // wrong query string header name assertEquals( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withReasonPhrase(HttpStatusCode.ACCEPTED_202.reasonPhrase()) .withBody("some_body_response"), makeRequest( request() .withMethod("GET") .withPath(calculatePath("some_pathRequest")) .withHeaders( header("OTHERrequestHeaderNameOne", "requestHeaderValueOne"), header("requestHeaderNameTwo", "requestHeaderValueTwo") ), headersToIgnore) ); } @Test public void shouldReturnResponseByNotMatchingHeaderWithNotOperatorForValue() { // when mockServerClient .when( request() .withMethod("GET") .withPath(calculatePath("some_pathRequest")) .withHeaders( header(string("requestHeaderNameOne"), not("requestHeaderValueOne")), header("requestHeaderNameTwo", "requestHeaderValueTwo") ) ) .respond( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withReasonPhrase(HttpStatusCode.ACCEPTED_202.reasonPhrase()) .withBody("some_body_response") ); // then // wrong query string header value assertEquals( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withReasonPhrase(HttpStatusCode.ACCEPTED_202.reasonPhrase()) .withBody("some_body_response"), makeRequest( request() .withMethod("GET") .withPath(calculatePath("some_pathRequest")) .withHeaders( header("requestHeaderNameOne", "OTHERrequestHeaderValueOne"), header("requestHeaderNameTwo", "requestHeaderValueTwo") ), headersToIgnore) ); } @Test public void shouldNotReturnResponseForWhenTimeToLiveExpired() { // when mockServerClient .when( request().withPath(calculatePath("some_path")), exactly(2), TimeToLive.exactly(TimeUnit.SECONDS, 3L) ) .respond( response().withBody("some_body").withDelay(TimeUnit.SECONDS, 3L) ); // then assertEquals( response() .withStatusCode(OK_200.code()) .withReasonPhrase(OK_200.reasonPhrase()) .withBody("some_body"), makeRequest( request() .withPath(calculatePath("some_path")), headersToIgnore) ); // - in http assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()) .withReasonPhrase(HttpStatusCode.NOT_FOUND_404.reasonPhrase()), makeRequest( request() .withPath(calculatePath("some_path")), headersToIgnore) ); // - in https assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()) .withReasonPhrase(HttpStatusCode.NOT_FOUND_404.reasonPhrase()), makeRequest( request() .withSecure(true) .withPath(calculatePath("some_path")), headersToIgnore) ); } @Test public void shouldNotReturnResponseForMatchingBodyWithNotOperator() { // when mockServerClient .when( request() .withBody(Not.not(json("{" + NEW_LINE + " \"id\": 1," + NEW_LINE + " \"name\": \"A green door\"," + NEW_LINE + " \"price\": 12.50," + NEW_LINE + " \"tags\": [\"home\", \"green\"]" + NEW_LINE + "}"))), exactly(2) ) .respond( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withReasonPhrase(HttpStatusCode.ACCEPTED_202.reasonPhrase()) .withBody("some_body") ); // then // - in http assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()) .withReasonPhrase(HttpStatusCode.NOT_FOUND_404.reasonPhrase()), makeRequest( request() .withPath(calculatePath("some_path")) .withMethod("POST") .withBody("{" + NEW_LINE + " \"id\": 1," + NEW_LINE + " \"extra_ignored_field\": \"some value\"," + NEW_LINE + " \"name\": \"A green door\"," + NEW_LINE + " \"price\": 12.50," + NEW_LINE + " \"tags\": [\"home\", \"green\"]" + NEW_LINE + "}"), headersToIgnore) ); // - in https assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()) .withReasonPhrase(HttpStatusCode.NOT_FOUND_404.reasonPhrase()), makeRequest( request() .withSecure(true) .withPath(calculatePath("some_path")) .withMethod("POST") .withBody("{" + NEW_LINE + " \"id\": 1," + NEW_LINE + " \"extra_ignored_array\": [\"one\", \"two\"]," + NEW_LINE + " \"name\": \"A green door\"," + NEW_LINE + " \"price\": 12.50," + NEW_LINE + " \"tags\": [\"home\", \"green\"]" + NEW_LINE + "}"), headersToIgnore) ); } @Test public void shouldNotReturnResponseForNonMatchingXPathBody() { // when mockServerClient.when(request().withBody(new XPathBody("/bookstore/book[price>35]/price")), exactly(2)).respond(response().withBody("some_body")); // then // - in http assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()) .withReasonPhrase(HttpStatusCode.NOT_FOUND_404.reasonPhrase()), makeRequest( request() .withSecure(true) .withPath(calculatePath("some_path")) .withMethod("POST") .withBody(new StringBody("" + "<?xml version=\"1.0\" encoding=\"ISO-8859-1\"?>" + NEW_LINE + "<bookstore>" + NEW_LINE + " <book category=\"COOKING\">" + NEW_LINE + " <title lang=\"en\">Everyday Italian</title>" + NEW_LINE + " <author>Giada De Laurentiis</author>" + NEW_LINE + " <year>2005</year>" + NEW_LINE + " <price>30.00</price>" + NEW_LINE + " </book>" + NEW_LINE + " <book category=\"CHILDREN\">" + NEW_LINE + " <title lang=\"en\">Harry Potter</title>" + NEW_LINE + " <author>J K. Rowling</author>" + NEW_LINE + " <year>2005</year>" + NEW_LINE + " <price>29.99</price>" + NEW_LINE + " </book>" + NEW_LINE + " <book category=\"WEB\">" + NEW_LINE + " <title lang=\"en\">Learning XML</title>" + NEW_LINE + " <author>Erik T. Ray</author>" + NEW_LINE + " <year>2003</year>" + NEW_LINE + " <price>31.95</price>" + NEW_LINE + " </book>" + NEW_LINE + "</bookstore>")), headersToIgnore) ); // - in https assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()) .withReasonPhrase(HttpStatusCode.NOT_FOUND_404.reasonPhrase()), makeRequest( request() .withSecure(true) .withPath(calculatePath("some_path")) .withMethod("POST") .withBody(new StringBody("" + "<?xml version=\"1.0\" encoding=\"ISO-8859-1\"?>" + NEW_LINE + "<bookstore>" + NEW_LINE + " <book category=\"COOKING\">" + NEW_LINE + " <title lang=\"en\">Everyday Italian</title>" + NEW_LINE + " <author>Giada De Laurentiis</author>" + NEW_LINE + " <year>2005</year>" + NEW_LINE + " <price>30.00</price>" + NEW_LINE + " </book>" + NEW_LINE + " <book category=\"CHILDREN\">" + NEW_LINE + " <title lang=\"en\">Harry Potter</title>" + NEW_LINE + " <author>J K. Rowling</author>" + NEW_LINE + " <year>2005</year>" + NEW_LINE + " <price>29.99</price>" + NEW_LINE + " </book>" + NEW_LINE + " <book category=\"WEB\">" + NEW_LINE + " <title lang=\"en\">Learning XML</title>" + NEW_LINE + " <author>Erik T. Ray</author>" + NEW_LINE + " <year>2003</year>" + NEW_LINE + " <price>31.95</price>" + NEW_LINE + " </book>" + NEW_LINE + "</bookstore>")), headersToIgnore) ); } @Test public void shouldNotReturnResponseForNonMatchingXmlBody() { // when mockServerClient.when(request().withBody(xml("" + "<?xml version=\"1.0\" encoding=\"ISO-8859-1\"?>" + NEW_LINE + "<bookstore>" + NEW_LINE + " <book category=\"COOKING\" nationality=\"ITALIAN\">" + NEW_LINE + " <title lang=\"en\">Everyday Italian</title>" + NEW_LINE + " <author>Giada De Laurentiis</author>" + NEW_LINE + " <year>2005</year>" + NEW_LINE + " <price>30.00</price>" + NEW_LINE + " </book>" + NEW_LINE + "</bookstore>")), exactly(2)).respond(response().withBody("some_body")); // then // - in http assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()) .withReasonPhrase(HttpStatusCode.NOT_FOUND_404.reasonPhrase()), makeRequest( request() .withSecure(true) .withPath(calculatePath("some_path")) .withMethod("POST") .withBody(new StringBody("" + "<?xml version=\"1.0\" encoding=\"ISO-8859-1\"?>" + NEW_LINE + "<bookstore>" + NEW_LINE + " <book category=\"COOKING\">" + NEW_LINE + " <title lang=\"en\">Everyday Italian</title>" + NEW_LINE + " <author>Giada De Laurentiis</author>" + NEW_LINE + " <year>2005</year>" + NEW_LINE + " <price>30.00</price>" + NEW_LINE + " </book>" + NEW_LINE + "</bookstore>")), headersToIgnore) ); // - in https assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()) .withReasonPhrase(HttpStatusCode.NOT_FOUND_404.reasonPhrase()), makeRequest( request() .withSecure(true) .withPath(calculatePath("some_path")) .withMethod("POST") .withBody(new StringBody("" + "<?xml version=\"1.0\" encoding=\"ISO-8859-1\"?>" + NEW_LINE + "<bookstore>" + NEW_LINE + " <book category=\"COOKING\">" + NEW_LINE + " <title lang=\"en\">Everyday Italian</title>" + NEW_LINE + " <author>Giada De Laurentiis</author>" + NEW_LINE + " <year>2005</year>" + NEW_LINE + " <price>30.00</price>" + NEW_LINE + " </book>" + NEW_LINE + "</bookstore>")), headersToIgnore) ); } @Test public void shouldNotReturnResponseForNonMatchingJsonBody() { // when mockServerClient.when(request().withBody(json("{" + NEW_LINE + " \"id\": 1," + NEW_LINE + " \"name\": \"A green door\"," + NEW_LINE + " \"price\": 12.50," + NEW_LINE + " \"tags\": [\"home\", \"green\"]" + NEW_LINE + "}")), exactly(2)).respond(response().withBody("some_body")); // then // - in http assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()) .withReasonPhrase(HttpStatusCode.NOT_FOUND_404.reasonPhrase()), makeRequest( request() .withPath(calculatePath("some_path")) .withMethod("POST") .withBody("{" + NEW_LINE + " \"id\": 1," + NEW_LINE + " \"name\": \"---- XXXX WRONG VALUE XXXX ----\"," + NEW_LINE + " \"price\": 12.50," + NEW_LINE + " \"tags\": [\"home\", \"green\"]" + NEW_LINE + "}"), headersToIgnore) ); // - in https assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()) .withReasonPhrase(HttpStatusCode.NOT_FOUND_404.reasonPhrase()), makeRequest( request() .withSecure(true) .withPath(calculatePath("some_path")) .withMethod("POST") .withBody("{" + NEW_LINE + " \"id\": 1," + NEW_LINE + " \"name\": \"---- XXXX WRONG VALUE XXXX ----\"," + NEW_LINE + " \"price\": 12.50," + NEW_LINE + " \"tags\": [\"home\", \"green\"]" + NEW_LINE + "}"), headersToIgnore) ); } @Test public void shouldNotReturnResponseForNonMatchingJsonBodyWithMatchType() { // when mockServerClient .when( request() .withBody(json("{" + NEW_LINE + " \"id\": 1," + NEW_LINE + " \"name\": \"A green door\"," + NEW_LINE + " \"price\": 12.50," + NEW_LINE + " \"tags\": [\"home\", \"green\"]" + NEW_LINE + "}", MatchType.STRICT)), exactly(2)) .respond( response() .withBody("some_body") ); // then // - in http assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()) .withReasonPhrase(HttpStatusCode.NOT_FOUND_404.reasonPhrase()), makeRequest( request() .withPath(calculatePath("some_path")) .withMethod("POST") .withBody("{" + NEW_LINE + " \"id\": 1," + NEW_LINE + " \"extra field\": \"some value\"," + NEW_LINE + " \"name\": \"A green door\"," + NEW_LINE + " \"price\": 12.50," + NEW_LINE + " \"tags\": [\"home\", \"green\"]" + NEW_LINE + "}"), headersToIgnore) ); // - in https assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()) .withReasonPhrase(HttpStatusCode.NOT_FOUND_404.reasonPhrase()), makeRequest( request() .withSecure(true) .withPath(calculatePath("some_path")) .withMethod("POST") .withBody("{" + NEW_LINE + " \"id\": 1," + NEW_LINE + " \"extra field\": \"some value\"," + NEW_LINE + " \"name\": \"A green door\"," + NEW_LINE + " \"price\": 12.50," + NEW_LINE + " \"tags\": [\"home\", \"green\"]" + NEW_LINE + "}"), headersToIgnore) ); } @Test public void shouldNotReturnResponseForNonMatchingJsonSchema() { // when mockServerClient.when(request().withBody(jsonSchema("{" + NEW_LINE + " \"$schema\": \"http://json-schema.org/draft-04/schema#\"," + NEW_LINE + " \"title\": \"Product\"," + NEW_LINE + " \"description\": \"A product from Acme's catalog\"," + NEW_LINE + " \"type\": \"object\"," + NEW_LINE + " \"properties\": {" + NEW_LINE + " \"id\": {" + NEW_LINE + " \"description\": \"The unique identifier for a product\"," + NEW_LINE + " \"type\": \"integer\"" + NEW_LINE + " }," + NEW_LINE + " \"name\": {" + NEW_LINE + " \"description\": \"Name of the product\"," + NEW_LINE + " \"type\": \"string\"" + NEW_LINE + " }," + NEW_LINE + " \"price\": {" + NEW_LINE + " \"type\": \"number\"," + NEW_LINE + " \"minimum\": 0," + NEW_LINE + " \"exclusiveMinimum\": true" + NEW_LINE + " }," + NEW_LINE + " \"tags\": {" + NEW_LINE + " \"type\": \"array\"," + NEW_LINE + " \"items\": {" + NEW_LINE + " \"type\": \"string\"" + NEW_LINE + " }," + NEW_LINE + " \"minItems\": 1," + NEW_LINE + " \"uniqueItems\": true" + NEW_LINE + " }" + NEW_LINE + " }," + NEW_LINE + " \"required\": [\"id\", \"name\", \"price\"]" + NEW_LINE + "}")), exactly(2)).respond(response().withBody("some_body")); // then // - in http assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()) .withReasonPhrase(HttpStatusCode.NOT_FOUND_404.reasonPhrase()), makeRequest( request() .withPath(calculatePath("some_path")) .withMethod("POST") .withBody("{" + NEW_LINE + " \"id\": 1," + NEW_LINE + " \"wrong field name\": \"A green door\"," + NEW_LINE + " \"price\": 12.50," + NEW_LINE + " \"tags\": [\"home\", \"green\"]" + NEW_LINE + "}"), headersToIgnore) ); // - in https assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()) .withReasonPhrase(HttpStatusCode.NOT_FOUND_404.reasonPhrase()), makeRequest( request() .withSecure(true) .withPath(calculatePath("some_path")) .withMethod("POST") .withBody("{" + NEW_LINE + " \"id\": 1," + NEW_LINE + " \"name\": \"A green door\"," + NEW_LINE + " \"wrong field name\": 12.50," + NEW_LINE + " \"tags\": [\"home\", \"green\"]" + NEW_LINE + "}"), headersToIgnore) ); } @Test public void shouldNotReturnResponseForMatchingPathWithNotOperator() { // when mockServerClient .when( request() .withPath(not(calculatePath("some_path"))) ) .respond( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withReasonPhrase(HttpStatusCode.ACCEPTED_202.reasonPhrase()) .withBody("some_body_response") ); // then // - in http assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()) .withReasonPhrase(HttpStatusCode.NOT_FOUND_404.reasonPhrase()), makeRequest( request() .withPath(calculatePath("some_path")), headersToIgnore) ); // - in https assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()) .withReasonPhrase(HttpStatusCode.NOT_FOUND_404.reasonPhrase()), makeRequest( request() .withPath(calculatePath("some_path")), headersToIgnore) ); } @Test public void shouldNotReturnResponseForMatchingMethodWithNotOperator() { // when mockServerClient .when( request() .withMethod(not("GET")) ) .respond( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withReasonPhrase(HttpStatusCode.ACCEPTED_202.reasonPhrase()) .withBody("some_body_response") ); // then // - in http assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()) .withReasonPhrase(HttpStatusCode.NOT_FOUND_404.reasonPhrase()), makeRequest( request() .withMethod("GET"), headersToIgnore) ); // - in https assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()) .withReasonPhrase(HttpStatusCode.NOT_FOUND_404.reasonPhrase()), makeRequest( request() .withMethod("GET"), headersToIgnore) ); } @Test public void shouldNotReturnResponseForNonMatchingBodyParameterName() { // when mockServerClient .when( request() .withMethod("POST") .withPath(calculatePath("some_pathRequest")) .withBody(params( param("bodyParameterOneName", "Parameter One Value One", "Parameter One Value Two"), param("bodyParameterTwoName", "Parameter Two") )) ) .respond( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withReasonPhrase(HttpStatusCode.ACCEPTED_202.reasonPhrase()) .withBody("some_body_response") .withHeaders(header("headerNameResponse", "headerValueResponse")) .withCookies(cookie("cookieNameResponse", "cookieValueResponse")) ); // then // wrong query string parameter name assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()) .withReasonPhrase(HttpStatusCode.NOT_FOUND_404.reasonPhrase()), makeRequest( request() .withMethod("POST") .withPath(calculatePath("some_pathRequest")) .withBody(params( param("OTHERBodyParameterOneName", "Parameter One Value One", "Parameter One Value Two"), param("bodyParameterTwoName", "Parameter Two") )) .withHeaders(header("headerNameRequest", "headerValueRequest")) .withCookies(cookie("cookieNameRequest", "cookieValueRequest")), headersToIgnore) ); // wrong query string parameter name assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()) .withReasonPhrase(HttpStatusCode.NOT_FOUND_404.reasonPhrase()), makeRequest( request() .withMethod("POST") .withPath(calculatePath("some_pathRequest")) .withBody(new StringBody("OTHERBodyParameterOneName=Parameter+One+Value+One" + "&bodyParameterOneName=Parameter+One+Value+Two" + "&bodyParameterTwoName=Parameter+Two")) .withHeaders(header("headerNameRequest", "headerValueRequest")) .withCookies(cookie("cookieNameRequest", "cookieValueRequest")), headersToIgnore) ); } @Test public void shouldNotReturnResponseForMatchingBodyParameterWithNotOperator() { // when mockServerClient .when( request() .withMethod("POST") .withPath(calculatePath("some_pathRequest")) .withBody(params( param(not("bodyParameterOneName"), not("Parameter One Value One"), not("Parameter One Value Two")), param("bodyParameterTwoName", "Parameter Two") )) ) .respond( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withReasonPhrase(HttpStatusCode.ACCEPTED_202.reasonPhrase()) .withBody("some_body_response") ); // then // wrong query string parameter name assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()) .withReasonPhrase(HttpStatusCode.NOT_FOUND_404.reasonPhrase()), makeRequest( request() .withMethod("POST") .withPath(calculatePath("some_pathRequest")) .withBody(params( param("bodyParameterOneName", "Parameter One Value One", "Parameter One Value Two"), param("bodyParameterTwoName", "Parameter Two") )) .withHeaders(header("headerNameRequest", "headerValueRequest")) .withCookies(cookie("cookieNameRequest", "cookieValueRequest")), headersToIgnore) ); // wrong query string parameter name assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()) .withReasonPhrase(HttpStatusCode.NOT_FOUND_404.reasonPhrase()), makeRequest( request() .withMethod("POST") .withPath(calculatePath("some_pathRequest")) .withBody(new StringBody("bodyParameterOneName=Other Parameter+One+Value+One" + "&bodyParameterOneName=Parameter+One+Value+Two" + "&bodyParameterTwoName=Parameter+Two")) .withHeaders(header("headerNameRequest", "headerValueRequest")) .withCookies(cookie("cookieNameRequest", "cookieValueRequest")), headersToIgnore) ); } @Test public void shouldNotReturnResponseForNonMatchingBodyParameterValue() { // when mockServerClient .when( request() .withMethod("POST") .withPath(calculatePath("some_pathRequest")) .withBody(params( param("bodyParameterOneName", "Parameter One Value One", "Parameter One Value Two"), param("bodyParameterTwoName", "Parameter Two") )) ) .respond( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withReasonPhrase(HttpStatusCode.ACCEPTED_202.reasonPhrase()) .withBody("some_body_response") .withHeaders(header("headerNameResponse", "headerValueResponse")) .withCookies(cookie("cookieNameResponse", "cookieValueResponse")) ); // then // wrong body parameter value assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()) .withReasonPhrase(HttpStatusCode.NOT_FOUND_404.reasonPhrase()), makeRequest( request() .withMethod("POST") .withPath(calculatePath("some_pathRequest")) .withBody(params( param("bodyParameterOneName", "Other Parameter One Value One", "Parameter One Value Two"), param("bodyParameterTwoName", "Parameter Two") )) .withHeaders(header("headerNameRequest", "headerValueRequest")) .withCookies(cookie("cookieNameRequest", "cookieValueRequest")), headersToIgnore) ); // wrong body parameter value assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()) .withReasonPhrase(HttpStatusCode.NOT_FOUND_404.reasonPhrase()), makeRequest( request() .withMethod("POST") .withPath(calculatePath("some_pathRequest")) .withBody(new StringBody("bodyParameterOneName=Other Parameter+One+Value+One" + "&bodyParameterOneName=Parameter+One+Value+Two" + "&bodyParameterTwoName=Parameter+Two")) .withHeaders(header("headerNameRequest", "headerValueRequest")) .withCookies(cookie("cookieNameRequest", "cookieValueRequest")), headersToIgnore) ); } @Test public void shouldNotReturnResponseForNonMatchingQueryStringParameterName() { // when mockServerClient .when( request() .withMethod("POST") .withPath(calculatePath("some_pathRequest")) .withQueryStringParameters( param("queryStringParameterOneName", "queryStringParameterOneValueOne", "queryStringParameterOneValueTwo"), param("queryStringParameterTwoName", "queryStringParameterTwoValue") ) .withBody("some_bodyRequest") ) .respond( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withReasonPhrase(HttpStatusCode.ACCEPTED_202.reasonPhrase()) .withBody("some_body_response") .withHeaders(header("headerNameResponse", "headerValueResponse")) .withCookies(cookie("cookieNameResponse", "cookieValueResponse")) ); // then // wrong query string parameter name assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()) .withReasonPhrase(HttpStatusCode.NOT_FOUND_404.reasonPhrase()), makeRequest( request() .withMethod("POST") .withPath(calculatePath("some_pathRequest")) .withQueryStringParameters( param("OTHERQueryStringParameterOneName", "queryStringParameterOneValueOne", "queryStringParameterOneValueTwo"), param("queryStringParameterTwoName", "queryStringParameterTwoValue") ) .withBody("some_bodyRequest") .withHeaders( header("headerNameRequest", "headerValueRequest") ) .withCookies(cookie("cookieNameRequest", "cookieValueRequest")), headersToIgnore) ); } @Test public void shouldNotReturnResponseForNonMatchingQueryStringParameterValue() { // when mockServerClient .when( request() .withMethod("POST") .withPath(calculatePath("some_pathRequest")) .withQueryStringParameters( param("queryStringParameterOneName", "queryStringParameterOneValueOne", "queryStringParameterOneValueTwo"), param("queryStringParameterTwoName", "queryStringParameterTwoValue") ) .withBody("some_bodyRequest") ) .respond( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withReasonPhrase(HttpStatusCode.ACCEPTED_202.reasonPhrase()) .withBody("some_body_response") .withHeaders(header("headerNameResponse", "headerValueResponse")) .withCookies(cookie("cookieNameResponse", "cookieValueResponse")) ); // then // wrong query string parameter value assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()) .withReasonPhrase(HttpStatusCode.NOT_FOUND_404.reasonPhrase()), makeRequest( request() .withMethod("POST") .withPath(calculatePath("some_pathRequest")) .withQueryStringParameters( param("queryStringParameterOneName", "OTHERqueryStringParameterOneValueOne", "queryStringParameterOneValueTwo"), param("queryStringParameterTwoName", "queryStringParameterTwoValue") ) .withBody("some_bodyRequest") .withHeaders(header("headerNameRequest", "headerValueRequest")) .withCookies(cookie("cookieNameRequest", "cookieValueRequest")), headersToIgnore) ); } @Test public void shouldNotReturnResponseForMatchingQueryStringParameterWithNotOperator() { // when mockServerClient .when( request() .withMethod("POST") .withPath(calculatePath("some_pathRequest")) .withQueryStringParameters( param(not("queryStringParameterOneName"), not("Parameter One Value One"), not("Parameter One Value Two")), param("queryStringParameterTwoName", "Parameter Two") ) ) .respond( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withReasonPhrase(HttpStatusCode.ACCEPTED_202.reasonPhrase()) .withBody("some_body_response") ); // then // wrong query string parameter name assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()) .withReasonPhrase(HttpStatusCode.NOT_FOUND_404.reasonPhrase()), makeRequest( request() .withMethod("POST") .withPath(calculatePath("some_pathRequest")) .withQueryStringParameters( param("queryStringParameterOneName", "Parameter One Value One", "Parameter One Value Two"), param("queryStringParameterTwoName", "Parameter Two") ), headersToIgnore) ); // wrong query string parameter name assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()) .withReasonPhrase(HttpStatusCode.NOT_FOUND_404.reasonPhrase()), makeRequest( request() .withMethod("POST") .withPath(calculatePath("some_pathRequest")) .withQueryStringParameters( param("queryStringParameterOneName", "Parameter One Value One", "Parameter One Value Two"), param("queryStringParameterTwoName", "Parameter Two") ), headersToIgnore) ); } @Test public void shouldNotReturnResponseForNonMatchingCookieName() { // when mockServerClient .when( request() .withMethod("GET") .withPath(calculatePath("some_path")) .withQueryStringParameters( param("queryStringParameterOneName", "queryStringParameterOneValue"), param("queryStringParameterTwoName", "queryStringParameterTwoValue") ) .withBody(exact("some_body")) .withHeaders(header("headerName", "headerValue")) .withCookies(cookie("cookieName", "cookieValue")) ) .respond( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withReasonPhrase(HttpStatusCode.ACCEPTED_202.reasonPhrase()) .withBody("some_body") .withHeaders(header("headerName", "headerValue")) .withCookies(cookie("cookieName", "cookieValue")) ); // then // - in http assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()) .withReasonPhrase(HttpStatusCode.NOT_FOUND_404.reasonPhrase()), makeRequest( request() .withMethod("GET") .withPath(calculatePath("some_path")) .withQueryStringParameters( param("queryStringParameterOneName", "queryStringParameterOneValue"), param("queryStringParameterTwoName", "queryStringParameterTwoValue") ) .withBody(exact("some_body")) .withHeaders(header("headerName", "headerValue")) .withCookies(cookie("cookieOtherName", "cookieValue")), headersToIgnore) ); // - in https assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()) .withReasonPhrase(HttpStatusCode.NOT_FOUND_404.reasonPhrase()), makeRequest( request() .withMethod("GET") .withSecure(true) .withPath(calculatePath("some_path")) .withQueryStringParameters( param("queryStringParameterOneName", "queryStringParameterOneValue"), param("queryStringParameterTwoName", "queryStringParameterTwoValue") ) .withBody(exact("some_body")) .withHeaders(header("headerName", "headerValue")) .withCookies(cookie("cookieOtherName", "cookieValue")), headersToIgnore) ); } @Test public void shouldNotReturnResponseForNonMatchingCookieValue() { // when mockServerClient .when( request() .withMethod("GET") .withPath(calculatePath("some_path")) .withQueryStringParameters( param("queryStringParameterOneName", "queryStringParameterOneValue"), param("queryStringParameterTwoName", "queryStringParameterTwoValue") ) .withBody(exact("some_body")) .withHeaders(header("headerName", "headerValue")) .withCookies(cookie("cookieName", "cookieValue")) ) .respond( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withReasonPhrase(HttpStatusCode.ACCEPTED_202.reasonPhrase()) .withBody("some_body") .withHeaders(header("headerName", "headerValue")) .withCookies(cookie("cookieName", "cookieValue")) ); // then // - in http assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()) .withReasonPhrase(HttpStatusCode.NOT_FOUND_404.reasonPhrase()), makeRequest( request() .withMethod("GET") .withPath(calculatePath("some_path")) .withQueryStringParameters( param("queryStringParameterOneName", "queryStringParameterOneValue"), param("queryStringParameterTwoName", "queryStringParameterTwoValue") ) .withBody(exact("some_body")) .withHeaders(header("headerName", "headerValue")) .withCookies(cookie("cookieName", "cookieOtherValue")), headersToIgnore) ); // - in https assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()) .withReasonPhrase(HttpStatusCode.NOT_FOUND_404.reasonPhrase()), makeRequest( request() .withMethod("GET") .withSecure(true) .withPath(calculatePath("some_path")) .withQueryStringParameters( param("queryStringParameterOneName", "queryStringParameterOneValue"), param("queryStringParameterTwoName", "queryStringParameterTwoValue") ) .withBody(exact("some_body")) .withHeaders(header("headerName", "headerValue")) .withCookies(cookie("cookieName", "cookieOtherValue")), headersToIgnore) ); } @Test public void shouldNotReturnResponseForMatchingCookieWithNotOperator() { // when mockServerClient .when( request() .withMethod("GET") .withPath(calculatePath("some_pathRequest")) .withCookies( cookie(not("requestCookieNameOne"), not("requestCookieValueOne")), cookie("requestCookieNameTwo", "requestCookieValueTwo") ) ) .respond( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withReasonPhrase(HttpStatusCode.ACCEPTED_202.reasonPhrase()) .withBody("some_body_response") ); // then // wrong query string parameter name assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()) .withReasonPhrase(HttpStatusCode.NOT_FOUND_404.reasonPhrase()), makeRequest( request() .withMethod("GET") .withPath(calculatePath("some_pathRequest")) .withCookies( cookie("requestCookieNameOne", "requestCookieValueOne"), cookie("requestCookieNameTwo", "requestCookieValueTwo") ), headersToIgnore) ); // wrong query string parameter name assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()) .withReasonPhrase(HttpStatusCode.NOT_FOUND_404.reasonPhrase()), makeRequest( request() .withMethod("GET") .withPath(calculatePath("some_pathRequest")) .withCookies( cookie("requestCookieNameOne", "requestCookieValueOne"), cookie("requestCookieNameTwo", "requestCookieValueTwo") ), headersToIgnore) ); } @Test public void shouldNotReturnResponseForNonMatchingHeaderName() { // when mockServerClient .when( request() .withMethod("GET") .withPath(calculatePath("some_path")) .withQueryStringParameters( param("queryStringParameterOneName", "queryStringParameterOneValue"), param("queryStringParameterTwoName", "queryStringParameterTwoValue") ) .withBody(exact("some_body")) .withHeaders(header("headerName", "headerValue")) .withCookies(cookie("cookieName", "cookieValue")) ) .respond( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withReasonPhrase(HttpStatusCode.ACCEPTED_202.reasonPhrase()) .withBody("some_body") .withHeaders(header("headerName", "headerValue")) .withCookies(cookie("cookieName", "cookieValue")) ); // then // - in http assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()) .withReasonPhrase(HttpStatusCode.NOT_FOUND_404.reasonPhrase()), makeRequest( request() .withMethod("GET") .withPath(calculatePath("some_path")) .withQueryStringParameters( param("queryStringParameterOneName", "queryStringParameterOneValue"), param("queryStringParameterTwoName", "queryStringParameterTwoValue") ) .withBody(exact("some_body")) .withHeaders(header("headerOtherName", "headerValue")) .withCookies(cookie("cookieName", "cookieValue")), headersToIgnore) ); // - in https assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()) .withReasonPhrase(HttpStatusCode.NOT_FOUND_404.reasonPhrase()), makeRequest( request() .withMethod("GET") .withSecure(true) .withPath(calculatePath("some_path")) .withQueryStringParameters( param("queryStringParameterOneName", "queryStringParameterOneValue"), param("queryStringParameterTwoName", "queryStringParameterTwoValue") ) .withBody(exact("some_body")) .withHeaders(header("headerOtherName", "headerValue")) .withCookies(cookie("cookieName", "cookieValue")), headersToIgnore) ); } @Test public void shouldNotReturnResponseForNonMatchingHeaderValue() { // when mockServerClient .when( request() .withMethod("GET") .withPath(calculatePath("some_path")) .withQueryStringParameters( param("queryStringParameterOneName", "queryStringParameterOneValue"), param("queryStringParameterTwoName", "queryStringParameterTwoValue") ) .withBody(exact("some_body")) .withHeaders(header("headerName", "headerValue")) .withCookies(cookie("cookieName", "cookieValue")) ) .respond( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withReasonPhrase(HttpStatusCode.ACCEPTED_202.reasonPhrase()) .withBody("some_body") .withHeaders(header("headerName", "headerValue")) .withCookies(cookie("cookieName", "cookieValue")) ); // then // - in http assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()) .withReasonPhrase(HttpStatusCode.NOT_FOUND_404.reasonPhrase()), makeRequest( request() .withMethod("GET") .withPath(calculatePath("some_path")) .withQueryStringParameters( param("queryStringParameterOneName", "queryStringParameterOneValue"), param("queryStringParameterTwoName", "queryStringParameterTwoValue") ) .withBody(exact("some_body")) .withHeaders(header("headerName", "headerOtherValue")) .withCookies(cookie("cookieName", "cookieValue")), headersToIgnore) ); // - in https assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()) .withReasonPhrase(HttpStatusCode.NOT_FOUND_404.reasonPhrase()), makeRequest( request() .withMethod("GET") .withSecure(true) .withPath(calculatePath("some_path")) .withQueryStringParameters( param("queryStringParameterOneName", "queryStringParameterOneValue"), param("queryStringParameterTwoName", "queryStringParameterTwoValue") ) .withBody(exact("some_body")) .withHeaders(header("headerName", "headerOtherValue")) .withCookies(cookie("cookieName", "cookieValue")), headersToIgnore) ); } @Test public void shouldNotReturnResponseForMatchingHeaderWithNotOperator() { // when mockServerClient .when( request() .withMethod("GET") .withPath(calculatePath("some_pathRequest")) .withHeaders( header(not("requestHeaderNameOne"), not("requestHeaderValueOne")), header("requestHeaderNameTwo", "requestHeaderValueTwo") ) ) .respond( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withReasonPhrase(HttpStatusCode.ACCEPTED_202.reasonPhrase()) .withBody("some_body_response") ); // then // wrong query string parameter name assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()) .withReasonPhrase(HttpStatusCode.NOT_FOUND_404.reasonPhrase()), makeRequest( request() .withMethod("GET") .withPath(calculatePath("some_pathRequest")) .withHeaders( header("requestHeaderNameOne", "requestHeaderValueOne"), header("requestHeaderNameTwo", "requestHeaderValueTwo") ), headersToIgnore) ); // wrong query string parameter name assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()) .withReasonPhrase(HttpStatusCode.NOT_FOUND_404.reasonPhrase()), makeRequest( request() .withMethod("GET") .withPath(calculatePath("some_pathRequest")) .withHeaders( header("requestHeaderNameOne", "requestHeaderValueOne"), header("requestHeaderNameTwo", "requestHeaderValueTwo") ), headersToIgnore) ); } @Test public void shouldVerifyReceivedRequestInSsl() { // when mockServerClient .when( request() .withPath(calculatePath("some.*path")), exactly(2) ) .respond( response() .withBody("some_body") ); // then // - in http assertEquals( response() .withStatusCode(OK_200.code()) .withReasonPhrase(OK_200.reasonPhrase()) .withBody("some_body"), makeRequest( request() .withPath(calculatePath("some_path")), headersToIgnore) ); mockServerClient.verify(request() .withPath(calculatePath("some_path")) .withSecure(false)); mockServerClient.verify(request() .withPath(calculatePath("some_path")) .withSecure(false), VerificationTimes.exactly(1)); // - in https assertEquals( response() .withStatusCode(OK_200.code()) .withReasonPhrase(OK_200.reasonPhrase()) .withBody("some_body"), makeRequest( request() .withPath(calculatePath("some_secure_path")) .withSecure(true), headersToIgnore) ); mockServerClient.verify(request() .withPath(calculatePath("some_secure_path")) .withSecure(true)); mockServerClient.verify(request() .withPath(calculatePath("some_secure_path")) .withSecure(true), VerificationTimes.exactly(1)); } @Test public void shouldVerifyReceivedRequestsWithRegexBody() { // when mockServerClient .when( request() .withMethod("POST") .withPath(calculatePath("some_path")) .withBody("{type: 'some_random_type', value: 'some_random_value'}"), exactly(2) ) .respond( response() .withBody("some_response") ); // then // - in http assertEquals( response() .withStatusCode(OK_200.code()) .withReasonPhrase(OK_200.reasonPhrase()) .withBody("some_response"), makeRequest( request() .withMethod("POST") .withPath(calculatePath("some_path")) .withBody("{type: 'some_random_type', value: 'some_random_value'}"), headersToIgnore) ); mockServerClient.verify( request() .withBody(regex("\\{type\\: \\'some_random_type\\'\\, value\\: \\'some_random_value\\'\\}")) ); mockServerClient.verify( request() .withBody(regex("\\{type\\: \\'some_random_type\\'\\, value\\: \\'some_random_value\\'\\}")), VerificationTimes.exactly(1) ); // - in https assertEquals( response() .withStatusCode(OK_200.code()) .withReasonPhrase(OK_200.reasonPhrase()) .withBody("some_response"), makeRequest( request() .withSecure(true) .withMethod("POST") .withPath(calculatePath("some_path")) .withBody("{type: 'some_random_type', value: 'some_random_value'}"), headersToIgnore) ); mockServerClient.verify( request() .withSecure(true) .withBody(regex("\\{type\\: \\'some_random_type\\'\\, value\\: \\'some_random_value\\'\\}")) ); mockServerClient.verify( request() .withSecure(true) .withBody(regex("\\{type\\: \\'some_random_type\\'\\, value\\: \\'some_random_value\\'\\}")), VerificationTimes.atLeast(1) ); } @Test public void shouldVerifyReceivedRequestsWithNoBody() { // when mockServerClient.when(request().withPath(calculatePath("some_path")), exactly(2)).respond(response()); // then // - in http assertEquals( response() .withStatusCode(OK_200.code()) .withReasonPhrase(OK_200.reasonPhrase()), makeRequest( request() .withPath(calculatePath("some_path")), headersToIgnore) ); mockServerClient.verify(request() .withPath(calculatePath("some_path"))); mockServerClient.verify(request() .withPath(calculatePath("some_path")), VerificationTimes.exactly(1)); } @Test public void shouldVerifyTooManyRequestsReceived() { // when mockServerClient.when(request().withPath(calculatePath("some_path")), exactly(2)).respond(response().withBody("some_body")); // then assertEquals( response() .withStatusCode(OK_200.code()) .withReasonPhrase(OK_200.reasonPhrase()) .withBody("some_body"), makeRequest( request() .withPath(calculatePath("some_path")), headersToIgnore) ); try { mockServerClient.verify(request() .withPath(calculatePath("some_path")), VerificationTimes.exactly(0)); fail(); } catch (AssertionError ae) { assertThat(ae.getMessage(), startsWith("Request not found exactly 0 times, expected:<{" + NEW_LINE + " \"path\" : \"" + calculatePath("some_path") + "\"" + NEW_LINE + "}> but was:<{" + NEW_LINE + " \"method\" : \"GET\"," + NEW_LINE + " \"path\" : \"" + calculatePath("some_path") + "\"," + NEW_LINE)); } } @Test public void shouldVerifyNoMatchingRequestsReceived() { // when mockServerClient.when(request().withPath(calculatePath("some_path")), exactly(2)).respond(response().withBody("some_body")); // then assertEquals( response() .withStatusCode(OK_200.code()) .withReasonPhrase(OK_200.reasonPhrase()) .withBody("some_body"), makeRequest( request() .withPath(calculatePath("some_path")), headersToIgnore) ); try { mockServerClient.verify(request() .withPath(calculatePath("some_other_path")), VerificationTimes.exactly(2)); fail(); } catch (AssertionError ae) { assertThat(ae.getMessage(), startsWith("Request not found exactly 2 times, expected:<{" + NEW_LINE + " \"path\" : \"" + calculatePath("some_other_path") + "\"" + NEW_LINE + "}> but was:<{" + NEW_LINE + " \"method\" : \"GET\"," + NEW_LINE + " \"path\" : \"" + calculatePath("some_path") + "\"," + NEW_LINE)); } } @Test public void shouldNotVerifyNoRequestsReceived() { // when mockServerClient.when(request().withPath(calculatePath("some_path")), exactly(2)).respond(response().withBody("some_body")); // then assertEquals( response() .withStatusCode(OK_200.code()) .withReasonPhrase(OK_200.reasonPhrase()) .withBody("some_body"), makeRequest( request() .withPath(calculatePath("some_path")), headersToIgnore) ); try { mockServerClient.verifyZeroInteractions(); fail(); } catch (AssertionError ae) { assertThat(ae.getMessage(), startsWith("Request not found exactly 0 times, expected:<{ }> but was:<{" + NEW_LINE + " \"method\" : \"GET\"," + NEW_LINE + " \"path\" : \"" + calculatePath("some_path") + "\"," + NEW_LINE)); } } @Test public void shouldVerifyNoMatchingRequestsReceivedInSsl() { // when mockServerClient.when(request().withPath(calculatePath("some.*path")), exactly(2)).respond(response().withBody("some_body")); // then // - in http assertEquals( response() .withStatusCode(OK_200.code()) .withReasonPhrase(OK_200.reasonPhrase()) .withBody("some_body"), makeRequest( request() .withPath(calculatePath("some_path")), headersToIgnore) ); try { mockServerClient.verify( request() .withPath(calculatePath("some_path")) .withSecure(true), VerificationTimes.atLeast(1) ); fail(); } catch (AssertionError ae) { assertThat(ae.getMessage(), startsWith("Request not found at least once, expected:<{" + NEW_LINE + " \"path\" : \"" + calculatePath("some_path") + "\"," + NEW_LINE + " \"secure\" : true" + NEW_LINE + "}> but was:<{" + NEW_LINE + " \"method\" : \"GET\"," + NEW_LINE + " \"path\" : \"" + calculatePath("some_path") + "\"," + NEW_LINE)); } // - in https assertEquals( response() .withStatusCode(OK_200.code()) .withReasonPhrase(OK_200.reasonPhrase()) .withBody("some_body"), makeRequest( request() .withPath(calculatePath("some_secure_path")) .withSecure(true), headersToIgnore) ); try { mockServerClient.verify( request() .withPath(calculatePath("some_secure_path")) .withSecure(false), VerificationTimes.atLeast(1) ); fail(); } catch (AssertionError ae) { assertThat(ae.getMessage(), startsWith("Request not found at least once, expected:<{" + NEW_LINE + " \"path\" : \"" + calculatePath("some_secure_path") + "\"," + NEW_LINE + " \"secure\" : false" + NEW_LINE + "}> but was:<[ {" + NEW_LINE + " \"method\" : \"GET\"," + NEW_LINE + " \"path\" : \"" + calculatePath("some_path") + "\"," + NEW_LINE)); } } @Test public void shouldVerifySequenceOfRequestsReceivedIncludingThoseNotMatchingAnException() { // when mockServerClient.when(request().withPath(calculatePath("some_path.*")), exactly(4)).respond(response().withBody("some_body")); // then assertEquals( response("some_body"), makeRequest( request().withPath(calculatePath("some_path_one")), headersToIgnore) ); assertEquals( notFoundResponse(), makeRequest( request().withPath(calculatePath("not_found")), headersToIgnore) ); assertEquals( response("some_body"), makeRequest( request().withPath(calculatePath("some_path_three")), headersToIgnore) ); mockServerClient.verify(request(calculatePath("some_path_one")), request(calculatePath("some_path_three"))); mockServerClient.verify(request(calculatePath("some_path_one")), request(calculatePath("not_found"))); mockServerClient.verify(request(calculatePath("some_path_one")), request(calculatePath("not_found")), request(calculatePath("some_path_three"))); mockServerClient.verify(request(calculatePath("some_path_one")), request(calculatePath("not_found")), request(calculatePath("some_path_three"))); } @Test public void shouldVerifySequenceOfRequestsNotReceived() { // when mockServerClient.when(request().withPath(calculatePath("some_path.*")), exactly(6)).respond(response().withBody("some_body")); // then assertEquals( response("some_body"), makeRequest( request().withPath(calculatePath("some_path_one")), headersToIgnore) ); assertEquals( response("some_body"), makeRequest( request().withPath(calculatePath("some_path_two")), headersToIgnore) ); assertEquals( response("some_body"), makeRequest( request().withPath(calculatePath("some_path_three")), headersToIgnore) ); try { mockServerClient.verify(request(calculatePath("some_path_two")), request(calculatePath("some_path_one"))); fail(); } catch (AssertionError ae) { assertThat(ae.getMessage(), startsWith("Request sequence not found, expected:<[ {" + NEW_LINE + " \"path\" : \"" + calculatePath("some_path_two") + "\"" + NEW_LINE + "}, {" + NEW_LINE + " \"path\" : \"" + calculatePath("some_path_one") + "\"" + NEW_LINE + "} ]> but was:<[ {" + NEW_LINE + " \"method\" : \"GET\"," + NEW_LINE + " \"path\" : \"" + calculatePath("some_path_one") + "\"," + NEW_LINE)); } try { mockServerClient.verify(request(calculatePath("some_path_three")), request(calculatePath("some_path_two"))); fail(); } catch (AssertionError ae) { assertThat(ae.getMessage(), startsWith("Request sequence not found, expected:<[ {" + NEW_LINE + " \"path\" : \"" + calculatePath("some_path_three") + "\"" + NEW_LINE + "}, {" + NEW_LINE + " \"path\" : \"" + calculatePath("some_path_two") + "\"" + NEW_LINE + "} ]> but was:<[ {" + NEW_LINE + " \"method\" : \"GET\"," + NEW_LINE + " \"path\" : \"" + calculatePath("some_path_one") + "\"," + NEW_LINE)); } try { mockServerClient.verify(request(calculatePath("some_path_four"))); fail(); } catch (AssertionError ae) { assertThat(ae.getMessage(), startsWith("Request sequence not found, expected:<[ {" + NEW_LINE + " \"path\" : \"" + calculatePath("some_path_four") + "\"" + NEW_LINE + "} ]> but was:<[ {" + NEW_LINE + " \"method\" : \"GET\"," + NEW_LINE + " \"path\" : \"" + calculatePath("some_path_one") + "\"," + NEW_LINE)); } } @Test public void shouldRetrieveRecordedRequestsAsJson() { // when mockServerClient.when(request().withPath(calculatePath("some_path.*")), exactly(4)).respond(response().withBody("some_body")); assertEquals( response("some_body"), makeRequest( request().withPath(calculatePath("some_path_one")), headersToIgnore) ); assertEquals( notFoundResponse(), makeRequest( request().withPath(calculatePath("not_found")), headersToIgnore) ); assertEquals( response("some_body"), makeRequest( request().withPath(calculatePath("some_path_three")), headersToIgnore) ); // then verifyRequestsMatches( new HttpRequestSerializer(new MockServerLogger()).deserializeArray(mockServerClient.retrieveRecordedRequests(request().withPath(calculatePath("some_path.*")), Format.JSON)), request(calculatePath("some_path_one")), request(calculatePath("some_path_three")) ); verifyRequestsMatches( new HttpRequestSerializer(new MockServerLogger()).deserializeArray(mockServerClient.retrieveRecordedRequests(request(), Format.JSON)), request(calculatePath("some_path_one")), request(calculatePath("not_found")), request(calculatePath("some_path_three")) ); verifyRequestsMatches( new HttpRequestSerializer(new MockServerLogger()).deserializeArray(mockServerClient.retrieveRecordedRequests(null, Format.JSON)), request(calculatePath("some_path_one")), request(calculatePath("not_found")), request(calculatePath("some_path_three")) ); } @Test public void shouldRetrieveActiveExpectationsAsJson() { // when mockServerClient.when(request().withPath(calculatePath("some_path.*")), exactly(4)) .respond(response().withBody("some_body")); mockServerClient.when(request().withPath(calculatePath("some_path.*"))) .respond(response().withBody("some_body")); mockServerClient.when(request().withPath(calculatePath("some_other_path"))) .respond(response().withBody("some_other_body")); mockServerClient.when(request().withPath(calculatePath("some_forward_path"))) .forward(forward()); // then assertThat( mockServerClient.retrieveActiveExpectations(request().withPath(calculatePath("some_path.*")), Format.JSON), is(new ExpectationSerializer(new MockServerLogger()).serialize(Arrays.asList( new Expectation(request().withPath(calculatePath("some_path.*")), exactly(4), TimeToLive.unlimited()) .thenRespond(response().withBody("some_body")), new Expectation(request().withPath(calculatePath("some_path.*"))) .thenRespond(response().withBody("some_body")) ))) ); assertThat( mockServerClient.retrieveActiveExpectations(null, Format.JSON), is(new ExpectationSerializer(new MockServerLogger()).serialize(Arrays.asList( new Expectation(request().withPath(calculatePath("some_path.*")), exactly(4), TimeToLive.unlimited()) .thenRespond(response().withBody("some_body")), new Expectation(request().withPath(calculatePath("some_path.*"))) .thenRespond(response().withBody("some_body")), new Expectation(request().withPath(calculatePath("some_other_path"))) .thenRespond(response().withBody("some_other_body")), new Expectation(request().withPath(calculatePath("some_forward_path"))) .thenForward(forward()) ))) ); assertThat( mockServerClient.retrieveActiveExpectations(request(), Format.JSON), is(new ExpectationSerializer(new MockServerLogger()).serialize(Arrays.asList( new Expectation(request().withPath(calculatePath("some_path.*")), exactly(4), TimeToLive.unlimited()) .thenRespond(response().withBody("some_body")), new Expectation(request().withPath(calculatePath("some_path.*"))) .thenRespond(response().withBody("some_body")), new Expectation(request().withPath(calculatePath("some_other_path"))) .thenRespond(response().withBody("some_other_body")), new Expectation(request().withPath(calculatePath("some_forward_path"))) .thenForward(forward()) ))) ); } @Test public void shouldRetrieveActiveExpectationsAsJava() { // when mockServerClient.when(request().withPath(calculatePath("some_path.*")), exactly(4)) .respond(response().withBody("some_body")); mockServerClient.when(request().withPath(calculatePath("some_path.*"))) .respond(response().withBody("some_body")); mockServerClient.when(request().withPath(calculatePath("some_other_path"))) .respond(response().withBody("some_other_body")); mockServerClient.when(request().withPath(calculatePath("some_forward_path"))) .forward(forward()); // then assertThat( mockServerClient.retrieveActiveExpectations(request().withPath(calculatePath("some_path.*")), Format.JAVA), is(new ExpectationToJavaSerializer().serialize(Arrays.asList( new Expectation(request().withPath(calculatePath("some_path.*")), exactly(4), TimeToLive.unlimited()) .thenRespond(response().withBody("some_body")), new Expectation(request().withPath(calculatePath("some_path.*"))) .thenRespond(response().withBody("some_body")) ))) ); assertThat( mockServerClient.retrieveActiveExpectations(null, Format.JAVA), is(new ExpectationToJavaSerializer().serialize(Arrays.asList( new Expectation(request().withPath(calculatePath("some_path.*")), exactly(4), TimeToLive.unlimited()) .thenRespond(response().withBody("some_body")), new Expectation(request().withPath(calculatePath("some_path.*"))) .thenRespond(response().withBody("some_body")), new Expectation(request().withPath(calculatePath("some_other_path"))) .thenRespond(response().withBody("some_other_body")), new Expectation(request().withPath(calculatePath("some_forward_path"))) .thenForward(forward()) ))) ); assertThat( mockServerClient.retrieveActiveExpectations(request(), Format.JAVA), is(new ExpectationToJavaSerializer().serialize(Arrays.asList( new Expectation(request().withPath(calculatePath("some_path.*")), exactly(4), TimeToLive.unlimited()) .thenRespond(response().withBody("some_body")), new Expectation(request().withPath(calculatePath("some_path.*"))) .thenRespond(response().withBody("some_body")), new Expectation(request().withPath(calculatePath("some_other_path"))) .thenRespond(response().withBody("some_other_body")), new Expectation(request().withPath(calculatePath("some_forward_path"))) .thenForward(forward()) ))) ); } @Test public void shouldRetrieveRecordedExpectationsAsJson() { // when EchoServer secureEchoServer = new EchoServer(false); try { mockServerClient.when(request().withPath(calculatePath("some_path.*")), exactly(4)).forward( forward() .withHost("127.0.0.1") .withPort(secureEchoServer.getPort()) ); assertEquals( response("some_body_one"), makeRequest( request().withPath(calculatePath("some_path_one")).withBody("some_body_one"), headersToIgnore ) ); assertEquals( response("some_body_three"), makeRequest( request().withPath(calculatePath("some_path_three")).withBody("some_body_three"), headersToIgnore ) ); // then Expectation[] recordedExpectations = new ExpectationSerializer(new MockServerLogger()).deserializeArray( mockServerClient.retrieveRecordedExpectations(request().withPath(calculatePath("some_path_one")), Format.JSON) ); assertThat(recordedExpectations.length, is(1)); verifyRequestsMatches( new HttpRequest[]{ recordedExpectations[0].getHttpRequest() }, request(calculatePath("some_path_one")).withBody("some_body_one") ); assertThat(recordedExpectations[0].getHttpResponse().getBodyAsString(), is("some_body_one")); // and recordedExpectations = new ExpectationSerializer(new MockServerLogger()).deserializeArray( mockServerClient.retrieveRecordedExpectations(request(), Format.JSON) ); assertThat(recordedExpectations.length, is(2)); verifyRequestsMatches( new HttpRequest[]{ recordedExpectations[0].getHttpRequest(), recordedExpectations[1].getHttpRequest() }, request(calculatePath("some_path_one")).withBody("some_body_one"), request(calculatePath("some_path_three")).withBody("some_body_three") ); assertThat(recordedExpectations[0].getHttpResponse().getBodyAsString(), is("some_body_one")); assertThat(recordedExpectations[1].getHttpResponse().getBodyAsString(), is("some_body_three")); // and recordedExpectations = new ExpectationSerializer(new MockServerLogger()).deserializeArray( mockServerClient.retrieveRecordedExpectations(null, Format.JSON) ); assertThat(recordedExpectations.length, is(2)); verifyRequestsMatches( new HttpRequest[]{ recordedExpectations[0].getHttpRequest(), recordedExpectations[1].getHttpRequest() }, request(calculatePath("some_path_one")).withBody("some_body_one"), request(calculatePath("some_path_three")).withBody("some_body_three") ); assertThat(recordedExpectations[0].getHttpResponse().getBodyAsString(), is("some_body_one")); assertThat(recordedExpectations[1].getHttpResponse().getBodyAsString(), is("some_body_three")); } finally { secureEchoServer.stop(); } } @Test public void shouldClearExpectationsOnly() { // given - some expectations mockServerClient .when( request() .withPath(calculatePath("some_path1")) ) .respond( response() .withBody("some_body1") ); mockServerClient .when( request() .withPath(calculatePath("some_path2")) ) .respond( response() .withBody("some_body2") ); // and - some matching requests assertEquals( response() .withStatusCode(OK_200.code()) .withReasonPhrase(OK_200.reasonPhrase()) .withBody("some_body1"), makeRequest( request() .withPath(calculatePath("some_path1")), headersToIgnore) ); assertEquals( response() .withStatusCode(OK_200.code()) .withReasonPhrase(OK_200.reasonPhrase()) .withBody("some_body2"), makeRequest( request() .withPath(calculatePath("some_path2")), headersToIgnore) ); // when mockServerClient .clear( request() .withPath(calculatePath("some_path1")), ClearType.EXPECTATIONS ); // then - expectations cleared assertThat( mockServerClient.retrieveActiveExpectations(null), arrayContaining( new Expectation(request() .withPath(calculatePath("some_path2"))) .thenRespond( response() .withBody("some_body2") ) ) ); // and then - request log not cleared verifyRequestsMatches( mockServerClient.retrieveRecordedRequests(null), request(calculatePath("some_path1")), request(calculatePath("some_path2")) ); } @Test public void shouldClearLogsOnly() { // given - some expectations mockServerClient .when( request() .withPath(calculatePath("some_path1")) ) .respond( response() .withBody("some_body1") ); mockServerClient .when( request() .withPath(calculatePath("some_path2")) ) .respond( response() .withBody("some_body2") ); // and - some matching requests assertEquals( response() .withStatusCode(OK_200.code()) .withReasonPhrase(OK_200.reasonPhrase()) .withBody("some_body1"), makeRequest( request() .withPath(calculatePath("some_path1")), headersToIgnore) ); assertEquals( response() .withStatusCode(OK_200.code()) .withReasonPhrase(OK_200.reasonPhrase()) .withBody("some_body2"), makeRequest( request() .withPath(calculatePath("some_path2")), headersToIgnore) ); // when mockServerClient .clear( request() .withPath(calculatePath("some_path1")), ClearType.LOG ); // then - expectations cleared assertThat( mockServerClient.retrieveActiveExpectations(null), arrayContaining( new Expectation(request() .withPath(calculatePath("some_path1"))) .thenRespond( response() .withBody("some_body1") ), new Expectation(request() .withPath(calculatePath("some_path2"))) .thenRespond( response() .withBody("some_body2") ) ) ); // and then - request log cleared verifyRequestsMatches( mockServerClient.retrieveRecordedRequests(null), request(calculatePath("some_path2")) ); } @Test public void shouldClearAllExpectationsWithNull() { // given mockServerClient .when( request() .withPath(calculatePath("some_path1")) ) .respond( response() .withBody("some_body1") ); mockServerClient .when( request() .withPath(calculatePath("some_path2")) ) .respond( response() .withBody("some_body2") ); assertEquals( response() .withStatusCode(OK_200.code()) .withReasonPhrase(OK_200.reasonPhrase()) .withBody("some_body2"), makeRequest( request() .withPath(calculatePath("some_path2")), headersToIgnore) ); // when mockServerClient.clear(null); // then assertThat(mockServerClient.retrieveActiveExpectations(null), emptyArray()); assertThat(mockServerClient.retrieveRecordedRequests(null), emptyArray()); } @Test public void shouldClearAllExpectationsWithEmptyRequest() { // given mockServerClient .when( request() .withPath(calculatePath("some_path1")) ) .respond( response() .withBody("some_body1") ); mockServerClient .when( request() .withPath(calculatePath("some_path2")) ) .respond( response() .withBody("some_body2") ); assertEquals( response() .withStatusCode(OK_200.code()) .withReasonPhrase(OK_200.reasonPhrase()) .withBody("some_body2"), makeRequest( request() .withPath(calculatePath("some_path2")), headersToIgnore) ); // when mockServerClient.clear(request()); // then assertThat(mockServerClient.retrieveActiveExpectations(null), emptyArray()); assertThat(mockServerClient.retrieveRecordedRequests(null), emptyArray()); } @Test public void shouldClearExpectationsWithXPathBody() { // given mockServerClient .when( request() .withBody(xpath("/bookstore/book[year=2005]/price")) ) .respond( response() .withBody("some_body1") ); mockServerClient .when( request() .withBody(xpath("/bookstore/book[year=2006]/price")) ) .respond( response() .withBody("some_body2") ); // and StringBody xmlBody = new StringBody("" + "<?xml version=\"1.0\" encoding=\"ISO-8859-1\"?>" + NEW_LINE + "<bookstore>" + NEW_LINE + " <book category=\"COOKING\">" + NEW_LINE + " <title lang=\"en\">Everyday Italian</title>" + NEW_LINE + " <author>Giada De Laurentiis</author>" + NEW_LINE + " <year>2005</year>" + NEW_LINE + " <price>30.00</price>" + NEW_LINE + " </book>" + NEW_LINE + " <book category=\"CHILDREN\">" + NEW_LINE + " <title lang=\"en\">Harry Potter</title>" + NEW_LINE + " <author>J K. Rowling</author>" + NEW_LINE + " <year>2006</year>" + NEW_LINE + " <price>29.99</price>" + NEW_LINE + " </book>" + NEW_LINE + " <book category=\"WEB\">" + NEW_LINE + " <title lang=\"en\">Learning XML</title>" + NEW_LINE + " <author>Erik T. Ray</author>" + NEW_LINE + " <year>2003</year>" + NEW_LINE + " <price>31.95</price>" + NEW_LINE + " </book>" + NEW_LINE + "</bookstore>"); // then assertEquals( response() .withStatusCode(OK_200.code()) .withReasonPhrase(OK_200.reasonPhrase()) .withBody("some_body1"), makeRequest( request() .withBody(xmlBody), headersToIgnore) ); // when mockServerClient .clear( request() .withBody(xpath("/bookstore/book[year=2005]/price")) ); // then assertThat( mockServerClient.retrieveActiveExpectations(null), arrayContaining( new Expectation(request() .withBody(xpath("/bookstore/book[year=2006]/price"))) .thenRespond( response() .withBody("some_body2") ) ) ); // - in http assertEquals( response() .withStatusCode(OK_200.code()) .withReasonPhrase(OK_200.reasonPhrase()) .withBody("some_body2"), makeRequest( request() .withBody(xmlBody), headersToIgnore) ); // - in https assertEquals( response() .withStatusCode(OK_200.code()) .withReasonPhrase(OK_200.reasonPhrase()) .withBody("some_body2"), makeRequest( request() .withSecure(true) .withBody(xmlBody), headersToIgnore) ); } @Test public void shouldClearExpectationsWithJsonSchemaBody() { // given JsonSchemaBody jsonSchemaBodyOne = jsonSchema("{" + NEW_LINE + " \"$schema\": \"http://json-schema.org/draft-04/schema#\"," + NEW_LINE + " \"title\": \"Product\"," + NEW_LINE + " \"description\": \"A product from Acme's catalog\"," + NEW_LINE + " \"type\": \"object\"," + NEW_LINE + " \"properties\": {" + NEW_LINE + " \"id\": {" + NEW_LINE + " \"description\": \"The unique identifier for a product\"," + NEW_LINE + " \"type\": \"integer\"" + NEW_LINE + " }," + NEW_LINE + " \"name\": {" + NEW_LINE + " \"description\": \"Name of the product\"," + NEW_LINE + " \"type\": \"string\"" + NEW_LINE + " }," + NEW_LINE + " \"price\": {" + NEW_LINE + " \"type\": \"number\"," + NEW_LINE + " \"minimum\": 0," + NEW_LINE + " \"exclusiveMinimum\": true" + NEW_LINE + " }," + NEW_LINE + " \"tags\": {" + NEW_LINE + " \"type\": \"array\"," + NEW_LINE + " \"items\": {" + NEW_LINE + " \"type\": \"string\"" + NEW_LINE + " }," + NEW_LINE + " \"minItems\": 1," + NEW_LINE + " \"uniqueItems\": true" + NEW_LINE + " }" + NEW_LINE + " }," + NEW_LINE + " \"required\": [\"id\", \"name\", \"price\"]" + NEW_LINE + "}"); JsonSchemaBody jsonSchemaBodyTwo = jsonSchema("{" + NEW_LINE + " \"$schema\": \"http://json-schema.org/draft-04/schema#\"," + NEW_LINE + " \"title\": \"Product\"," + NEW_LINE + " \"description\": \"A product from Acme's catalog\"," + NEW_LINE + " \"type\": \"object\"," + NEW_LINE + " \"properties\": {" + NEW_LINE + " \"id\": {" + NEW_LINE + " \"description\": \"The unique identifier for a product\"," + NEW_LINE + " \"type\": \"integer\"" + NEW_LINE + " }," + NEW_LINE + " \"name\": {" + NEW_LINE + " \"description\": \"Name of the product\"," + NEW_LINE + " \"type\": \"string\"" + NEW_LINE + " }," + NEW_LINE + " \"price\": {" + NEW_LINE + " \"type\": \"number\"," + NEW_LINE + " \"minimum\": 10," + NEW_LINE + " \"exclusiveMinimum\": true" + NEW_LINE + " }," + NEW_LINE + " \"tags\": {" + NEW_LINE + " \"type\": \"array\"," + NEW_LINE + " \"items\": {" + NEW_LINE + " \"type\": \"string\"" + NEW_LINE + " }," + NEW_LINE + " \"minItems\": 1," + NEW_LINE + " \"uniqueItems\": true" + NEW_LINE + " }" + NEW_LINE + " }," + NEW_LINE + " \"required\": [\"id\", \"name\", \"price\"]" + NEW_LINE + "}"); mockServerClient .when( request() .withBody(jsonSchemaBodyOne) ) .respond( response() .withBody("some_body1") ); mockServerClient .when( request() .withBody(jsonSchemaBodyTwo) ) .respond( response() .withBody("some_body2") ); // then assertEquals( response() .withStatusCode(OK_200.code()) .withReasonPhrase(OK_200.reasonPhrase()) .withBody("some_body1"), makeRequest( request() .withBody("{" + NEW_LINE + " \"id\": 1," + NEW_LINE + " \"name\": \"A green door\"," + NEW_LINE + " \"price\": 12.50," + NEW_LINE + " \"tags\": [\"home\", \"green\"]" + NEW_LINE + "}"), headersToIgnore) ); // when mockServerClient .clear( request() .withBody(jsonSchemaBodyOne) ); // then assertThat( mockServerClient.retrieveActiveExpectations(null), arrayContaining( new Expectation(request() .withBody(jsonSchemaBodyTwo)) .thenRespond( response() .withBody("some_body2") ) ) ); // - in http assertEquals( response() .withStatusCode(OK_200.code()) .withReasonPhrase(OK_200.reasonPhrase()) .withBody("some_body2"), makeRequest( request() .withBody("{" + NEW_LINE + " \"id\": 1," + NEW_LINE + " \"name\": \"A green door\"," + NEW_LINE + " \"price\": 12.50," + NEW_LINE + " \"tags\": [\"home\", \"green\"]" + NEW_LINE + "}"), headersToIgnore) ); // - in https assertEquals( response() .withStatusCode(OK_200.code()) .withReasonPhrase(OK_200.reasonPhrase()) .withBody("some_body2"), makeRequest( request() .withSecure(true) .withBody("{" + NEW_LINE + " \"id\": 1," + NEW_LINE + " \"name\": \"A green door\"," + NEW_LINE + " \"price\": 12.50," + NEW_LINE + " \"tags\": [\"home\", \"green\"]" + NEW_LINE + "}"), headersToIgnore) ); } @Test public void shouldClearExpectationsWithParameterBody() { // given mockServerClient .when( request() .withBody(params(param("bodyParameterNameOne", "bodyParameterValueOne"))) ) .respond( response() .withBody("some_body1") ); mockServerClient .when( request() .withBody(params(param("bodyParameterNameTwo", "bodyParameterValueTwo"))) ) .respond( response() .withBody("some_body2") ); // then assertEquals( response() .withStatusCode(OK_200.code()) .withReasonPhrase(OK_200.reasonPhrase()) .withBody("some_body1"), makeRequest( request() .withBody(params(param("bodyParameterName.*", "bodyParameterValue.*"))), headersToIgnore) ); // when mockServerClient .clear( request() .withBody(params(param("bodyParameterNameOne", "bodyParameterValueOne"))) ); // then assertThat( mockServerClient.retrieveActiveExpectations(null), arrayContaining( new Expectation(request() .withBody(params(param("bodyParameterNameTwo", "bodyParameterValueTwo")))) .thenRespond( response() .withBody("some_body2") ) ) ); // - in http assertEquals( response() .withStatusCode(OK_200.code()) .withReasonPhrase(OK_200.reasonPhrase()) .withBody("some_body2"), makeRequest( request() .withBody(params(param("bodyParameterName.*", "bodyParameterValue.*"))), headersToIgnore) ); // - in https assertEquals( response() .withStatusCode(OK_200.code()) .withReasonPhrase(OK_200.reasonPhrase()) .withBody("some_body2"), makeRequest( request() .withSecure(true) .withBody(params(param("bodyParameterName.*", "bodyParameterValue.*"))), headersToIgnore) ); } @Test public void shouldEnsureThatInterruptedRequestsAreVerifiable() throws Exception { mockServerClient .when( request(calculatePath("delayed")) ) .respond( response("delayed data") .withDelay(new Delay(TimeUnit.SECONDS, 3)) ); Future<HttpResponse> delayedFuture = Executors.newSingleThreadExecutor().submit(new Callable<HttpResponse>() { @Override public HttpResponse call() throws Exception { return httpClient.sendRequest( request(addContextToPath(calculatePath("delayed"))) .withHeader(HOST.toString(), "localhost:" + getServerPort()) ).get(10, TimeUnit.SECONDS); } }); Uninterruptibles.sleepUninterruptibly(1, TimeUnit.SECONDS); // Let request reach server delayedFuture.cancel(true); // Then interrupt requesting thread mockServerClient.verify(request(calculatePath("delayed"))); // We should be able to verify request that reached server even though its later interrupted } @Test public void shouldEnsureThatRequestDelaysDoNotAffectOtherRequests() throws Exception { mockServerClient .when( request("/slow") ) .respond( response("super slow") .withDelay(new Delay(TimeUnit.SECONDS, 5)) ); mockServerClient .when( request("/fast") ) .respond( response("quite fast") ); ExecutorService executorService = Executors.newFixedThreadPool(2); Future<Long> slowFuture = executorService.submit(new Callable<Long>() { @Override public Long call() throws Exception { long start = System.currentTimeMillis(); makeRequest(request("/slow"), Collections.<String>emptySet()); return System.currentTimeMillis() - start; } }); // Let fast request come to the server slightly after slow request Uninterruptibles.sleepUninterruptibly(1, TimeUnit.SECONDS); Future<Long> fastFuture = executorService.submit(new Callable<Long>() { @Override public Long call() throws Exception { long start = System.currentTimeMillis(); makeRequest(request("/fast"), Collections.<String>emptySet()); return System.currentTimeMillis() - start; } }); Long slowRequestElapsedMillis = slowFuture.get(); Long fastRequestElapsedMillis = fastFuture.get(); assertThat("Slow request takes less than expected", slowRequestElapsedMillis, is(greaterThan(5 * 1000L))); assertThat("Fast request takes longer than expected", fastRequestElapsedMillis, is(lessThan(5 * 1000L))); } }
dipjyotimetia/mockserver
mockserver-integration-testing/src/main/java/org/mockserver/integration/server/AbstractExtendedMockingIntegrationTest.java
923
package org.mockserver.integration.server; import com.google.common.base.Charsets; import com.google.common.net.HttpHeaders; import com.google.common.net.MediaType; import com.google.common.util.concurrent.Uninterruptibles; import org.apache.commons.io.IOUtils; import org.junit.Before; import org.junit.Test; import org.mockserver.client.netty.NettyHttpClient; import org.mockserver.client.netty.SocketConnectionException; import org.mockserver.client.server.MockServerClient; import org.mockserver.echo.http.EchoServer; import org.mockserver.matchers.HttpRequestMatcher; import org.mockserver.matchers.MatchType; import org.mockserver.matchers.TimeToLive; import org.mockserver.matchers.Times; import org.mockserver.mock.Expectation; import org.mockserver.model.*; import org.mockserver.socket.PortFactory; import org.mockserver.verify.VerificationTimes; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.IOException; import java.util.*; import java.util.concurrent.*; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.*; import static org.hamcrest.core.Is.is; import static org.hamcrest.core.StringStartsWith.startsWith; import static org.hamcrest.number.OrderingComparison.greaterThan; import static org.junit.Assert.*; import static org.mockserver.matchers.Times.exactly; import static org.mockserver.matchers.Times.once; import static org.mockserver.model.BinaryBody.binary; import static org.mockserver.model.Cookie.cookie; import static org.mockserver.model.Header.header; import static org.mockserver.model.HttpCallback.callback; import static org.mockserver.model.HttpForward.forward; import static org.mockserver.model.HttpRequest.request; import static org.mockserver.model.HttpResponse.notFoundResponse; import static org.mockserver.model.HttpResponse.response; import static org.mockserver.model.JsonBody.json; import static org.mockserver.model.JsonSchemaBody.jsonSchema; import static org.mockserver.model.NottableString.not; import static org.mockserver.model.NottableString.string; import static org.mockserver.model.OutboundHttpRequest.outboundRequest; import static org.mockserver.model.Parameter.param; import static org.mockserver.model.ParameterBody.params; import static org.mockserver.model.StringBody.exact; import static org.mockserver.model.XPathBody.xpath; import static org.mockserver.model.XmlBody.xml; /** * @author jamesdbloom */ public abstract class AbstractClientServerIntegrationTest { protected static final String TEXT_PLAIN = MediaType.create("text", "plain").toString(); protected static MockServerClient mockServerClient; protected static String servletContext = ""; private final Logger logger = LoggerFactory.getLogger(this.getClass()); protected List<String> headersToIgnore = Arrays.asList( "server", "expires", "date", "host", "connection", "user-agent", "content-length", "accept-encoding", "transfer-encoding", "access-control-allow-origin", "access-control-allow-methods", "x-cors" ); private NettyHttpClient httpClient = new NettyHttpClient(); public static Expectation expectation(HttpRequest httpRequest) { return new Expectation(httpRequest, Times.unlimited(), TimeToLive.unlimited()); } public abstract int getMockServerPort(); public abstract int getMockServerSecurePort(); public abstract int getTestServerPort(); protected String calculatePath(String path) { return "/" + path; } @Before public void resetServer() { mockServerClient.reset(); } @Test public void shouldForwardRequestInHTTP() { // when mockServerClient .when( request() .withPath(calculatePath("echo")) ) .forward( forward() .withHost("127.0.0.1") .withPort(getTestServerPort()) ); // then // - in http assertEquals( response() .withStatusCode(HttpStatusCode.OK_200.code()) .withHeaders( header("x-test", "test_headers_and_body") ) .withBody("an_example_body_http"), makeRequest( request() .withPath(calculatePath("echo")) .withMethod("POST") .withHeaders( header("x-test", "test_headers_and_body") ) .withBody("an_example_body_http"), headersToIgnore) ); // - in https assertEquals( response() .withStatusCode(HttpStatusCode.OK_200.code()) .withHeaders( header("x-test", "test_headers_and_body") ) .withBody("an_example_body_https"), makeRequest( request() .withSecure(true) .withPath(calculatePath("echo")) .withMethod("POST") .withHeaders( header("x-test", "test_headers_and_body") ) .withBody("an_example_body_https"), headersToIgnore) ); } @Test public void shouldForwardRequestInHTTPS() { int testServerHttpsPort = PortFactory.findFreePort(); EchoServer secureEchoServer = new EchoServer(testServerHttpsPort, true); try { // when mockServerClient .when( request() .withPath(calculatePath("echo")) ) .forward( forward() .withHost("127.0.0.1") .withPort(testServerHttpsPort) .withScheme(HttpForward.Scheme.HTTPS) ); // then // - in http assertEquals( response() .withStatusCode(HttpStatusCode.OK_200.code()) .withHeaders( header("x-test", "test_headers_and_body") ) .withBody("an_example_body_http"), makeRequest( request() .withPath(calculatePath("echo")) .withMethod("POST") .withHeaders( header("x-test", "test_headers_and_body") ) .withBody("an_example_body_http"), headersToIgnore) ); // - in https assertEquals( response() .withStatusCode(HttpStatusCode.OK_200.code()) .withHeaders( header("x-test", "test_headers_and_body") ) .withBody("an_example_body_https"), makeRequest( request() .withSecure(true) .withPath(calculatePath("echo")) .withMethod("POST") .withHeaders( header("x-test", "test_headers_and_body") ) .withBody("an_example_body_https"), headersToIgnore) ); } finally { secureEchoServer.stop(); } } @Test public void shouldAllowSimultaneousForwardAndResponseExpectations() { // when mockServerClient .when( request() .withPath(calculatePath("echo")), once() ) .forward( forward() .withHost("127.0.0.1") .withPort(getTestServerPort()) ); mockServerClient .when( request() .withPath(calculatePath("test_headers_and_body")), once() ) .respond( response() .withBody("some_body") ); // then // - forward assertEquals( response() .withStatusCode(HttpStatusCode.OK_200.code()) .withHeaders( header("x-test", "test_headers_and_body") ) .withBody("an_example_body"), makeRequest( request() .withPath(calculatePath("echo")) .withMethod("POST") .withHeaders( header("x-test", "test_headers_and_body") ) .withBody("an_example_body"), headersToIgnore) ); // - respond assertEquals( response() .withStatusCode(HttpStatusCode.OK_200.code()) .withBody("some_body"), makeRequest( request() .withPath(calculatePath("test_headers_and_body")), headersToIgnore) ); // - no response or forward assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()), makeRequest( request() .withPath(calculatePath("test_headers_and_body")), headersToIgnore) ); } @Test public void shouldCallbackToSpecifiedClassWithPrecannedResponse() { // when mockServerClient .when( request() .withPath(calculatePath("callback")) ) .callback( callback() .withCallbackClass("org.mockserver.integration.callback.PrecannedTestExpectationCallback") ); // then // - in http assertEquals( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withHeaders( header("x-callback", "test_callback_header") ) .withBody("a_callback_response"), makeRequest( request() .withPath(calculatePath("callback")) .withMethod("POST") .withHeaders( header("x-test", "test_headers_and_body") ) .withBody("an_example_body_http"), headersToIgnore ) ); // - in https assertEquals( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withHeaders( header("x-callback", "test_callback_header") ) .withBody("a_callback_response"), makeRequest( request() .withSecure(true) .withPath(calculatePath("callback")) .withMethod("POST") .withHeaders( header("x-test", "test_headers_and_body") ) .withBody("an_example_body_https"), headersToIgnore ) ); } @Test public void shouldReturnResponseWithOnlyBody() { // when mockServerClient.when(request()).respond(response().withBody("some_body")); // then // - in http assertEquals( response() .withStatusCode(HttpStatusCode.OK_200.code()) .withBody("some_body"), makeRequest( request() .withPath(calculatePath("")), headersToIgnore) ); // - in https assertEquals( response() .withStatusCode(HttpStatusCode.OK_200.code()) .withBody("some_body"), makeRequest( request() .withSecure(true) .withPath(calculatePath("")), headersToIgnore) ); } @Test public void shouldReturnResponseForRequestInSsl() { // when mockServerClient.when(request().withSecure(true)).respond(response().withBody("some_body")); // then // - in http assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()), makeRequest( request() .withPath(calculatePath("")), headersToIgnore) ); // - in https assertEquals( response() .withStatusCode(HttpStatusCode.OK_200.code()) .withBody("some_body"), makeRequest( request() .withSecure(true) .withPath(calculatePath("")), headersToIgnore) ); } @Test public void shouldReturnResponseForRequestNotInSsl() { // when mockServerClient.when(request().withSecure(false)).respond(response().withBody("some_body")); // then // - in http assertEquals( response() .withStatusCode(HttpStatusCode.OK_200.code()) .withBody("some_body"), makeRequest( request() .withPath(calculatePath("")), headersToIgnore) ); // - in https assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()), makeRequest( request() .withSecure(true) .withPath(calculatePath("")), headersToIgnore) ); } @Test public void shouldReturnMatchRequestWithBodyInUTF16() { // when String body = "我说中国话"; mockServerClient.when(request().withBody(body, Charsets.UTF_16)).respond(response().withBody(body, Charsets.UTF_8)); // then // - in http assertEquals( response() .withHeader(HttpHeaders.CONTENT_TYPE, MediaType.create("text", "plain").withCharset(Charsets.UTF_8).toString()) .withStatusCode(HttpStatusCode.OK_200.code()) .withBody(body), makeRequest( request() .withPath(calculatePath("")) .withBody(body, Charsets.UTF_16), headersToIgnore) ); // - in https assertEquals( response() .withHeader(HttpHeaders.CONTENT_TYPE, MediaType.create("text", "plain").withCharset(Charsets.UTF_8).toString()) .withStatusCode(HttpStatusCode.OK_200.code()) .withBody(body), makeRequest( request() .withSecure(true) .withPath(calculatePath("")) .withBody(body, Charsets.UTF_16), headersToIgnore) ); } @Test public void shouldReturnMatchRequestWithBodyInUTF16WithContentTypeHeader() { // when String body = "我说中国话"; mockServerClient .when( request() .withHeader(HttpHeaders.CONTENT_TYPE, MediaType.create("text", "plain").withCharset(Charsets.UTF_8).toString()) .withBody(body) ) .respond( response() .withBody(body, Charsets.UTF_8) ); // then // - in http assertEquals( response() .withHeader(HttpHeaders.CONTENT_TYPE, MediaType.create("text", "plain").withCharset(Charsets.UTF_8).toString()) .withStatusCode(HttpStatusCode.OK_200.code()) .withBody(body), makeRequest( request() .withHeader(HttpHeaders.CONTENT_TYPE, MediaType.create("text", "plain").withCharset(Charsets.UTF_8).toString()) .withPath(calculatePath("")) .withBody(body), headersToIgnore) ); // - in https assertEquals( response() .withHeader(HttpHeaders.CONTENT_TYPE, MediaType.create("text", "plain").withCharset(Charsets.UTF_8).toString()) .withStatusCode(HttpStatusCode.OK_200.code()) .withBody(body), makeRequest( request() .withHeader(HttpHeaders.CONTENT_TYPE, MediaType.create("text", "plain").withCharset(Charsets.UTF_8).toString()) .withSecure(true) .withPath(calculatePath("")) .withBody(body), headersToIgnore) ); } @Test public void shouldReturnResponseWithBodyInUTF8() { // when String body = "我说中国话"; mockServerClient.when(request()).respond(response().withBody(body, Charsets.UTF_16)); // then // - in http assertEquals( response() .withHeader(HttpHeaders.CONTENT_TYPE, MediaType.create("text", "plain").withCharset(Charsets.UTF_16).toString()) .withStatusCode(HttpStatusCode.OK_200.code()) .withBody(body), makeRequest( request() .withPath(calculatePath("")), headersToIgnore) ); // - in https assertEquals( response() .withHeader(HttpHeaders.CONTENT_TYPE, MediaType.create("text", "plain").withCharset(Charsets.UTF_16).toString()) .withStatusCode(HttpStatusCode.OK_200.code()) .withBody(body), makeRequest( request() .withSecure(true) .withPath(calculatePath("")), headersToIgnore) ); } @Test public void shouldReturnResponseWithBodyInUTF16WithContentTypeHeader() { // when String body = "我说中国话"; mockServerClient .when( request() ) .respond( response() .withHeader(HttpHeaders.CONTENT_TYPE, MediaType.create("text", "plain").withCharset(Charsets.UTF_8).toString()) .withBody(body) ); // then // - in http assertEquals( response() .withHeader(HttpHeaders.CONTENT_TYPE, MediaType.create("text", "plain").withCharset(Charsets.UTF_8).toString()) .withStatusCode(HttpStatusCode.OK_200.code()) .withBody(body), makeRequest( request() .withPath(calculatePath("")), headersToIgnore) ); // - in https assertEquals( response() .withHeader(HttpHeaders.CONTENT_TYPE, MediaType.create("text", "plain").withCharset(Charsets.UTF_8).toString()) .withStatusCode(HttpStatusCode.OK_200.code()) .withBody(body), makeRequest( request() .withSecure(true) .withPath(calculatePath("")), headersToIgnore) ); } @Test public void shouldReturnResponseWithOnlyStatusCode() { // when mockServerClient .when( request() .withMethod("POST") .withPath(calculatePath("some_path")) ) .respond( response() .withStatusCode(200) ); // then // - in http assertEquals( response() .withStatusCode(HttpStatusCode.OK_200.code()), makeRequest( request() .withPath(calculatePath("some_path")) .withMethod("POST"), headersToIgnore) ); // - in https assertEquals( response() .withStatusCode(HttpStatusCode.OK_200.code()), makeRequest( request() .withSecure(true) .withPath(calculatePath("some_path")) .withMethod("POST"), headersToIgnore) ); } @Test public void shouldReturnResponseByMatchingPath() { // when mockServerClient .when( request() .withPath(calculatePath("some_path1")) ) .respond( response() .withBody("some_body1") ); mockServerClient .when( request() .withPath(calculatePath("some_path2")) ) .respond( response() .withBody("some_body2") ); // then // - in http assertEquals( response() .withStatusCode(HttpStatusCode.OK_200.code()) .withBody("some_body2"), makeRequest( request() .withPath(calculatePath("some_path2")), headersToIgnore) ); assertEquals( response() .withStatusCode(HttpStatusCode.OK_200.code()) .withBody("some_body1"), makeRequest( request() .withPath(calculatePath("some_path1")), headersToIgnore) ); // - in https assertEquals( response() .withStatusCode(HttpStatusCode.OK_200.code()) .withBody("some_body2"), makeRequest( request() .withSecure(true) .withPath(calculatePath("some_path2")), headersToIgnore) ); assertEquals( response() .withStatusCode(HttpStatusCode.OK_200.code()) .withBody("some_body1"), makeRequest( request() .withSecure(true) .withPath(calculatePath("some_path1")), headersToIgnore) ); } @Test public void shouldReturnResponseByMatchingPathExactTimes() { // when mockServerClient .when( request() .withPath(calculatePath("some_path")), exactly(2) ) .respond( response() .withBody("some_body") ); // then // - in http assertEquals( response() .withStatusCode(HttpStatusCode.OK_200.code()) .withBody("some_body"), makeRequest( request() .withPath(calculatePath("some_path")), headersToIgnore) ); // - in https assertEquals( response() .withStatusCode(HttpStatusCode.OK_200.code()) .withBody("some_body"), makeRequest( request() .withSecure(true) .withPath(calculatePath("some_path")), headersToIgnore) ); // - in http assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()), makeRequest( request() .withPath(calculatePath("some_path")), headersToIgnore) ); // - in https assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()), makeRequest( request() .withSecure(true) .withPath(calculatePath("some_path")), headersToIgnore) ); } @Test public void shouldReturnResponseWhenTimeToLiveHasNotExpired() { // when mockServerClient .when( request().withPath(calculatePath("some_path")), exactly(2), TimeToLive.exactly(TimeUnit.HOURS, 1L) ) .respond( response().withBody("some_body") ); // then // - in http assertEquals( response() .withStatusCode(HttpStatusCode.OK_200.code()) .withBody("some_body"), makeRequest( request() .withPath(calculatePath("some_path")), headersToIgnore) ); // - in https assertEquals( response() .withStatusCode(HttpStatusCode.OK_200.code()) .withBody("some_body"), makeRequest( request() .withSecure(true) .withPath(calculatePath("some_path")), headersToIgnore) ); // - in http assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()), makeRequest( request() .withPath(calculatePath("some_path")), headersToIgnore) ); // - in https assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()), makeRequest( request() .withSecure(true) .withPath(calculatePath("some_path")), headersToIgnore) ); } @Test public void shouldReturnResponseByMatchingBodyWithXPath() { // when mockServerClient.when(request().withBody(xpath("/bookstore/book[price>30]/price")), exactly(2)).respond(response().withBody("some_body")); // then // - in http assertEquals( response() .withStatusCode(HttpStatusCode.OK_200.code()) .withBody("some_body"), makeRequest( request() .withPath(calculatePath("some_path")) .withMethod("POST") .withBody(new StringBody("" + "<?xml version=\"1.0\" encoding=\"ISO-8859-1\"?>" + System.getProperty("line.separator") + "<bookstore>" + System.getProperty("line.separator") + " <book category=\"COOKING\">" + System.getProperty("line.separator") + " <title lang=\"en\">Everyday Italian</title>" + System.getProperty("line.separator") + " <author>Giada De Laurentiis</author>" + System.getProperty("line.separator") + " <year>2005</year>" + System.getProperty("line.separator") + " <price>30.00</price>" + System.getProperty("line.separator") + " </book>" + System.getProperty("line.separator") + " <book category=\"CHILDREN\">" + System.getProperty("line.separator") + " <title lang=\"en\">Harry Potter</title>" + System.getProperty("line.separator") + " <author>J K. Rowling</author>" + System.getProperty("line.separator") + " <year>2005</year>" + System.getProperty("line.separator") + " <price>29.99</price>" + System.getProperty("line.separator") + " </book>" + System.getProperty("line.separator") + " <book category=\"WEB\">" + System.getProperty("line.separator") + " <title lang=\"en\">Learning XML</title>" + System.getProperty("line.separator") + " <author>Erik T. Ray</author>" + System.getProperty("line.separator") + " <year>2003</year>" + System.getProperty("line.separator") + " <price>31.95</price>" + System.getProperty("line.separator") + " </book>" + System.getProperty("line.separator") + "</bookstore>")), headersToIgnore) ); // - in https assertEquals( response() .withStatusCode(HttpStatusCode.OK_200.code()) .withBody("some_body"), makeRequest( request() .withSecure(true) .withPath(calculatePath("some_path")) .withMethod("POST") .withBody(new StringBody("" + "<?xml version=\"1.0\" encoding=\"ISO-8859-1\"?>" + System.getProperty("line.separator") + "<bookstore>" + System.getProperty("line.separator") + " <book category=\"COOKING\">" + System.getProperty("line.separator") + " <title lang=\"en\">Everyday Italian</title>" + System.getProperty("line.separator") + " <author>Giada De Laurentiis</author>" + System.getProperty("line.separator") + " <year>2005</year>" + System.getProperty("line.separator") + " <price>30.00</price>" + System.getProperty("line.separator") + " </book>" + System.getProperty("line.separator") + " <book category=\"CHILDREN\">" + System.getProperty("line.separator") + " <title lang=\"en\">Harry Potter</title>" + System.getProperty("line.separator") + " <author>J K. Rowling</author>" + System.getProperty("line.separator") + " <year>2005</year>" + System.getProperty("line.separator") + " <price>29.99</price>" + System.getProperty("line.separator") + " </book>" + System.getProperty("line.separator") + " <book category=\"WEB\">" + System.getProperty("line.separator") + " <title lang=\"en\">Learning XML</title>" + System.getProperty("line.separator") + " <author>Erik T. Ray</author>" + System.getProperty("line.separator") + " <year>2003</year>" + System.getProperty("line.separator") + " <price>31.95</price>" + System.getProperty("line.separator") + " </book>" + System.getProperty("line.separator") + "</bookstore>")), headersToIgnore) ); } @Test public void shouldReturnResponseByMatchingBodyWithXml() { // when mockServerClient.when(request().withBody(xml("" + "<bookstore>" + System.getProperty("line.separator") + " <book nationality=\"ITALIAN\" category=\"COOKING\"><title lang=\"en\">Everyday Italian</title><author>Giada De Laurentiis</author><year>2005</year><price>30.00</price></book>" + System.getProperty("line.separator") + "</bookstore>")), exactly(2)).respond(response().withBody("some_body")); // then // - in http assertEquals( response() .withStatusCode(HttpStatusCode.OK_200.code()) .withBody("some_body"), makeRequest( request() .withPath(calculatePath("some_path")) .withMethod("POST") .withBody(new StringBody("" + "<?xml version=\"1.0\" encoding=\"ISO-8859-1\"?>" + System.getProperty("line.separator") + "<bookstore>" + System.getProperty("line.separator") + " <book category=\"COOKING\" nationality=\"ITALIAN\">" + System.getProperty("line.separator") + " <title lang=\"en\">Everyday Italian</title>" + System.getProperty("line.separator") + " <author>Giada De Laurentiis</author>" + System.getProperty("line.separator") + " <year>2005</year>" + System.getProperty("line.separator") + " <price>30.00</price>" + System.getProperty("line.separator") + " </book>" + System.getProperty("line.separator") + "</bookstore>")), headersToIgnore) ); // - in https assertEquals( response() .withStatusCode(HttpStatusCode.OK_200.code()) .withBody("some_body"), makeRequest( request() .withSecure(true) .withPath(calculatePath("some_path")) .withMethod("POST") .withBody(new StringBody("" + "<?xml version=\"1.0\" encoding=\"ISO-8859-1\"?>" + System.getProperty("line.separator") + "<bookstore>" + System.getProperty("line.separator") + " <book category=\"COOKING\" nationality=\"ITALIAN\">" + System.getProperty("line.separator") + " <title lang=\"en\">Everyday Italian</title>" + System.getProperty("line.separator") + " <author>Giada De Laurentiis</author>" + System.getProperty("line.separator") + " <year>2005</year>" + System.getProperty("line.separator") + " <price>30.00</price>" + System.getProperty("line.separator") + " </book>" + System.getProperty("line.separator") + "</bookstore>")), headersToIgnore) ); } @Test public void shouldReturnResponseByMatchingBodyWithJson() { // when mockServerClient .when( request() .withBody(json("{" + System.getProperty("line.separator") + " \"id\": 1," + System.getProperty("line.separator") + " \"name\": \"A green door\"," + System.getProperty("line.separator") + " \"price\": 12.50," + System.getProperty("line.separator") + " \"tags\": [\"home\", \"green\"]" + System.getProperty("line.separator") + "}")), exactly(2) ) .respond( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body") ); // then // - in http assertEquals( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body"), makeRequest( request() .withPath(calculatePath("some_path")) .withMethod("POST") .withBody("{" + System.getProperty("line.separator") + " \"id\": 1," + System.getProperty("line.separator") + " \"extra ignored field\": \"some value\"," + System.getProperty("line.separator") + " \"name\": \"A green door\"," + System.getProperty("line.separator") + " \"price\": 12.50," + System.getProperty("line.separator") + " \"tags\": [\"home\", \"green\"]" + System.getProperty("line.separator") + "}"), headersToIgnore) ); // - in https assertEquals( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body"), makeRequest( request() .withSecure(true) .withPath(calculatePath("some_path")) .withMethod("POST") .withBody("{" + System.getProperty("line.separator") + " \"id\": 1," + System.getProperty("line.separator") + " \"extra ignored array\": [\"one\", \"two\"]," + System.getProperty("line.separator") + " \"name\": \"A green door\"," + System.getProperty("line.separator") + " \"price\": 12.50," + System.getProperty("line.separator") + " \"tags\": [\"home\", \"green\"]" + System.getProperty("line.separator") + "}"), headersToIgnore) ); } @Test public void shouldReturnResponseByMatchingBodyWithJsonWithCharsetUTF8() { // when mockServerClient .when( request() .withBody(json("{" + System.getProperty("line.separator") + " \"ταυτότητα\": 1," + System.getProperty("line.separator") + " \"όνομα\": \"μια πράσινη πόρτα\"," + System.getProperty("line.separator") + " \"τιμή\": 12.50," + System.getProperty("line.separator") + " \"ετικέτες\": [\"σπίτι\", \"πράσινος\"]" + System.getProperty("line.separator") + "}", Charsets.UTF_16, MatchType.ONLY_MATCHING_FIELDS)), exactly(2) ) .respond( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body") ); // then // - in http assertEquals( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body"), makeRequest( request() .withPath(calculatePath("some_path")) .withMethod("POST") .withBody(json("{" + System.getProperty("line.separator") + " \"ταυτότητα\": 1," + System.getProperty("line.separator") + " \"επιπλέον αγνοούνται τομέα\": \"κάποια αξία\"," + System.getProperty("line.separator") + " \"όνομα\": \"μια πράσινη πόρτα\"," + System.getProperty("line.separator") + " \"τιμή\": 12.50," + System.getProperty("line.separator") + " \"ετικέτες\": [\"σπίτι\", \"πράσινος\"]" + System.getProperty("line.separator") + "}", Charsets.UTF_16, MatchType.ONLY_MATCHING_FIELDS)), headersToIgnore) ); // - in https assertEquals( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body"), makeRequest( request() .withSecure(true) .withPath(calculatePath("some_path")) .withMethod("POST") .withBody(json("{" + System.getProperty("line.separator") + " \"ταυτότητα\": 1," + System.getProperty("line.separator") + " \"επιπλέον αγνοούνται σειρά\": [\"ένας\", \"δυο\"]," + System.getProperty("line.separator") + " \"όνομα\": \"μια πράσινη πόρτα\"," + System.getProperty("line.separator") + " \"τιμή\": 12.50," + System.getProperty("line.separator") + " \"ετικέτες\": [\"σπίτι\", \"πράσινος\"]" + System.getProperty("line.separator") + "}", Charsets.UTF_16, MatchType.ONLY_MATCHING_FIELDS)), headersToIgnore) ); } @Test public void shouldReturnResponseByMatchingBodyWithJsonWithContentTypeHeader() { // when mockServerClient .when( request() .withBody(json("{" + System.getProperty("line.separator") + " \"ταυτότητα\": 1," + System.getProperty("line.separator") + " \"όνομα\": \"μια πράσινη πόρτα\"," + System.getProperty("line.separator") + " \"τιμή\": 12.50," + System.getProperty("line.separator") + " \"ετικέτες\": [\"σπίτι\", \"πράσινος\"]" + System.getProperty("line.separator") + "}", Charsets.UTF_16, MatchType.ONLY_MATCHING_FIELDS)), exactly(2) ) .respond( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body") ); // then // - in http assertEquals( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body"), makeRequest( request() .withHeader(HttpHeaders.CONTENT_TYPE, MediaType.create("text", "plain").withCharset(Charsets.UTF_16).toString()) .withPath(calculatePath("some_path")) .withMethod("POST") .withBody(json("{" + System.getProperty("line.separator") + " \"ταυτότητα\": 1," + System.getProperty("line.separator") + " \"επιπλέον αγνοούνται τομέα\": \"κάποια αξία\"," + System.getProperty("line.separator") + " \"όνομα\": \"μια πράσινη πόρτα\"," + System.getProperty("line.separator") + " \"τιμή\": 12.50," + System.getProperty("line.separator") + " \"ετικέτες\": [\"σπίτι\", \"πράσινος\"]" + System.getProperty("line.separator") + "}")), headersToIgnore) ); // - in https assertEquals( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body"), makeRequest( request() .withSecure(true) .withHeader(HttpHeaders.CONTENT_TYPE, MediaType.create("text", "plain").withCharset(Charsets.UTF_16).toString()) .withPath(calculatePath("some_path")) .withMethod("POST") .withBody(json("{" + System.getProperty("line.separator") + " \"ταυτότητα\": 1," + System.getProperty("line.separator") + " \"επιπλέον αγνοούνται σειρά\": [\"ένας\", \"δυο\"]," + System.getProperty("line.separator") + " \"όνομα\": \"μια πράσινη πόρτα\"," + System.getProperty("line.separator") + " \"τιμή\": 12.50," + System.getProperty("line.separator") + " \"ετικέτες\": [\"σπίτι\", \"πράσινος\"]" + System.getProperty("line.separator") + "}")), headersToIgnore) ); } @Test public void shouldReturnResponseByMatchingBodyWithJsonWithMatchType() { // when mockServerClient .when( request() .withBody(json("{" + System.getProperty("line.separator") + " \"id\": 1," + System.getProperty("line.separator") + " \"name\": \"A green door\"," + System.getProperty("line.separator") + " \"price\": 12.50," + System.getProperty("line.separator") + " \"tags\": [\"home\", \"green\"]" + System.getProperty("line.separator") + "}", MatchType.ONLY_MATCHING_FIELDS)), exactly(2) ) .respond( response() .withBody("some_body") ); // then // - in http assertEquals( response("some_body"), makeRequest( request() .withPath(calculatePath("some_path")) .withMethod("POST") .withBody("{" + System.getProperty("line.separator") + " \"id\": 1," + System.getProperty("line.separator") + " \"extra field\": \"some value\"," + System.getProperty("line.separator") + " \"name\": \"A green door\"," + System.getProperty("line.separator") + " \"price\": 12.50," + System.getProperty("line.separator") + " \"tags\": [\"home\", \"green\"]" + System.getProperty("line.separator") + "}"), headersToIgnore) ); // - in https assertEquals( response("some_body"), makeRequest( request() .withSecure(true) .withPath(calculatePath("some_path")) .withMethod("POST") .withBody("{" + System.getProperty("line.separator") + " \"id\": 1," + System.getProperty("line.separator") + " \"extra field\": \"some value\"," + System.getProperty("line.separator") + " \"name\": \"A green door\"," + System.getProperty("line.separator") + " \"price\": 12.50," + System.getProperty("line.separator") + " \"tags\": [\"home\", \"green\"]" + System.getProperty("line.separator") + "}"), headersToIgnore) ); } @Test public void shouldReturnResponseByMatchingBodyWithJsonSchema() { // when mockServerClient.when(request().withBody(jsonSchema("{" + System.getProperty("line.separator") + " \"$schema\": \"http://json-schema.org/draft-04/schema#\"," + System.getProperty("line.separator") + " \"title\": \"Product\"," + System.getProperty("line.separator") + " \"description\": \"A product from Acme's catalog\"," + System.getProperty("line.separator") + " \"type\": \"object\"," + System.getProperty("line.separator") + " \"properties\": {" + System.getProperty("line.separator") + " \"id\": {" + System.getProperty("line.separator") + " \"description\": \"The unique identifier for a product\"," + System.getProperty("line.separator") + " \"type\": \"integer\"" + System.getProperty("line.separator") + " }," + System.getProperty("line.separator") + " \"name\": {" + System.getProperty("line.separator") + " \"description\": \"Name of the product\"," + System.getProperty("line.separator") + " \"type\": \"string\"" + System.getProperty("line.separator") + " }," + System.getProperty("line.separator") + " \"price\": {" + System.getProperty("line.separator") + " \"type\": \"number\"," + System.getProperty("line.separator") + " \"minimum\": 0," + System.getProperty("line.separator") + " \"exclusiveMinimum\": true" + System.getProperty("line.separator") + " }," + System.getProperty("line.separator") + " \"tags\": {" + System.getProperty("line.separator") + " \"type\": \"array\"," + System.getProperty("line.separator") + " \"items\": {" + System.getProperty("line.separator") + " \"type\": \"string\"" + System.getProperty("line.separator") + " }," + System.getProperty("line.separator") + " \"minItems\": 1," + System.getProperty("line.separator") + " \"uniqueItems\": true" + System.getProperty("line.separator") + " }" + System.getProperty("line.separator") + " }," + System.getProperty("line.separator") + " \"required\": [\"id\", \"name\", \"price\"]" + System.getProperty("line.separator") + "}")), exactly(2)).respond(response().withBody("some_body")); // then // - in http assertEquals( response() .withStatusCode(HttpStatusCode.OK_200.code()) .withBody("some_body"), makeRequest( request() .withPath(calculatePath("some_path")) .withMethod("POST") .withBody("{" + System.getProperty("line.separator") + " \"id\": 1," + System.getProperty("line.separator") + " \"name\": \"A green door\"," + System.getProperty("line.separator") + " \"price\": 12.50," + System.getProperty("line.separator") + " \"tags\": [\"home\", \"green\"]" + System.getProperty("line.separator") + "}"), headersToIgnore) ); // - in https assertEquals( response() .withStatusCode(HttpStatusCode.OK_200.code()) .withBody("some_body"), makeRequest( request() .withSecure(true) .withPath(calculatePath("some_path")) .withMethod("POST") .withBody("{" + System.getProperty("line.separator") + " \"id\": 1," + System.getProperty("line.separator") + " \"name\": \"A green door\"," + System.getProperty("line.separator") + " \"price\": 12.50," + System.getProperty("line.separator") + " \"tags\": [\"home\", \"green\"]" + System.getProperty("line.separator") + "}"), headersToIgnore) ); } @Test public void shouldReturnPDFResponseByMatchingPath() throws IOException { // when byte[] pdfBytes = IOUtils.toByteArray(getClass().getClassLoader().getResourceAsStream("test.pdf")); mockServerClient .when( request() .withPath(calculatePath("ws/rest/user/[0-9]+/document/[0-9]+\\.pdf")) ) .respond( response() .withStatusCode(HttpStatusCode.OK_200.code()) .withHeaders( header(HttpHeaders.CONTENT_TYPE, MediaType.PDF.toString()), header(HttpHeaders.CONTENT_DISPOSITION, "form-data; name=\"test.pdf\"; filename=\"test.pdf\""), header(HttpHeaders.CACHE_CONTROL, "must-revalidate, post-check=0, pre-check=0") ) .withBody(binary(pdfBytes)) ); // then // - in http assertEquals( response() .withStatusCode(HttpStatusCode.OK_200.code()) .withHeaders( header(HttpHeaders.CONTENT_DISPOSITION, "form-data; name=\"test.pdf\"; filename=\"test.pdf\""), header(HttpHeaders.CACHE_CONTROL, "must-revalidate, post-check=0, pre-check=0"), header(HttpHeaders.CONTENT_TYPE, MediaType.PDF.toString()) ) .withBody(binary(pdfBytes)), makeRequest( request() .withPath(calculatePath("ws/rest/user/1/document/2.pdf")) .withMethod("GET"), headersToIgnore) ); // - in https assertEquals( response() .withStatusCode(HttpStatusCode.OK_200.code()) .withHeaders( header(HttpHeaders.CONTENT_DISPOSITION, "form-data; name=\"test.pdf\"; filename=\"test.pdf\""), header(HttpHeaders.CACHE_CONTROL, "must-revalidate, post-check=0, pre-check=0"), header(HttpHeaders.CONTENT_TYPE, MediaType.PDF.toString()) ) .withBody(binary(pdfBytes)), makeRequest( request() .withSecure(true) .withPath(calculatePath("ws/rest/user/1/document/2.pdf")) .withMethod("GET"), headersToIgnore) ); } @Test public void shouldReturnPNGResponseByMatchingPath() throws IOException { // when byte[] pngBytes = IOUtils.toByteArray(getClass().getClassLoader().getResourceAsStream("test.png")); mockServerClient .when( request() .withPath(calculatePath("ws/rest/user/[0-9]+/icon/[0-9]+\\.png")) ) .respond( response() .withStatusCode(HttpStatusCode.OK_200.code()) .withHeaders( header(HttpHeaders.CONTENT_TYPE, MediaType.PNG.toString()), header(HttpHeaders.CONTENT_DISPOSITION, "form-data; name=\"test.png\"; filename=\"test.png\"") ) .withBody(binary(pngBytes)) ); // then // - in http assertEquals( response() .withStatusCode(HttpStatusCode.OK_200.code()) .withHeaders( header(HttpHeaders.CONTENT_DISPOSITION, "form-data; name=\"test.png\"; filename=\"test.png\""), header(HttpHeaders.CONTENT_TYPE, MediaType.PNG.toString()) ) .withBody(binary(pngBytes)), makeRequest( request() .withPath(calculatePath("ws/rest/user/1/icon/1.png")) .withMethod("GET"), headersToIgnore) ); // - in https assertEquals( response() .withStatusCode(HttpStatusCode.OK_200.code()) .withHeaders( header(HttpHeaders.CONTENT_DISPOSITION, "form-data; name=\"test.png\"; filename=\"test.png\""), header(HttpHeaders.CONTENT_TYPE, MediaType.PNG.toString()) ) .withBody(binary(pngBytes)), makeRequest( request() .withSecure(true) .withPath(calculatePath("ws/rest/user/1/icon/1.png")) .withMethod("GET"), headersToIgnore) ); } @Test public void shouldReturnPDFResponseByMatchingBinaryPDFBody() throws IOException { // when byte[] pdfBytes = IOUtils.toByteArray(getClass().getClassLoader().getResourceAsStream("test.pdf")); mockServerClient .when( request().withBody(binary(pdfBytes)) ) .respond( response() .withStatusCode(HttpStatusCode.OK_200.code()) .withHeaders( header(HttpHeaders.CONTENT_TYPE, MediaType.PDF.toString()), header(HttpHeaders.CONTENT_DISPOSITION, "form-data; name=\"test.pdf\"; filename=\"test.pdf\""), header(HttpHeaders.CACHE_CONTROL, "must-revalidate, post-check=0, pre-check=0") ) .withBody(binary(pdfBytes)) ); // then // - in http assertEquals( response() .withStatusCode(HttpStatusCode.OK_200.code()) .withHeaders( header(HttpHeaders.CONTENT_DISPOSITION, "form-data; name=\"test.pdf\"; filename=\"test.pdf\""), header(HttpHeaders.CACHE_CONTROL, "must-revalidate, post-check=0, pre-check=0"), header(HttpHeaders.CONTENT_TYPE, MediaType.PDF.toString()) ) .withBody(binary(pdfBytes)), makeRequest( request() .withPath(calculatePath("ws/rest/user/1/document/2.pdf")) .withBody(binary(pdfBytes)) .withMethod("POST"), headersToIgnore) ); // - in https assertEquals( response() .withStatusCode(HttpStatusCode.OK_200.code()) .withHeaders( header(HttpHeaders.CONTENT_DISPOSITION, "form-data; name=\"test.pdf\"; filename=\"test.pdf\""), header(HttpHeaders.CACHE_CONTROL, "must-revalidate, post-check=0, pre-check=0"), header(HttpHeaders.CONTENT_TYPE, MediaType.PDF.toString()) ) .withBody(binary(pdfBytes)), makeRequest( request() .withSecure(true) .withPath(calculatePath("ws/rest/user/1/document/2.pdf")) .withBody(binary(pdfBytes)) .withMethod("POST"), headersToIgnore) ); } @Test public void shouldReturnPNGResponseByMatchingBinaryPNGBody() throws IOException { // when byte[] pngBytes = IOUtils.toByteArray(getClass().getClassLoader().getResourceAsStream("test.png")); mockServerClient .when( request().withBody(binary(pngBytes)) ) .respond( response() .withStatusCode(HttpStatusCode.OK_200.code()) .withHeaders( header(HttpHeaders.CONTENT_TYPE, MediaType.PNG.toString()), header(HttpHeaders.CONTENT_DISPOSITION, "form-data; name=\"test.png\"; filename=\"test.png\"") ) .withBody(binary(pngBytes)) ); // then // - in http assertEquals( response() .withStatusCode(HttpStatusCode.OK_200.code()) .withHeaders( header(HttpHeaders.CONTENT_DISPOSITION, "form-data; name=\"test.png\"; filename=\"test.png\""), header(HttpHeaders.CONTENT_TYPE, MediaType.PNG.toString()) ) .withBody(binary(pngBytes)), makeRequest( request() .withPath(calculatePath("ws/rest/user/1/icon/1.png")) .withBody(binary(pngBytes)) .withMethod("POST"), headersToIgnore) ); // - in https assertEquals( response() .withStatusCode(HttpStatusCode.OK_200.code()) .withHeaders( header(HttpHeaders.CONTENT_DISPOSITION, "form-data; name=\"test.png\"; filename=\"test.png\""), header(HttpHeaders.CONTENT_TYPE, MediaType.PNG.toString()) ) .withBody(binary(pngBytes)), makeRequest( request() .withSecure(true) .withPath(calculatePath("ws/rest/user/1/icon/1.png")) .withBody(binary(pngBytes)) .withMethod("POST"), headersToIgnore) ); } @Test public void shouldReturnResponseForExpectationWithDelay() { // when mockServerClient .when( request() .withPath(calculatePath("some_path1")) ) .respond( response() .withBody("some_body1") .withDelay(new Delay(TimeUnit.MILLISECONDS, 10)) ); mockServerClient .when( request() .withPath(calculatePath("some_path2")) ) .respond( response() .withBody("some_body2") .withDelay(new Delay(TimeUnit.MILLISECONDS, 20)) ); // then // - in http assertEquals( response() .withStatusCode(HttpStatusCode.OK_200.code()) .withBody("some_body2"), makeRequest( request() .withPath(calculatePath("some_path2")), headersToIgnore) ); assertEquals( response() .withStatusCode(HttpStatusCode.OK_200.code()) .withBody("some_body1"), makeRequest( request() .withPath(calculatePath("some_path1")), headersToIgnore) ); // - in https assertEquals( response() .withStatusCode(HttpStatusCode.OK_200.code()) .withBody("some_body2"), makeRequest( request() .withSecure(true) .withPath(calculatePath("some_path2")), headersToIgnore) ); assertEquals( response() .withStatusCode(HttpStatusCode.OK_200.code()) .withBody("some_body1"), makeRequest( request() .withSecure(true) .withPath(calculatePath("some_path1")), headersToIgnore) ); } @Test public void shouldReturnResponseByMatchingPathAndMethod() { // when mockServerClient .when( request() .withMethod("GET") .withPath(calculatePath("some_pathRequest")) ) .respond( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body_response") ); // then // - in http assertEquals( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body_response"), makeRequest( request() .withMethod("GET") .withPath(calculatePath("some_pathRequest")) .withQueryStringParameters( param("queryStringParameterOneName", "queryStringParameterOneValue"), param("queryStringParameterTwoName", "queryStringParameterTwoValue") ) .withHeaders(header("headerNameRequest", "headerValueRequest")) .withCookies(cookie("cookieNameRequest", "cookieValueRequest")), headersToIgnore) ); // - in https assertEquals( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body_response"), makeRequest( request() .withMethod("GET") .withSecure(true) .withPath(calculatePath("some_pathRequest")) .withQueryStringParameters( param("queryStringParameterOneName", "queryStringParameterOneValue"), param("queryStringParameterTwoName", "queryStringParameterTwoValue") ) .withHeaders(header("headerNameRequest", "headerValueRequest")) .withCookies(cookie("cookieNameRequest", "cookieValueRequest")), headersToIgnore) ); } @Test public void shouldReturnResponseByNotMatchingPathWithNotOperator() { // when mockServerClient .when( request() .withPath(not(calculatePath("some_path"))) ) .respond( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body_response") ); // then // - in http assertEquals( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body_response"), makeRequest( request() .withPath(calculatePath("some_other_path")), headersToIgnore) ); // - in https assertEquals( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body_response"), makeRequest( request() .withPath(calculatePath("some_other_path")), headersToIgnore) ); } @Test public void shouldReturnResponseByNotMatchingMethodWithNotOperator() { // when mockServerClient .when( request() .withMethod(not("GET")) ) .respond( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body_response") ); // then // - in http assertEquals( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body_response"), makeRequest( request() .withMethod("POST"), headersToIgnore) ); // - in https assertEquals( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body_response"), makeRequest( request() .withMethod("POST"), headersToIgnore) ); } @Test public void shouldReturnResponseByMatchingPathAndMethodAndBody() { // when mockServerClient .when( request() .withMethod("POST") .withPath(calculatePath("some_pathRequest")) .withBody("some_bodyRequest") ) .respond( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body_response") .withHeaders(header("headerNameResponse", "headerValueResponse")) ); // then // - in http assertEquals( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body_response") .withHeaders( header("headerNameResponse", "headerValueResponse") ), makeRequest( request() .withMethod("POST") .withPath(calculatePath("some_pathRequest")) .withQueryStringParameters( param("queryStringParameterOneName", "queryStringParameterOneValue"), param("queryStringParameterTwoName", "queryStringParameterTwoValue") ) .withBody("some_bodyRequest") .withHeaders(header("headerNameRequest", "headerValueRequest")) .withCookies(cookie("cookieNameRequest", "cookieValueRequest")), headersToIgnore) ); // - in https assertEquals( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body_response") .withHeaders( header("headerNameResponse", "headerValueResponse") ), makeRequest( request() .withMethod("POST") .withSecure(true) .withPath(calculatePath("some_pathRequest")) .withQueryStringParameters( param("queryStringParameterOneName", "queryStringParameterOneValue"), param("queryStringParameterTwoName", "queryStringParameterTwoValue") ) .withBody("some_bodyRequest") .withHeaders(header("headerNameRequest", "headerValueRequest")) .withCookies(cookie("cookieNameRequest", "cookieValueRequest")), headersToIgnore) ); } @Test public void shouldReturnResponseByMatchingPathAndMethodAndQueryStringParameters() { // when mockServerClient .when( request() .withMethod("GET") .withPath(calculatePath("some_pathRequest")) .withQueryStringParameters( param("queryStringParameterOneName", "queryStringParameterOneValue"), param("queryStringParameterTwoName", "queryStringParameterTwoValue") ) ) .respond( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body_response") .withCookies(cookie("cookieNameResponse", "cookieValueResponse")) ); // then // - in http assertEquals( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body_response") .withCookies(cookie("cookieNameResponse", "cookieValueResponse")) .withHeaders( header("Set-Cookie", "cookieNameResponse=cookieValueResponse") ), makeRequest( request() .withMethod("GET") .withPath(calculatePath("some_pathRequest")) .withQueryStringParameters( param("queryStringParameterOneName", "queryStringParameterOneValue"), param("queryStringParameterTwoName", "queryStringParameterTwoValue") ) .withHeaders(header("headerNameRequest", "headerValueRequest")) .withCookies(cookie("cookieNameRequest", "cookieValueRequest")), headersToIgnore) ); // - in https assertEquals( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body_response") .withCookies(cookie("cookieNameResponse", "cookieValueResponse")) .withHeaders( header("Set-Cookie", "cookieNameResponse=cookieValueResponse") ), makeRequest( request() .withMethod("GET") .withSecure(true) .withPath(calculatePath("some_pathRequest")) .withQueryStringParameters( param("queryStringParameterOneName", "queryStringParameterOneValue"), param("queryStringParameterTwoName", "queryStringParameterTwoValue") ) .withHeaders(header("headerNameRequest", "headerValueRequest")) .withCookies(cookie("cookieNameRequest", "cookieValueRequest")), headersToIgnore) ); } @Test public void shouldReturnResponseByMatchingPathAndMethodAndHeaders() { // when mockServerClient .when( request() .withMethod("GET") .withPath(calculatePath("some_pathRequest")) .withHeaders( header("requestHeaderNameOne", "requestHeaderValueOne_One", "requestHeaderValueOne_Two"), header("requestHeaderNameTwo", "requestHeaderValueTwo") ) ) .respond( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body_response") .withCookies(cookie("cookieNameResponse", "cookieValueResponse")) ); // then // - in http assertEquals( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body_response") .withCookies(cookie("cookieNameResponse", "cookieValueResponse")) .withHeaders( header("Set-Cookie", "cookieNameResponse=cookieValueResponse") ), makeRequest( request() .withMethod("GET") .withPath(calculatePath("some_pathRequest")) .withHeaders( header("requestHeaderNameOne", "requestHeaderValueOne_One", "requestHeaderValueOne_Two"), header("requestHeaderNameTwo", "requestHeaderValueTwo") ) .withCookies(cookie("cookieNameRequest", "cookieValueRequest")), headersToIgnore) ); // - in https assertEquals( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body_response") .withCookies(cookie("cookieNameResponse", "cookieValueResponse")) .withHeaders( header("Set-Cookie", "cookieNameResponse=cookieValueResponse") ), makeRequest( request() .withMethod("GET") .withSecure(true) .withPath(calculatePath("some_pathRequest")) .withHeaders( header("requestHeaderNameOne", "requestHeaderValueOne_One", "requestHeaderValueOne_Two"), header("requestHeaderNameTwo", "requestHeaderValueTwo") ) .withCookies(cookie("cookieNameRequest", "cookieValueRequest")), headersToIgnore) ); } @Test public void shouldReturnResponseByMatchingPathAndMethodAndCookies() { // when mockServerClient .when( request() .withMethod("GET") .withPath(calculatePath("some_pathRequest")) .withCookies( cookie("requestCookieNameOne", "requestCookieValueOne"), cookie("requestCookieNameTwo", "requestCookieValueTwo") ) ) .respond( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body_response") .withCookies( cookie("responseCookieNameOne", "responseCookieValueOne"), cookie("responseCookieNameTwo", "responseCookieValueTwo") ) ); // then // - in http - cookie objects assertEquals( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body_response") .withCookies( cookie("responseCookieNameOne", "responseCookieValueOne"), cookie("responseCookieNameTwo", "responseCookieValueTwo") ) .withHeaders( header("Set-Cookie", "responseCookieNameOne=responseCookieValueOne", "responseCookieNameTwo=responseCookieValueTwo") ), makeRequest( request() .withMethod("GET") .withPath(calculatePath("some_pathRequest")) .withHeaders( header("headerNameRequest", "headerValueRequest"), header(HttpHeaders.CONTENT_TYPE, TEXT_PLAIN) ) .withCookies( cookie("requestCookieNameOne", "requestCookieValueOne"), cookie("requestCookieNameTwo", "requestCookieValueTwo") ), headersToIgnore) ); // - in http - cookie header assertEquals( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body_response") .withCookies( cookie("responseCookieNameOne", "responseCookieValueOne"), cookie("responseCookieNameTwo", "responseCookieValueTwo") ) .withHeaders( header("Set-Cookie", "responseCookieNameOne=responseCookieValueOne", "responseCookieNameTwo=responseCookieValueTwo") ), makeRequest( request() .withMethod("GET") .withPath(calculatePath("some_pathRequest")) .withHeaders( header("headerNameRequest", "headerValueRequest"), header("Cookie", "requestCookieNameOne=requestCookieValueOne; requestCookieNameTwo=requestCookieValueTwo") ), headersToIgnore) ); // - in https - cookie objects assertEquals( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body_response") .withCookies( cookie("responseCookieNameOne", "responseCookieValueOne"), cookie("responseCookieNameTwo", "responseCookieValueTwo") ) .withHeaders( header("Set-Cookie", "responseCookieNameOne=responseCookieValueOne", "responseCookieNameTwo=responseCookieValueTwo") ), makeRequest( request() .withMethod("GET") .withSecure(true) .withPath(calculatePath("some_pathRequest")) .withHeaders( header("headerNameRequest", "headerValueRequest") ) .withCookies( cookie("requestCookieNameOne", "requestCookieValueOne"), cookie("requestCookieNameTwo", "requestCookieValueTwo") ), headersToIgnore) ); // - in https - cookie header assertEquals( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body_response") .withCookies( cookie("responseCookieNameOne", "responseCookieValueOne"), cookie("responseCookieNameTwo", "responseCookieValueTwo") ) .withHeaders( header("Set-Cookie", "responseCookieNameOne=responseCookieValueOne", "responseCookieNameTwo=responseCookieValueTwo") ), makeRequest( request() .withMethod("GET") .withSecure(true) .withPath(calculatePath("some_pathRequest")) .withHeaders( header("headerNameRequest", "headerValueRequest"), header("Cookie", "requestCookieNameOne=requestCookieValueOne; requestCookieNameTwo=requestCookieValueTwo") ), headersToIgnore) ); } @Test public void shouldReturnResponseByMatchingPathAndMethodAndQueryStringParametersAndBodyParameters() { // when mockServerClient .when( request() .withMethod("POST") .withPath(calculatePath("some_pathRequest")) .withQueryStringParameters( param("queryStringParameterOneName", "queryStringParameterOneValueOne", "queryStringParameterOneValueTwo"), param("queryStringParameterTwoName", "queryStringParameterTwoValue") ) .withBody(params(param("bodyParameterName", "bodyParameterValue"))) ) .respond( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body") ); // then // - in http - url query string assertEquals( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body"), makeRequest( request() .withMethod("POST") .withPath(calculatePath("some_pathRequest")) .withQueryStringParameters( param("queryStringParameterOneName", "queryStringParameterOneValueOne", "queryStringParameterOneValueTwo"), param("queryStringParameterTwoName", "queryStringParameterTwoValue") ) .withBody(params(param("bodyParameterName", "bodyParameterValue"))), headersToIgnore) ); // - in https - query string parameter objects assertEquals( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body"), makeRequest( request() .withSecure(true) .withMethod("POST") .withPath(calculatePath("some_pathRequest")) .withQueryStringParameters( param("queryStringParameterOneName", "queryStringParameterOneValueOne", "queryStringParameterOneValueTwo"), param("queryStringParameterTwoName", "queryStringParameterTwoValue") ) .withBody(params(param("bodyParameterName", "bodyParameterValue"))), headersToIgnore) ); } @Test public void shouldReturnResponseByMatchingPathAndMethodAndQueryStringParametersAndBody() { // when mockServerClient .when( request() .withMethod("POST") .withPath(calculatePath("some_pathRequest")) .withQueryStringParameters( param("queryStringParameterOneName", "queryStringParameterOneValueOne", "queryStringParameterOneValueTwo"), param("queryStringParameterTwoName", "queryStringParameterTwoValue") ) .withBody("some_bodyRequest") ) .respond( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body_response") .withHeaders(header("headerNameResponse", "headerValueResponse")) .withCookies(cookie("cookieNameResponse", "cookieValueResponse")) ); // then // - in http - url query string assertEquals( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body_response") .withCookies(cookie("cookieNameResponse", "cookieValueResponse")) .withHeaders( header("headerNameResponse", "headerValueResponse"), header("Set-Cookie", "cookieNameResponse=cookieValueResponse") ), makeRequest( request() .withMethod("POST") .withPath(calculatePath("some_pathRequest")) .withQueryStringParameters( param("queryStringParameterOneName", "queryStringParameterOneValueOne", "queryStringParameterOneValueTwo"), param("queryStringParameterTwoName", "queryStringParameterTwoValue") ) .withBody("some_bodyRequest") .withHeaders(header("headerNameRequest", "headerValueRequest")) .withCookies(cookie("cookieNameRequest", "cookieValueRequest")), headersToIgnore) ); // - in http - query string parameter objects assertEquals( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body_response") .withCookies(cookie("cookieNameResponse", "cookieValueResponse")) .withHeaders( header("headerNameResponse", "headerValueResponse"), header("Set-Cookie", "cookieNameResponse=cookieValueResponse") ), makeRequest( request() .withMethod("POST") .withPath(calculatePath("some_pathRequest")) .withQueryStringParameters( param("queryStringParameterOneName", "queryStringParameterOneValueOne", "queryStringParameterOneValueTwo"), param("queryStringParameterTwoName", "queryStringParameterTwoValue") ) .withBody("some_bodyRequest") .withHeaders(header("headerNameRequest", "headerValueRequest")) .withCookies(cookie("cookieNameRequest", "cookieValueRequest")), headersToIgnore) ); // - in https - url string and query string parameter objects assertEquals( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body_response") .withCookies(cookie("cookieNameResponse", "cookieValueResponse")) .withHeaders( header("headerNameResponse", "headerValueResponse"), header("Set-Cookie", "cookieNameResponse=cookieValueResponse") ), makeRequest( request() .withMethod("POST") .withPath(calculatePath("some_pathRequest")) .withQueryStringParameters( param("queryStringParameterOneName", "queryStringParameterOneValueOne", "queryStringParameterOneValueTwo"), param("queryStringParameterTwoName", "queryStringParameterTwoValue") ) .withBody("some_bodyRequest") .withHeaders(header("headerNameRequest", "headerValueRequest")) .withCookies(cookie("cookieNameRequest", "cookieValueRequest")), headersToIgnore) ); } @Test public void shouldReturnResponseByMatchingPathAndMethodAndBodyParameters() { // when mockServerClient .when( request() .withMethod("POST") .withPath(calculatePath("some_pathRequest")) .withBody(params( param("bodyParameterOneName", "Parameter One Value One", "Parameter One Value Two"), param("bodyParameterTwoName", "Parameter Two") )) ) .respond( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body_response") .withHeaders(header("headerNameResponse", "headerValueResponse")) .withCookies(cookie("cookieNameResponse", "cookieValueResponse")) ); // then // - in http - body string assertEquals( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body_response") .withCookies(cookie("cookieNameResponse", "cookieValueResponse")) .withHeaders( header("headerNameResponse", "headerValueResponse"), header("Set-Cookie", "cookieNameResponse=cookieValueResponse") ), makeRequest( request() .withMethod("POST") .withPath(calculatePath("some_pathRequest")) .withBody(new StringBody("bodyParameterOneName=Parameter+One+Value+One" + "&bodyParameterOneName=Parameter+One+Value+Two" + "&bodyParameterTwoName=Parameter+Two")) .withHeaders(header("headerNameRequest", "headerValueRequest")) .withCookies(cookie("cookieNameRequest", "cookieValueRequest")), headersToIgnore) ); // - in http - body parameter objects assertEquals( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body_response") .withCookies(cookie("cookieNameResponse", "cookieValueResponse")) .withHeaders( header("headerNameResponse", "headerValueResponse"), header("Set-Cookie", "cookieNameResponse=cookieValueResponse") ), makeRequest( request() .withMethod("POST") .withPath(calculatePath("some_pathRequest")) .withBody(params( param("bodyParameterOneName", "Parameter One Value One", "Parameter One Value Two"), param("bodyParameterTwoName", "Parameter Two") )) .withHeaders(header("headerNameRequest", "headerValueRequest")) .withCookies(cookie("cookieNameRequest", "cookieValueRequest")), headersToIgnore) ); // - in https - url string and query string parameter objects assertEquals( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body_response") .withCookies(cookie("cookieNameResponse", "cookieValueResponse")) .withHeaders( header("headerNameResponse", "headerValueResponse"), header("Set-Cookie", "cookieNameResponse=cookieValueResponse") ), makeRequest( request() .withMethod("POST") .withPath(calculatePath("some_pathRequest")) .withBody(params( param("bodyParameterOneName", "Parameter One Value One", "Parameter One Value Two"), param("bodyParameterTwoName", "Parameter Two") )) .withHeaders(header("headerNameRequest", "headerValueRequest")) .withCookies(cookie("cookieNameRequest", "cookieValueRequest")), headersToIgnore) ); } @Test public void shouldReturnResponseByMatchingPathAndMethodAndParametersAndHeadersAndCookies() { // when mockServerClient .when( request() .withMethod("PUT") .withPath(calculatePath("some_pathRequest")) .withBody(new StringBody("bodyParameterOneName=Parameter+One+Value+One" + "&bodyParameterOneName=Parameter+One+Value+Two" + "&bodyParameterTwoName=Parameter+Two")) .withHeaders(header("headerNameRequest", "headerValueRequest")) .withCookies(cookie("cookieNameRequest", "cookieValueRequest")) ) .respond( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body_response") .withHeaders(header("headerNameResponse", "headerValueResponse")) .withCookies(cookie("cookieNameResponse", "cookieValueResponse")) ); // then // - in http - body string assertEquals( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body_response") .withCookies(cookie("cookieNameResponse", "cookieValueResponse")) .withHeaders( header("headerNameResponse", "headerValueResponse"), header("Set-Cookie", "cookieNameResponse=cookieValueResponse") ), makeRequest( request() .withMethod("PUT") .withPath(calculatePath("some_pathRequest")) .withBody(new StringBody("bodyParameterOneName=Parameter+One+Value+One" + "&bodyParameterOneName=Parameter+One+Value+Two" + "&bodyParameterTwoName=Parameter+Two")) .withHeaders( header("headerNameRequest", "headerValueRequest"), header("Cookie", "cookieNameRequest=cookieValueRequest") ), headersToIgnore) ); // - in http - body parameter objects assertEquals( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body_response") .withCookies(cookie("cookieNameResponse", "cookieValueResponse")) .withHeaders( header("headerNameResponse", "headerValueResponse"), header("Set-Cookie", "cookieNameResponse=cookieValueResponse") ), makeRequest( request() .withMethod("PUT") .withPath(calculatePath("some_pathRequest")) .withBody(params( param("bodyParameterOneName", "Parameter One Value One", "Parameter One Value Two"), param("bodyParameterTwoName", "Parameter Two") )) .withHeaders(header("headerNameRequest", "headerValueRequest")) .withCookies(cookie("cookieNameRequest", "cookieValueRequest")), headersToIgnore) ); } @Test public void shouldReturnResponseByNotMatchingBodyParameterWithNotOperatorForNameAndValue() { // when mockServerClient .when( request() .withMethod("POST") .withPath(calculatePath("some_pathRequest")) .withBody(params( param(not("bodyParameterOneName"), not("Parameter One Value One"), not("Parameter One Value Two")), param("bodyParameterTwoName", "Parameter Two") )) ) .respond( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body_response") ); // then // wrong query string parameter name assertEquals( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body_response"), makeRequest( request() .withMethod("POST") .withPath(calculatePath("some_pathRequest")) .withBody(params( param("OTHERBodyParameterOneName", "Parameter One Value One", "Parameter One Value Two"), param("bodyParameterTwoName", "Parameter Two") )) .withHeaders(header("headerNameRequest", "headerValueRequest")) .withCookies(cookie("cookieNameRequest", "cookieValueRequest")), headersToIgnore) ); // wrong query string parameter name assertEquals( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body_response"), makeRequest( request() .withMethod("POST") .withPath(calculatePath("some_pathRequest")) .withBody(new StringBody("OTHERBodyParameterOneName=Parameter+One+Value+One" + "&OTHERBodyParameterOneName=Parameter+One+Value+Two" + "&bodyParameterTwoName=Parameter+Two")) .withHeaders(header("headerNameRequest", "headerValueRequest")) .withCookies(cookie("cookieNameRequest", "cookieValueRequest")), headersToIgnore) ); // wrong query string parameter value assertEquals( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body_response"), makeRequest( request() .withMethod("POST") .withPath(calculatePath("some_pathRequest")) .withBody(params( param("bodyParameterOneName", "OTHER Parameter One Value One", "OTHER Parameter One Value Two"), param("bodyParameterTwoName", "Parameter Two") )) .withHeaders(header("headerNameRequest", "headerValueRequest")) .withCookies(cookie("cookieNameRequest", "cookieValueRequest")), headersToIgnore) ); // wrong query string parameter value assertEquals( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body_response"), makeRequest( request() .withMethod("POST") .withPath(calculatePath("some_pathRequest")) .withBody(new StringBody("bodyParameterOneName=OTHER Parameter+One+Value+One" + "&bodyParameterOneName=OTHER Parameter+One+Value+Two" + "&bodyParameterTwoName=Parameter+Two")) .withHeaders(header("headerNameRequest", "headerValueRequest")) .withCookies(cookie("cookieNameRequest", "cookieValueRequest")), headersToIgnore) ); } @Test public void shouldReturnResponseByNotMatchingBodyParameterWithNotOperatorForName() { // when mockServerClient .when( request() .withMethod("POST") .withPath(calculatePath("some_pathRequest")) .withBody(params( param(not("bodyParameterOneName"), string("Parameter One Value One"), string("Parameter One Value Two")), param("bodyParameterTwoName", "Parameter Two") )) ) .respond( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body_response") ); // then // wrong query string parameter name assertEquals( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body_response"), makeRequest( request() .withMethod("POST") .withPath(calculatePath("some_pathRequest")) .withBody(params( param("OTHERBodyParameterOneName", "Parameter One Value One", "Parameter One Value Two"), param("bodyParameterTwoName", "Parameter Two") )) .withHeaders(header("headerNameRequest", "headerValueRequest")) .withCookies(cookie("cookieNameRequest", "cookieValueRequest")), headersToIgnore) ); // wrong query string parameter name assertEquals( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body_response"), makeRequest( request() .withMethod("POST") .withPath(calculatePath("some_pathRequest")) .withBody(new StringBody("OTHERBodyParameterOneName=Parameter+One+Value+One" + "&OTHERBodyParameterOneName=Parameter+One+Value+Two" + "&bodyParameterTwoName=Parameter+Two")) .withHeaders(header("headerNameRequest", "headerValueRequest")) .withCookies(cookie("cookieNameRequest", "cookieValueRequest")), headersToIgnore) ); } @Test public void shouldReturnResponseByNotMatchingBodyParameterWithNotOperatorForValue() { // when mockServerClient .when( request() .withMethod("POST") .withPath(calculatePath("some_pathRequest")) .withBody(params( param(string("bodyParameterOneName"), not("Parameter One Value One"), not("Parameter One Value Two")), param("bodyParameterTwoName", "Parameter Two") )) ) .respond( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body_response") ); // then // wrong query string parameter value assertEquals( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body_response"), makeRequest( request() .withMethod("POST") .withPath(calculatePath("some_pathRequest")) .withBody(params( param("bodyParameterOneName", "OTHER Parameter One Value One", "OTHER Parameter One Value Two"), param("bodyParameterTwoName", "Parameter Two") )) .withHeaders(header("headerNameRequest", "headerValueRequest")) .withCookies(cookie("cookieNameRequest", "cookieValueRequest")), headersToIgnore) ); // wrong query string parameter value assertEquals( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body_response"), makeRequest( request() .withMethod("POST") .withPath(calculatePath("some_pathRequest")) .withBody(new StringBody("bodyParameterOneName=OTHER Parameter+One+Value+One" + "&bodyParameterOneName=OTHER Parameter+One+Value+Two" + "&bodyParameterTwoName=Parameter+Two")) .withHeaders(header("headerNameRequest", "headerValueRequest")) .withCookies(cookie("cookieNameRequest", "cookieValueRequest")), headersToIgnore) ); } @Test public void shouldReturnResponseByNotMatchingQueryStringParameterWithNotOperatorForNameAndValue() { // when mockServerClient .when( request() .withMethod("POST") .withPath(calculatePath("some_pathRequest")) .withQueryStringParameters( param(not("queryStringParameterOneName"), not("Parameter One Value One"), not("Parameter One Value Two")), param("queryStringParameterTwoName", "Parameter Two") ) ) .respond( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body_response") ); // then // wrong query string parameter name assertEquals( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body_response"), makeRequest( request() .withMethod("POST") .withPath(calculatePath("some_pathRequest")) .withQueryStringParameters( param("OTHERQueryStringParameterOneName", "Parameter One Value One", "Parameter One Value Two"), param("queryStringParameterTwoName", "Parameter Two") ), headersToIgnore) ); // wrong query string parameter value assertEquals( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body_response"), makeRequest( request() .withMethod("POST") .withPath(calculatePath("some_pathRequest")) .withQueryStringParameters( param("queryStringParameterOneName", "OTHER Parameter One Value One", "OTHER Parameter One Value Two"), param("queryStringParameterTwoName", "Parameter Two") ), headersToIgnore) ); } @Test public void shouldReturnResponseByNotMatchingQueryStringParameterWithNotOperatorForName() { // when mockServerClient .when( request() .withMethod("POST") .withPath(calculatePath("some_pathRequest")) .withQueryStringParameters( param(not("queryStringParameterOneName"), string("Parameter One Value One"), string("Parameter One Value Two")), param("queryStringParameterTwoName", "Parameter Two") ) ) .respond( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body_response") ); // then // wrong query string parameter name assertEquals( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body_response"), makeRequest( request() .withMethod("POST") .withPath(calculatePath("some_pathRequest")) .withQueryStringParameters( param("OTHERQueryStringParameterOneName", "Parameter One Value One", "Parameter One Value Two"), param("queryStringParameterTwoName", "Parameter Two") ), headersToIgnore) ); } @Test public void shouldReturnResponseByNotMatchingQueryStringParameterWithNotOperatorForValue() { // when mockServerClient .when( request() .withMethod("POST") .withPath(calculatePath("some_pathRequest")) .withQueryStringParameters( param(string("queryStringParameterOneName"), not("Parameter One Value One"), not("Parameter One Value Two")), param("queryStringParameterTwoName", "Parameter Two") ) ) .respond( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body_response") ); // then // wrong query string parameter value assertEquals( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body_response"), makeRequest( request() .withMethod("POST") .withPath(calculatePath("some_pathRequest")) .withQueryStringParameters( param("queryStringParameterOneName", "OTHER Parameter One Value One", "OTHER Parameter One Value Two"), param("queryStringParameterTwoName", "Parameter Two") ), headersToIgnore) ); } @Test public void shouldReturnResponseByNotMatchingCookieWithNotOperatorForNameAndValue() { // when mockServerClient .when( request() .withMethod("GET") .withPath(calculatePath("some_pathRequest")) .withCookies( cookie(not("requestCookieNameOne"), not("requestCookieValueOne")), cookie("requestCookieNameTwo", "requestCookieValueTwo") ) ) .respond( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body_response") ); // then // wrong query string cookie name assertEquals( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body_response"), makeRequest( request() .withMethod("GET") .withPath(calculatePath("some_pathRequest")) .withCookies( cookie("OTHERrequestCookieNameOne", "requestCookieValueOne"), cookie("requestCookieNameTwo", "requestCookieValueTwo") ), headersToIgnore) ); // wrong query string cookie value assertEquals( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body_response"), makeRequest( request() .withMethod("GET") .withPath(calculatePath("some_pathRequest")) .withCookies( cookie("requestCookieNameOne", "OTHERrequestCookieValueOne"), cookie("requestCookieNameTwo", "requestCookieValueTwo") ), headersToIgnore) ); } @Test public void shouldReturnResponseByNotMatchingCookieWithNotOperatorForName() { // when mockServerClient .when( request() .withMethod("GET") .withPath(calculatePath("some_pathRequest")) .withCookies( cookie(not("requestCookieNameOne"), string("requestCookieValueOne")), cookie("requestCookieNameTwo", "requestCookieValueTwo") ) ) .respond( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body_response") ); // then // wrong query string cookie name assertEquals( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body_response"), makeRequest( request() .withMethod("GET") .withPath(calculatePath("some_pathRequest")) .withCookies( cookie("OTHERrequestCookieNameOne", "requestCookieValueOne"), cookie("requestCookieNameTwo", "requestCookieValueTwo") ), headersToIgnore) ); } @Test public void shouldReturnResponseByNotMatchingCookieWithNotOperatorForValue() { // when mockServerClient .when( request() .withMethod("GET") .withPath(calculatePath("some_pathRequest")) .withCookies( cookie(string("requestCookieNameOne"), not("requestCookieValueOne")), cookie("requestCookieNameTwo", "requestCookieValueTwo") ) ) .respond( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body_response") ); // then // wrong query string cookie value assertEquals( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body_response"), makeRequest( request() .withMethod("GET") .withPath(calculatePath("some_pathRequest")) .withCookies( cookie("requestCookieNameOne", "OTHERrequestCookieValueOne"), cookie("requestCookieNameTwo", "requestCookieValueTwo") ), headersToIgnore) ); } @Test public void shouldReturnResponseByNotMatchingHeaderWithNotOperatorForNameAndValue() { // when mockServerClient .when( request() .withMethod("GET") .withPath(calculatePath("some_pathRequest")) .withHeaders( header(not("requestHeaderNameOne"), not("requestHeaderValueOne")), header("requestHeaderNameTwo", "requestHeaderValueTwo") ) ) .respond( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body_response") ); // then // wrong query string header name assertEquals( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body_response"), makeRequest( request() .withMethod("GET") .withPath(calculatePath("some_pathRequest")) .withHeaders( header("OTHERrequestHeaderNameOne", "requestHeaderValueOne"), header("requestHeaderNameTwo", "requestHeaderValueTwo") ), headersToIgnore) ); // wrong query string header value assertEquals( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body_response"), makeRequest( request() .withMethod("GET") .withPath(calculatePath("some_pathRequest")) .withHeaders( header("requestHeaderNameOne", "OTHERrequestHeaderValueOne"), header("requestHeaderNameTwo", "requestHeaderValueTwo") ), headersToIgnore) ); } @Test public void shouldReturnResponseByNotMatchingHeaderWithNotOperatorForName() { // when mockServerClient .when( request() .withMethod("GET") .withPath(calculatePath("some_pathRequest")) .withHeaders( header(not("requestHeaderNameOne"), string("requestHeaderValueOne")), header("requestHeaderNameTwo", "requestHeaderValueTwo") ) ) .respond( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body_response") ); // then // wrong query string header name assertEquals( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body_response"), makeRequest( request() .withMethod("GET") .withPath(calculatePath("some_pathRequest")) .withHeaders( header("OTHERrequestHeaderNameOne", "requestHeaderValueOne"), header("requestHeaderNameTwo", "requestHeaderValueTwo") ), headersToIgnore) ); } @Test public void shouldReturnResponseByNotMatchingHeaderWithNotOperatorForValue() { // when mockServerClient .when( request() .withMethod("GET") .withPath(calculatePath("some_pathRequest")) .withHeaders( header(string("requestHeaderNameOne"), not("requestHeaderValueOne")), header("requestHeaderNameTwo", "requestHeaderValueTwo") ) ) .respond( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body_response") ); // then // wrong query string header value assertEquals( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body_response"), makeRequest( request() .withMethod("GET") .withPath(calculatePath("some_pathRequest")) .withHeaders( header("requestHeaderNameOne", "OTHERrequestHeaderValueOne"), header("requestHeaderNameTwo", "requestHeaderValueTwo") ), headersToIgnore) ); } @Test public void shouldNotReturnResponseForWhenTimeToLiveExpired() { // when mockServerClient .when( request().withPath(calculatePath("some_path")), exactly(2), TimeToLive.exactly(TimeUnit.SECONDS, 5L) ) .respond( response().withBody("some_body").withDelay(TimeUnit.SECONDS, 5L) ); // then assertEquals( response() .withStatusCode(HttpStatusCode.OK_200.code()) .withBody("some_body"), makeRequest( request() .withPath(calculatePath("some_path")), headersToIgnore) ); // - in http assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()), makeRequest( request() .withPath(calculatePath("some_path")), headersToIgnore) ); // - in https assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()), makeRequest( request() .withSecure(true) .withPath(calculatePath("some_path")), headersToIgnore) ); } @Test public void shouldNotReturnResponseForNonMatchingBody() { // when mockServerClient .when( request() .withMethod("GET") .withPath(calculatePath("some_path")) .withQueryStringParameters( param("queryStringParameterOneName", "queryStringParameterOneValue"), param("queryStringParameterTwoName", "queryStringParameterTwoValue") ) .withBody(exact("some_body")) .withHeaders(header("headerName", "headerValue")) .withCookies(cookie("cookieName", "cookieValue")) ) .respond( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body") .withHeaders(header("headerName", "headerValue")) .withCookies(cookie("cookieName", "cookieValue")) ); // then // - in http assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()), makeRequest( request() .withMethod("GET") .withPath(calculatePath("some_path")) .withQueryStringParameters( param("queryStringParameterOneName", "queryStringParameterOneValue"), param("queryStringParameterTwoName", "queryStringParameterTwoValue") ) .withBody(exact("some_other_body")) .withHeaders(header("headerName", "headerValue")) .withCookies(cookie("cookieName", "cookieValue")), headersToIgnore) ); // - in https assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()), makeRequest( request() .withMethod("GET") .withSecure(true) .withPath(calculatePath("some_path")) .withQueryStringParameters( param("queryStringParameterOneName", "queryStringParameterOneValue"), param("queryStringParameterTwoName", "queryStringParameterTwoValue") ) .withBody(exact("some_other_body")) .withHeaders(header("headerName", "headerValue")) .withCookies(cookie("cookieName", "cookieValue")), headersToIgnore) ); } @Test public void shouldNotReturnResponseForMatchingBodyWithNotOperator() { // when mockServerClient .when( request() .withBody(Not.not(json("{" + System.getProperty("line.separator") + " \"id\": 1," + System.getProperty("line.separator") + " \"name\": \"A green door\"," + System.getProperty("line.separator") + " \"price\": 12.50," + System.getProperty("line.separator") + " \"tags\": [\"home\", \"green\"]" + System.getProperty("line.separator") + "}"))), exactly(2) ) .respond( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body") ); // then // - in http assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()), makeRequest( request() .withPath(calculatePath("some_path")) .withMethod("POST") .withBody("{" + System.getProperty("line.separator") + " \"id\": 1," + System.getProperty("line.separator") + " \"extra_ignored_field\": \"some value\"," + System.getProperty("line.separator") + " \"name\": \"A green door\"," + System.getProperty("line.separator") + " \"price\": 12.50," + System.getProperty("line.separator") + " \"tags\": [\"home\", \"green\"]" + System.getProperty("line.separator") + "}"), headersToIgnore) ); // - in https assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()), makeRequest( request() .withSecure(true) .withPath(calculatePath("some_path")) .withMethod("POST") .withBody("{" + System.getProperty("line.separator") + " \"id\": 1," + System.getProperty("line.separator") + " \"extra_ignored_array\": [\"one\", \"two\"]," + System.getProperty("line.separator") + " \"name\": \"A green door\"," + System.getProperty("line.separator") + " \"price\": 12.50," + System.getProperty("line.separator") + " \"tags\": [\"home\", \"green\"]" + System.getProperty("line.separator") + "}"), headersToIgnore) ); } @Test public void shouldNotReturnResponseForNonMatchingXPathBody() { // when mockServerClient.when(request().withBody(new XPathBody("/bookstore/book[price>35]/price")), exactly(2)).respond(response().withBody("some_body")); // then // - in http assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()), makeRequest( request() .withSecure(true) .withPath(calculatePath("some_path")) .withMethod("POST") .withBody(new StringBody("" + "<?xml version=\"1.0\" encoding=\"ISO-8859-1\"?>" + System.getProperty("line.separator") + "<bookstore>" + System.getProperty("line.separator") + " <book category=\"COOKING\">" + System.getProperty("line.separator") + " <title lang=\"en\">Everyday Italian</title>" + System.getProperty("line.separator") + " <author>Giada De Laurentiis</author>" + System.getProperty("line.separator") + " <year>2005</year>" + System.getProperty("line.separator") + " <price>30.00</price>" + System.getProperty("line.separator") + " </book>" + System.getProperty("line.separator") + " <book category=\"CHILDREN\">" + System.getProperty("line.separator") + " <title lang=\"en\">Harry Potter</title>" + System.getProperty("line.separator") + " <author>J K. Rowling</author>" + System.getProperty("line.separator") + " <year>2005</year>" + System.getProperty("line.separator") + " <price>29.99</price>" + System.getProperty("line.separator") + " </book>" + System.getProperty("line.separator") + " <book category=\"WEB\">" + System.getProperty("line.separator") + " <title lang=\"en\">Learning XML</title>" + System.getProperty("line.separator") + " <author>Erik T. Ray</author>" + System.getProperty("line.separator") + " <year>2003</year>" + System.getProperty("line.separator") + " <price>31.95</price>" + System.getProperty("line.separator") + " </book>" + System.getProperty("line.separator") + "</bookstore>")), headersToIgnore) ); // - in https assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()), makeRequest( request() .withSecure(true) .withPath(calculatePath("some_path")) .withMethod("POST") .withBody(new StringBody("" + "<?xml version=\"1.0\" encoding=\"ISO-8859-1\"?>" + System.getProperty("line.separator") + "<bookstore>" + System.getProperty("line.separator") + " <book category=\"COOKING\">" + System.getProperty("line.separator") + " <title lang=\"en\">Everyday Italian</title>" + System.getProperty("line.separator") + " <author>Giada De Laurentiis</author>" + System.getProperty("line.separator") + " <year>2005</year>" + System.getProperty("line.separator") + " <price>30.00</price>" + System.getProperty("line.separator") + " </book>" + System.getProperty("line.separator") + " <book category=\"CHILDREN\">" + System.getProperty("line.separator") + " <title lang=\"en\">Harry Potter</title>" + System.getProperty("line.separator") + " <author>J K. Rowling</author>" + System.getProperty("line.separator") + " <year>2005</year>" + System.getProperty("line.separator") + " <price>29.99</price>" + System.getProperty("line.separator") + " </book>" + System.getProperty("line.separator") + " <book category=\"WEB\">" + System.getProperty("line.separator") + " <title lang=\"en\">Learning XML</title>" + System.getProperty("line.separator") + " <author>Erik T. Ray</author>" + System.getProperty("line.separator") + " <year>2003</year>" + System.getProperty("line.separator") + " <price>31.95</price>" + System.getProperty("line.separator") + " </book>" + System.getProperty("line.separator") + "</bookstore>")), headersToIgnore) ); } @Test public void shouldNotReturnResponseForNonMatchingXmlBody() { // when mockServerClient.when(request().withBody(xml("" + "<?xml version=\"1.0\" encoding=\"ISO-8859-1\"?>" + System.getProperty("line.separator") + "<bookstore>" + System.getProperty("line.separator") + " <book category=\"COOKING\" nationality=\"ITALIAN\">" + System.getProperty("line.separator") + " <title lang=\"en\">Everyday Italian</title>" + System.getProperty("line.separator") + " <author>Giada De Laurentiis</author>" + System.getProperty("line.separator") + " <year>2005</year>" + System.getProperty("line.separator") + " <price>30.00</price>" + System.getProperty("line.separator") + " </book>" + System.getProperty("line.separator") + "</bookstore>")), exactly(2)).respond(response().withBody("some_body")); // then // - in http assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()), makeRequest( request() .withSecure(true) .withPath(calculatePath("some_path")) .withMethod("POST") .withBody(new StringBody("" + "<?xml version=\"1.0\" encoding=\"ISO-8859-1\"?>" + System.getProperty("line.separator") + "<bookstore>" + System.getProperty("line.separator") + " <book category=\"COOKING\">" + System.getProperty("line.separator") + " <title lang=\"en\">Everyday Italian</title>" + System.getProperty("line.separator") + " <author>Giada De Laurentiis</author>" + System.getProperty("line.separator") + " <year>2005</year>" + System.getProperty("line.separator") + " <price>30.00</price>" + System.getProperty("line.separator") + " </book>" + System.getProperty("line.separator") + "</bookstore>")), headersToIgnore) ); // - in https assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()), makeRequest( request() .withSecure(true) .withPath(calculatePath("some_path")) .withMethod("POST") .withBody(new StringBody("" + "<?xml version=\"1.0\" encoding=\"ISO-8859-1\"?>" + System.getProperty("line.separator") + "<bookstore>" + System.getProperty("line.separator") + " <book category=\"COOKING\">" + System.getProperty("line.separator") + " <title lang=\"en\">Everyday Italian</title>" + System.getProperty("line.separator") + " <author>Giada De Laurentiis</author>" + System.getProperty("line.separator") + " <year>2005</year>" + System.getProperty("line.separator") + " <price>30.00</price>" + System.getProperty("line.separator") + " </book>" + System.getProperty("line.separator") + "</bookstore>")), headersToIgnore) ); } @Test public void shouldNotReturnResponseForNonMatchingJsonBody() { // when mockServerClient.when(request().withBody(json("{" + System.getProperty("line.separator") + " \"id\": 1," + System.getProperty("line.separator") + " \"name\": \"A green door\"," + System.getProperty("line.separator") + " \"price\": 12.50," + System.getProperty("line.separator") + " \"tags\": [\"home\", \"green\"]" + System.getProperty("line.separator") + "}")), exactly(2)).respond(response().withBody("some_body")); // then // - in http assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()), makeRequest( request() .withPath(calculatePath("some_path")) .withMethod("POST") .withBody("{" + System.getProperty("line.separator") + " \"id\": 1," + System.getProperty("line.separator") + " \"name\": \"---- XXXX WRONG VALUE XXXX ----\"," + System.getProperty("line.separator") + " \"price\": 12.50," + System.getProperty("line.separator") + " \"tags\": [\"home\", \"green\"]" + System.getProperty("line.separator") + "}"), headersToIgnore) ); // - in https assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()), makeRequest( request() .withSecure(true) .withPath(calculatePath("some_path")) .withMethod("POST") .withBody("{" + System.getProperty("line.separator") + " \"id\": 1," + System.getProperty("line.separator") + " \"name\": \"---- XXXX WRONG VALUE XXXX ----\"," + System.getProperty("line.separator") + " \"price\": 12.50," + System.getProperty("line.separator") + " \"tags\": [\"home\", \"green\"]" + System.getProperty("line.separator") + "}"), headersToIgnore) ); } @Test public void shouldNotReturnResponseForNonMatchingJsonBodyWithMatchType() { // when mockServerClient .when( request() .withBody(json("{" + System.getProperty("line.separator") + " \"id\": 1," + System.getProperty("line.separator") + " \"name\": \"A green door\"," + System.getProperty("line.separator") + " \"price\": 12.50," + System.getProperty("line.separator") + " \"tags\": [\"home\", \"green\"]" + System.getProperty("line.separator") + "}", MatchType.STRICT)), exactly(2)) .respond( response() .withBody("some_body") ); // then // - in http assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()), makeRequest( request() .withPath(calculatePath("some_path")) .withMethod("POST") .withBody("{" + System.getProperty("line.separator") + " \"id\": 1," + System.getProperty("line.separator") + " \"extra field\": \"some value\"," + System.getProperty("line.separator") + " \"name\": \"A green door\"," + System.getProperty("line.separator") + " \"price\": 12.50," + System.getProperty("line.separator") + " \"tags\": [\"home\", \"green\"]" + System.getProperty("line.separator") + "}"), headersToIgnore) ); // - in https assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()), makeRequest( request() .withSecure(true) .withPath(calculatePath("some_path")) .withMethod("POST") .withBody("{" + System.getProperty("line.separator") + " \"id\": 1," + System.getProperty("line.separator") + " \"extra field\": \"some value\"," + System.getProperty("line.separator") + " \"name\": \"A green door\"," + System.getProperty("line.separator") + " \"price\": 12.50," + System.getProperty("line.separator") + " \"tags\": [\"home\", \"green\"]" + System.getProperty("line.separator") + "}"), headersToIgnore) ); } @Test public void shouldNotReturnResponseForNonMatchingJsonSchema() { // when mockServerClient.when(request().withBody(jsonSchema("{" + System.getProperty("line.separator") + " \"$schema\": \"http://json-schema.org/draft-04/schema#\"," + System.getProperty("line.separator") + " \"title\": \"Product\"," + System.getProperty("line.separator") + " \"description\": \"A product from Acme's catalog\"," + System.getProperty("line.separator") + " \"type\": \"object\"," + System.getProperty("line.separator") + " \"properties\": {" + System.getProperty("line.separator") + " \"id\": {" + System.getProperty("line.separator") + " \"description\": \"The unique identifier for a product\"," + System.getProperty("line.separator") + " \"type\": \"integer\"" + System.getProperty("line.separator") + " }," + System.getProperty("line.separator") + " \"name\": {" + System.getProperty("line.separator") + " \"description\": \"Name of the product\"," + System.getProperty("line.separator") + " \"type\": \"string\"" + System.getProperty("line.separator") + " }," + System.getProperty("line.separator") + " \"price\": {" + System.getProperty("line.separator") + " \"type\": \"number\"," + System.getProperty("line.separator") + " \"minimum\": 0," + System.getProperty("line.separator") + " \"exclusiveMinimum\": true" + System.getProperty("line.separator") + " }," + System.getProperty("line.separator") + " \"tags\": {" + System.getProperty("line.separator") + " \"type\": \"array\"," + System.getProperty("line.separator") + " \"items\": {" + System.getProperty("line.separator") + " \"type\": \"string\"" + System.getProperty("line.separator") + " }," + System.getProperty("line.separator") + " \"minItems\": 1," + System.getProperty("line.separator") + " \"uniqueItems\": true" + System.getProperty("line.separator") + " }" + System.getProperty("line.separator") + " }," + System.getProperty("line.separator") + " \"required\": [\"id\", \"name\", \"price\"]" + System.getProperty("line.separator") + "}")), exactly(2)).respond(response().withBody("some_body")); // then // - in http assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()), makeRequest( request() .withPath(calculatePath("some_path")) .withMethod("POST") .withBody("{" + System.getProperty("line.separator") + " \"id\": 1," + System.getProperty("line.separator") + " \"wrong field name\": \"A green door\"," + System.getProperty("line.separator") + " \"price\": 12.50," + System.getProperty("line.separator") + " \"tags\": [\"home\", \"green\"]" + System.getProperty("line.separator") + "}"), headersToIgnore) ); // - in https assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()), makeRequest( request() .withSecure(true) .withPath(calculatePath("some_path")) .withMethod("POST") .withBody("{" + System.getProperty("line.separator") + " \"id\": 1," + System.getProperty("line.separator") + " \"name\": \"A green door\"," + System.getProperty("line.separator") + " \"wrong field name\": 12.50," + System.getProperty("line.separator") + " \"tags\": [\"home\", \"green\"]" + System.getProperty("line.separator") + "}"), headersToIgnore) ); } @Test public void shouldNotReturnResponseForNonMatchingPath() { // when mockServerClient .when( request() .withMethod("GET") .withPath(calculatePath("some_path")) .withQueryStringParameters( param("queryStringParameterOneName", "queryStringParameterOneValue"), param("queryStringParameterTwoName", "queryStringParameterTwoValue") ) .withBody(exact("some_body")) .withHeaders(header("headerName", "headerValue")) .withCookies(cookie("cookieName", "cookieValue")) ) .respond( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body") .withHeaders(header("headerName", "headerValue")) .withCookies(cookie("cookieName", "cookieValue")) ); // then // - in http assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()), makeRequest( request() .withMethod("GET") .withPath(calculatePath("some_other_path")) .withQueryStringParameters( param("queryStringParameterOneName", "queryStringParameterOneValue"), param("queryStringParameterTwoName", "queryStringParameterTwoValue") ) .withBody(exact("some_body")) .withHeaders(header("headerName", "headerValue")) .withCookies(cookie("cookieName", "cookieValue")), headersToIgnore) ); // - in https assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()), makeRequest( request() .withMethod("GET") .withSecure(true) .withPath(calculatePath("some_other_path")) .withQueryStringParameters( param("queryStringParameterOneName", "queryStringParameterOneValue"), param("queryStringParameterTwoName", "queryStringParameterTwoValue") ) .withBody(exact("some_body")) .withHeaders(header("headerName", "headerValue")) .withCookies(cookie("cookieName", "cookieValue")), headersToIgnore) ); } @Test public void shouldNotReturnResponseForMatchingPathWithNotOperator() { // when mockServerClient .when( request() .withPath(not(calculatePath("some_path"))) ) .respond( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body_response") ); // then // - in http assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()), makeRequest( request() .withPath(calculatePath("some_path")), headersToIgnore) ); // - in https assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()), makeRequest( request() .withPath(calculatePath("some_path")), headersToIgnore) ); } @Test public void shouldNotReturnResponseForMatchingMethodWithNotOperator() { // when mockServerClient .when( request() .withMethod(not("GET")) ) .respond( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body_response") ); // then // - in http assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()), makeRequest( request() .withMethod("GET"), headersToIgnore) ); // - in https assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()), makeRequest( request() .withMethod("GET"), headersToIgnore) ); } @Test public void shouldNotReturnResponseForNonMatchingBodyParameterName() { // when mockServerClient .when( request() .withMethod("POST") .withPath(calculatePath("some_pathRequest")) .withBody(params( param("bodyParameterOneName", "Parameter One Value One", "Parameter One Value Two"), param("bodyParameterTwoName", "Parameter Two") )) ) .respond( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body_response") .withHeaders(header("headerNameResponse", "headerValueResponse")) .withCookies(cookie("cookieNameResponse", "cookieValueResponse")) ); // then // wrong query string parameter name assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()), makeRequest( request() .withMethod("POST") .withPath(calculatePath("some_pathRequest")) .withBody(params( param("OTHERBodyParameterOneName", "Parameter One Value One", "Parameter One Value Two"), param("bodyParameterTwoName", "Parameter Two") )) .withHeaders(header("headerNameRequest", "headerValueRequest")) .withCookies(cookie("cookieNameRequest", "cookieValueRequest")), headersToIgnore) ); // wrong query string parameter name assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()), makeRequest( request() .withMethod("POST") .withPath(calculatePath("some_pathRequest")) .withBody(new StringBody("OTHERBodyParameterOneName=Parameter+One+Value+One" + "&bodyParameterOneName=Parameter+One+Value+Two" + "&bodyParameterTwoName=Parameter+Two")) .withHeaders(header("headerNameRequest", "headerValueRequest")) .withCookies(cookie("cookieNameRequest", "cookieValueRequest")), headersToIgnore) ); } @Test public void shouldNotReturnResponseForMatchingBodyParameterWithNotOperator() { // when mockServerClient .when( request() .withMethod("POST") .withPath(calculatePath("some_pathRequest")) .withBody(params( param(not("bodyParameterOneName"), not("Parameter One Value One"), not("Parameter One Value Two")), param("bodyParameterTwoName", "Parameter Two") )) ) .respond( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body_response") ); // then // wrong query string parameter name assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()), makeRequest( request() .withMethod("POST") .withPath(calculatePath("some_pathRequest")) .withBody(params( param("bodyParameterOneName", "Parameter One Value One", "Parameter One Value Two"), param("bodyParameterTwoName", "Parameter Two") )) .withHeaders(header("headerNameRequest", "headerValueRequest")) .withCookies(cookie("cookieNameRequest", "cookieValueRequest")), headersToIgnore) ); // wrong query string parameter name assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()), makeRequest( request() .withMethod("POST") .withPath(calculatePath("some_pathRequest")) .withBody(new StringBody("bodyParameterOneName=Other Parameter+One+Value+One" + "&bodyParameterOneName=Parameter+One+Value+Two" + "&bodyParameterTwoName=Parameter+Two")) .withHeaders(header("headerNameRequest", "headerValueRequest")) .withCookies(cookie("cookieNameRequest", "cookieValueRequest")), headersToIgnore) ); } @Test public void shouldNotReturnResponseForNonMatchingBodyParameterValue() { // when mockServerClient .when( request() .withMethod("POST") .withPath(calculatePath("some_pathRequest")) .withBody(params( param("bodyParameterOneName", "Parameter One Value One", "Parameter One Value Two"), param("bodyParameterTwoName", "Parameter Two") )) ) .respond( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body_response") .withHeaders(header("headerNameResponse", "headerValueResponse")) .withCookies(cookie("cookieNameResponse", "cookieValueResponse")) ); // then // wrong body parameter value assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()), makeRequest( request() .withMethod("POST") .withPath(calculatePath("some_pathRequest")) .withBody(params( param("bodyParameterOneName", "Other Parameter One Value One", "Parameter One Value Two"), param("bodyParameterTwoName", "Parameter Two") )) .withHeaders(header("headerNameRequest", "headerValueRequest")) .withCookies(cookie("cookieNameRequest", "cookieValueRequest")), headersToIgnore) ); // wrong body parameter value assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()), makeRequest( request() .withMethod("POST") .withPath(calculatePath("some_pathRequest")) .withBody(new StringBody("bodyParameterOneName=Other Parameter+One+Value+One" + "&bodyParameterOneName=Parameter+One+Value+Two" + "&bodyParameterTwoName=Parameter+Two")) .withHeaders(header("headerNameRequest", "headerValueRequest")) .withCookies(cookie("cookieNameRequest", "cookieValueRequest")), headersToIgnore) ); } @Test public void shouldNotReturnResponseForNonMatchingQueryStringParameterName() { // when mockServerClient .when( request() .withMethod("POST") .withPath(calculatePath("some_pathRequest")) .withQueryStringParameters( param("queryStringParameterOneName", "queryStringParameterOneValueOne", "queryStringParameterOneValueTwo"), param("queryStringParameterTwoName", "queryStringParameterTwoValue") ) .withBody("some_bodyRequest") ) .respond( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body_response") .withHeaders(header("headerNameResponse", "headerValueResponse")) .withCookies(cookie("cookieNameResponse", "cookieValueResponse")) ); // then // wrong query string parameter name assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()), makeRequest( request() .withMethod("POST") .withPath(calculatePath("some_pathRequest")) .withQueryStringParameters( param("OTHERQueryStringParameterOneName", "queryStringParameterOneValueOne", "queryStringParameterOneValueTwo"), param("queryStringParameterTwoName", "queryStringParameterTwoValue") ) .withBody("some_bodyRequest") .withHeaders( header("headerNameRequest", "headerValueRequest") ) .withCookies(cookie("cookieNameRequest", "cookieValueRequest")), headersToIgnore) ); } @Test public void shouldNotReturnResponseForNonMatchingQueryStringParameterValue() { // when mockServerClient .when( request() .withMethod("POST") .withPath(calculatePath("some_pathRequest")) .withQueryStringParameters( param("queryStringParameterOneName", "queryStringParameterOneValueOne", "queryStringParameterOneValueTwo"), param("queryStringParameterTwoName", "queryStringParameterTwoValue") ) .withBody("some_bodyRequest") ) .respond( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body_response") .withHeaders(header("headerNameResponse", "headerValueResponse")) .withCookies(cookie("cookieNameResponse", "cookieValueResponse")) ); // then // wrong query string parameter value assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()), makeRequest( request() .withMethod("POST") .withPath(calculatePath("some_pathRequest")) .withQueryStringParameters( param("queryStringParameterOneName", "OTHERqueryStringParameterOneValueOne", "queryStringParameterOneValueTwo"), param("queryStringParameterTwoName", "queryStringParameterTwoValue") ) .withBody("some_bodyRequest") .withHeaders(header("headerNameRequest", "headerValueRequest")) .withCookies(cookie("cookieNameRequest", "cookieValueRequest")), headersToIgnore) ); } @Test public void shouldNotReturnResponseForMatchingQueryStringParameterWithNotOperator() { // when mockServerClient .when( request() .withMethod("POST") .withPath(calculatePath("some_pathRequest")) .withQueryStringParameters( param(not("queryStringParameterOneName"), not("Parameter One Value One"), not("Parameter One Value Two")), param("queryStringParameterTwoName", "Parameter Two") ) ) .respond( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body_response") ); // then // wrong query string parameter name assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()), makeRequest( request() .withMethod("POST") .withPath(calculatePath("some_pathRequest")) .withQueryStringParameters( param("queryStringParameterOneName", "Parameter One Value One", "Parameter One Value Two"), param("queryStringParameterTwoName", "Parameter Two") ), headersToIgnore) ); // wrong query string parameter name assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()), makeRequest( request() .withMethod("POST") .withPath(calculatePath("some_pathRequest")) .withQueryStringParameters( param("queryStringParameterOneName", "Parameter One Value One", "Parameter One Value Two"), param("queryStringParameterTwoName", "Parameter Two") ), headersToIgnore) ); } @Test public void shouldNotReturnResponseForNonMatchingCookieName() { // when mockServerClient .when( request() .withMethod("GET") .withPath(calculatePath("some_path")) .withQueryStringParameters( param("queryStringParameterOneName", "queryStringParameterOneValue"), param("queryStringParameterTwoName", "queryStringParameterTwoValue") ) .withBody(exact("some_body")) .withHeaders(header("headerName", "headerValue")) .withCookies(cookie("cookieName", "cookieValue")) ) .respond( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body") .withHeaders(header("headerName", "headerValue")) .withCookies(cookie("cookieName", "cookieValue")) ); // then // - in http assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()), makeRequest( request() .withMethod("GET") .withPath(calculatePath("some_path")) .withQueryStringParameters( param("queryStringParameterOneName", "queryStringParameterOneValue"), param("queryStringParameterTwoName", "queryStringParameterTwoValue") ) .withBody(exact("some_body")) .withHeaders(header("headerName", "headerValue")) .withCookies(cookie("cookieOtherName", "cookieValue")), headersToIgnore) ); // - in https assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()), makeRequest( request() .withMethod("GET") .withSecure(true) .withPath(calculatePath("some_path")) .withQueryStringParameters( param("queryStringParameterOneName", "queryStringParameterOneValue"), param("queryStringParameterTwoName", "queryStringParameterTwoValue") ) .withBody(exact("some_body")) .withHeaders(header("headerName", "headerValue")) .withCookies(cookie("cookieOtherName", "cookieValue")), headersToIgnore) ); } @Test public void shouldNotReturnResponseForNonMatchingCookieValue() { // when mockServerClient .when( request() .withMethod("GET") .withPath(calculatePath("some_path")) .withQueryStringParameters( param("queryStringParameterOneName", "queryStringParameterOneValue"), param("queryStringParameterTwoName", "queryStringParameterTwoValue") ) .withBody(exact("some_body")) .withHeaders(header("headerName", "headerValue")) .withCookies(cookie("cookieName", "cookieValue")) ) .respond( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body") .withHeaders(header("headerName", "headerValue")) .withCookies(cookie("cookieName", "cookieValue")) ); // then // - in http assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()), makeRequest( request() .withMethod("GET") .withPath(calculatePath("some_path")) .withQueryStringParameters( param("queryStringParameterOneName", "queryStringParameterOneValue"), param("queryStringParameterTwoName", "queryStringParameterTwoValue") ) .withBody(exact("some_body")) .withHeaders(header("headerName", "headerValue")) .withCookies(cookie("cookieName", "cookieOtherValue")), headersToIgnore) ); // - in https assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()), makeRequest( request() .withMethod("GET") .withSecure(true) .withPath(calculatePath("some_path")) .withQueryStringParameters( param("queryStringParameterOneName", "queryStringParameterOneValue"), param("queryStringParameterTwoName", "queryStringParameterTwoValue") ) .withBody(exact("some_body")) .withHeaders(header("headerName", "headerValue")) .withCookies(cookie("cookieName", "cookieOtherValue")), headersToIgnore) ); } @Test public void shouldNotReturnResponseForMatchingCookieWithNotOperator() { // when mockServerClient .when( request() .withMethod("GET") .withPath(calculatePath("some_pathRequest")) .withCookies( cookie(not("requestCookieNameOne"), not("requestCookieValueOne")), cookie("requestCookieNameTwo", "requestCookieValueTwo") ) ) .respond( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body_response") ); // then // wrong query string parameter name assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()), makeRequest( request() .withMethod("GET") .withPath(calculatePath("some_pathRequest")) .withCookies( cookie("requestCookieNameOne", "requestCookieValueOne"), cookie("requestCookieNameTwo", "requestCookieValueTwo") ), headersToIgnore) ); // wrong query string parameter name assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()), makeRequest( request() .withMethod("GET") .withPath(calculatePath("some_pathRequest")) .withCookies( cookie("requestCookieNameOne", "requestCookieValueOne"), cookie("requestCookieNameTwo", "requestCookieValueTwo") ), headersToIgnore) ); } @Test public void shouldNotReturnResponseForNonMatchingHeaderName() { // when mockServerClient .when( request() .withMethod("GET") .withPath(calculatePath("some_path")) .withQueryStringParameters( param("queryStringParameterOneName", "queryStringParameterOneValue"), param("queryStringParameterTwoName", "queryStringParameterTwoValue") ) .withBody(exact("some_body")) .withHeaders(header("headerName", "headerValue")) .withCookies(cookie("cookieName", "cookieValue")) ) .respond( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body") .withHeaders(header("headerName", "headerValue")) .withCookies(cookie("cookieName", "cookieValue")) ); // then // - in http assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()), makeRequest( request() .withMethod("GET") .withPath(calculatePath("some_path")) .withQueryStringParameters( param("queryStringParameterOneName", "queryStringParameterOneValue"), param("queryStringParameterTwoName", "queryStringParameterTwoValue") ) .withBody(exact("some_body")) .withHeaders(header("headerOtherName", "headerValue")) .withCookies(cookie("cookieName", "cookieValue")), headersToIgnore) ); // - in https assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()), makeRequest( request() .withMethod("GET") .withSecure(true) .withPath(calculatePath("some_path")) .withQueryStringParameters( param("queryStringParameterOneName", "queryStringParameterOneValue"), param("queryStringParameterTwoName", "queryStringParameterTwoValue") ) .withBody(exact("some_body")) .withHeaders(header("headerOtherName", "headerValue")) .withCookies(cookie("cookieName", "cookieValue")), headersToIgnore) ); } @Test public void shouldNotReturnResponseForNonMatchingHeaderValue() { // when mockServerClient .when( request() .withMethod("GET") .withPath(calculatePath("some_path")) .withQueryStringParameters( param("queryStringParameterOneName", "queryStringParameterOneValue"), param("queryStringParameterTwoName", "queryStringParameterTwoValue") ) .withBody(exact("some_body")) .withHeaders(header("headerName", "headerValue")) .withCookies(cookie("cookieName", "cookieValue")) ) .respond( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body") .withHeaders(header("headerName", "headerValue")) .withCookies(cookie("cookieName", "cookieValue")) ); // then // - in http assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()), makeRequest( request() .withMethod("GET") .withPath(calculatePath("some_path")) .withQueryStringParameters( param("queryStringParameterOneName", "queryStringParameterOneValue"), param("queryStringParameterTwoName", "queryStringParameterTwoValue") ) .withBody(exact("some_body")) .withHeaders(header("headerName", "headerOtherValue")) .withCookies(cookie("cookieName", "cookieValue")), headersToIgnore) ); // - in https assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()), makeRequest( request() .withMethod("GET") .withSecure(true) .withPath(calculatePath("some_path")) .withQueryStringParameters( param("queryStringParameterOneName", "queryStringParameterOneValue"), param("queryStringParameterTwoName", "queryStringParameterTwoValue") ) .withBody(exact("some_body")) .withHeaders(header("headerName", "headerOtherValue")) .withCookies(cookie("cookieName", "cookieValue")), headersToIgnore) ); } @Test public void shouldNotReturnResponseForMatchingHeaderWithNotOperator() { // when mockServerClient .when( request() .withMethod("GET") .withPath(calculatePath("some_pathRequest")) .withHeaders( header(not("requestHeaderNameOne"), not("requestHeaderValueOne")), header("requestHeaderNameTwo", "requestHeaderValueTwo") ) ) .respond( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body_response") ); // then // wrong query string parameter name assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()), makeRequest( request() .withMethod("GET") .withPath(calculatePath("some_pathRequest")) .withHeaders( header("requestHeaderNameOne", "requestHeaderValueOne"), header("requestHeaderNameTwo", "requestHeaderValueTwo") ), headersToIgnore) ); // wrong query string parameter name assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()), makeRequest( request() .withMethod("GET") .withPath(calculatePath("some_pathRequest")) .withHeaders( header("requestHeaderNameOne", "requestHeaderValueOne"), header("requestHeaderNameTwo", "requestHeaderValueTwo") ), headersToIgnore) ); } @Test public void shouldVerifyReceivedRequests() { // when mockServerClient .when( request() .withPath(calculatePath("some_path")), exactly(2) ) .respond( response() .withBody("some_body") ); // then // - in http assertEquals( response() .withStatusCode(HttpStatusCode.OK_200.code()) .withBody("some_body"), makeRequest( request() .withPath(calculatePath("some_path")), headersToIgnore) ); mockServerClient.verify(request() .withPath(calculatePath("some_path"))); mockServerClient.verify(request() .withPath(calculatePath("some_path")), VerificationTimes.exactly(1)); // - in https assertEquals( response() .withStatusCode(HttpStatusCode.OK_200.code()) .withBody("some_body"), makeRequest( request() .withSecure(true) .withPath(calculatePath("some_path")), headersToIgnore) ); mockServerClient.verify(request().withPath(calculatePath("some_path")), VerificationTimes.atLeast(1)); mockServerClient.verify(request().withPath(calculatePath("some_path")), VerificationTimes.exactly(2)); } @Test public void shouldVerifyReceivedRequestInSsl() { // when mockServerClient .when( request() .withPath(calculatePath("some.*path")), exactly(2) ) .respond( response() .withBody("some_body") ); // then // - in http assertEquals( response() .withStatusCode(HttpStatusCode.OK_200.code()) .withBody("some_body"), makeRequest( request() .withPath(calculatePath("some_path")), headersToIgnore) ); mockServerClient.verify(request() .withPath(calculatePath("some_path")) .withSecure(false)); mockServerClient.verify(request() .withPath(calculatePath("some_path")) .withSecure(false), VerificationTimes.exactly(1)); // - in https assertEquals( response() .withStatusCode(HttpStatusCode.OK_200.code()) .withBody("some_body"), makeRequest( request() .withPath(calculatePath("some_secure_path")) .withSecure(true), headersToIgnore) ); mockServerClient.verify(request() .withPath(calculatePath("some_secure_path")) .withSecure(true)); mockServerClient.verify(request() .withPath(calculatePath("some_secure_path")) .withSecure(true), VerificationTimes.exactly(1)); } @Test public void shouldVerifyReceivedRequestsWithNoBody() { // when mockServerClient.when(request().withPath(calculatePath("some_path")), exactly(2)).respond(response()); // then // - in http assertEquals( response() .withStatusCode(HttpStatusCode.OK_200.code()), makeRequest( request() .withPath(calculatePath("some_path")), headersToIgnore) ); mockServerClient.verify(request() .withPath(calculatePath("some_path"))); mockServerClient.verify(request() .withPath(calculatePath("some_path")), VerificationTimes.exactly(1)); } @Test public void shouldVerifyNotEnoughRequestsReceived() { // when mockServerClient.when(request().withPath(calculatePath("some_path")), exactly(2)).respond(response().withBody("some_body")); // then assertEquals( response() .withStatusCode(HttpStatusCode.OK_200.code()) .withBody("some_body"), makeRequest( request() .withPath(calculatePath("some_path")), headersToIgnore) ); try { mockServerClient.verify(request() .withPath(calculatePath("some_path")), VerificationTimes.atLeast(2)); fail(); } catch (AssertionError ae) { assertThat(ae.getMessage(), startsWith("Request not found at least 2 times, expected:<{" + System.getProperty("line.separator") + " \"path\" : \"" + calculatePath("some_path") + "\"" + System.getProperty("line.separator") + "}> but was:<{" + System.getProperty("line.separator") + " \"method\" : \"GET\"," + System.getProperty("line.separator") + " \"path\" : \"" + calculatePath("some_path") + "\"," + System.getProperty("line.separator"))); } } @Test public void shouldVerifyTooManyRequestsReceived() { // when mockServerClient.when(request().withPath(calculatePath("some_path")), exactly(2)).respond(response().withBody("some_body")); // then assertEquals( response() .withStatusCode(HttpStatusCode.OK_200.code()) .withBody("some_body"), makeRequest( request() .withPath(calculatePath("some_path")), headersToIgnore) ); try { mockServerClient.verify(request() .withPath(calculatePath("some_path")), VerificationTimes.exactly(0)); fail(); } catch (AssertionError ae) { assertThat(ae.getMessage(), startsWith("Request not found exactly 0 times, expected:<{" + System.getProperty("line.separator") + " \"path\" : \"" + calculatePath("some_path") + "\"" + System.getProperty("line.separator") + "}> but was:<{" + System.getProperty("line.separator") + " \"method\" : \"GET\"," + System.getProperty("line.separator") + " \"path\" : \"" + calculatePath("some_path") + "\"," + System.getProperty("line.separator"))); } } @Test public void shouldVerifyNoMatchingRequestsReceived() { // when mockServerClient.when(request().withPath(calculatePath("some_path")), exactly(2)).respond(response().withBody("some_body")); // then assertEquals( response() .withStatusCode(HttpStatusCode.OK_200.code()) .withBody("some_body"), makeRequest( request() .withPath(calculatePath("some_path")), headersToIgnore) ); try { mockServerClient.verify(request() .withPath(calculatePath("some_other_path")), VerificationTimes.exactly(2)); fail(); } catch (AssertionError ae) { assertThat(ae.getMessage(), startsWith("Request not found exactly 2 times, expected:<{" + System.getProperty("line.separator") + " \"path\" : \"" + calculatePath("some_other_path") + "\"" + System.getProperty("line.separator") + "}> but was:<{" + System.getProperty("line.separator") + " \"method\" : \"GET\"," + System.getProperty("line.separator") + " \"path\" : \"" + calculatePath("some_path") + "\"," + System.getProperty("line.separator"))); } } @Test public void shouldVerifyNoRequestsReceived() { // when mockServerClient.reset(); // then mockServerClient.verifyZeroInteractions(); } @Test public void shouldNotVerifyNoRequestsReceived() { // when mockServerClient.when(request().withPath(calculatePath("some_path")), exactly(2)).respond(response().withBody("some_body")); // then assertEquals( response() .withStatusCode(HttpStatusCode.OK_200.code()) .withBody("some_body"), makeRequest( request() .withPath(calculatePath("some_path")), headersToIgnore) ); try { mockServerClient.verifyZeroInteractions(); fail(); } catch (AssertionError ae) { assertThat(ae.getMessage(), startsWith("Request not found exactly 0 times, expected:<{ }> but was:<{" + System.getProperty("line.separator") + " \"method\" : \"GET\"," + System.getProperty("line.separator") + " \"path\" : \"" + calculatePath("some_path") + "\"," + System.getProperty("line.separator"))); } } @Test public void shouldVerifyNoMatchingRequestsReceivedInSsl() { // when mockServerClient.when(request().withPath(calculatePath("some.*path")), exactly(2)).respond(response().withBody("some_body")); // then // - in http assertEquals( response() .withStatusCode(HttpStatusCode.OK_200.code()) .withBody("some_body"), makeRequest( request() .withPath(calculatePath("some_path")), headersToIgnore) ); try { mockServerClient.verify( request() .withPath(calculatePath("some_path")) .withSecure(true), VerificationTimes.atLeast(1) ); fail(); } catch (AssertionError ae) { assertThat(ae.getMessage(), startsWith("Request not found at least once, expected:<{" + System.getProperty("line.separator") + " \"path\" : \"" + calculatePath("some_path") + "\"," + System.getProperty("line.separator") + " \"secure\" : true" + System.getProperty("line.separator") + "}> but was:<{" + System.getProperty("line.separator") + " \"method\" : \"GET\"," + System.getProperty("line.separator") + " \"path\" : \"" + calculatePath("some_path") + "\"," + System.getProperty("line.separator"))); } // - in https assertEquals( response() .withStatusCode(HttpStatusCode.OK_200.code()) .withBody("some_body"), makeRequest( request() .withPath(calculatePath("some_secure_path")) .withSecure(true), headersToIgnore) ); try { mockServerClient.verify( request() .withPath(calculatePath("some_secure_path")) .withSecure(false), VerificationTimes.atLeast(1) ); fail(); } catch (AssertionError ae) { assertThat(ae.getMessage(), startsWith("Request not found at least once, expected:<{" + System.getProperty("line.separator") + " \"path\" : \"" + calculatePath("some_secure_path") + "\"," + System.getProperty("line.separator") + " \"secure\" : false" + System.getProperty("line.separator") + "}> but was:<[ {" + System.getProperty("line.separator") + " \"method\" : \"GET\"," + System.getProperty("line.separator") + " \"path\" : \"" + calculatePath("some_path") + "\"," + System.getProperty("line.separator"))); } } @Test public void shouldVerifySequenceOfRequestsReceived() { // when mockServerClient.when(request().withPath(calculatePath("some_path.*")), exactly(6)).respond(response().withBody("some_body")); // then assertEquals( response("some_body"), makeRequest( request().withPath(calculatePath("some_path_one")), headersToIgnore) ); assertEquals( response("some_body"), makeRequest( request().withPath(calculatePath("some_path_two")), headersToIgnore) ); assertEquals( response("some_body"), makeRequest( request().withPath(calculatePath("some_path_three")), headersToIgnore) ); mockServerClient.verify(request(calculatePath("some_path_one")), request(calculatePath("some_path_three"))); mockServerClient.verify(request(calculatePath("some_path_one")), request(calculatePath("some_path_two"))); mockServerClient.verify(request(calculatePath("some_path_one")), request(calculatePath("some_path_two")), request(calculatePath("some_path_three"))); } @Test public void shouldVerifySequenceOfRequestsReceivedIncludingThoseNotMatchingAnException() { // when mockServerClient.when(request().withPath(calculatePath("some_path.*")), exactly(4)).respond(response().withBody("some_body")); // then assertEquals( response("some_body"), makeRequest( request().withPath(calculatePath("some_path_one")), headersToIgnore) ); assertEquals( notFoundResponse(), makeRequest( request().withPath(calculatePath("not_found")), headersToIgnore) ); assertEquals( response("some_body"), makeRequest( request().withPath(calculatePath("some_path_three")), headersToIgnore) ); mockServerClient.verify(request(calculatePath("some_path_one")), request(calculatePath("some_path_three"))); mockServerClient.verify(request(calculatePath("some_path_one")), request(calculatePath("not_found"))); mockServerClient.verify(request(calculatePath("some_path_one")), request(calculatePath("not_found")), request(calculatePath("some_path_three"))); mockServerClient.verify(request(calculatePath("some_path_one")), request(calculatePath("not_found")), request(calculatePath("some_path_three"))); } @Test public void shouldRetrieveSequenceOfRequestsReceivedIncludingThoseNotMatchingAnException() { // when mockServerClient.when(request().withPath(calculatePath("some_path.*")), exactly(4)).respond(response().withBody("some_body")); assertEquals( response("some_body"), makeRequest( request().withPath(calculatePath("some_path_one")), headersToIgnore) ); assertEquals( notFoundResponse(), makeRequest( request().withPath(calculatePath("not_found")), headersToIgnore) ); assertEquals( response("some_body"), makeRequest( request().withPath(calculatePath("some_path_three")), headersToIgnore) ); // then verifyRequestMatches( mockServerClient.retrieveRecordedRequests(request().withPath(calculatePath("some_path.*"))), request(calculatePath("some_path_one")), request(calculatePath("some_path_three")) ); verifyRequestMatches( mockServerClient.retrieveRecordedRequests(request()), request(calculatePath("some_path_one")), request(calculatePath("not_found")), request(calculatePath("some_path_three")) ); verifyRequestMatches( mockServerClient.retrieveRecordedRequests(null), request(calculatePath("some_path_one")), request(calculatePath("not_found")), request(calculatePath("some_path_three")) ); } @Test public void shouldRetrieveSequenceOfExpectationsSetup() { // when mockServerClient.when(request().withPath(calculatePath("some_path.*")), exactly(4)) .respond(response().withBody("some_body")); mockServerClient.when(request().withPath(calculatePath("some_path.*"))) .respond(response().withBody("some_body")); mockServerClient.when(request().withPath(calculatePath("some_other_path"))) .respond(response().withBody("some_other_body")); mockServerClient.when(request().withPath(calculatePath("some_forward_path"))) .forward(forward()); // then assertThat( mockServerClient.retrieveExistingExpectations(request().withPath(calculatePath("some_path.*"))), arrayContaining( new Expectation(request().withPath(calculatePath("some_path.*")), exactly(4), TimeToLive.unlimited()) .thenRespond(response().withBody("some_body")), expectation(request().withPath(calculatePath("some_path.*"))) .thenRespond(response().withBody("some_body")) ) ); assertThat( mockServerClient.retrieveExistingExpectations(null), arrayContaining( new Expectation(request().withPath(calculatePath("some_path.*")), exactly(4), TimeToLive.unlimited()) .thenRespond(response().withBody("some_body")), expectation(request().withPath(calculatePath("some_path.*"))) .thenRespond(response().withBody("some_body")), expectation(request().withPath(calculatePath("some_other_path"))) .thenRespond(response().withBody("some_other_body")), expectation(request().withPath(calculatePath("some_forward_path"))) .thenForward(forward()) ) ); assertThat( mockServerClient.retrieveExistingExpectations(request()), arrayContaining( new Expectation(request().withPath(calculatePath("some_path.*")), exactly(4), TimeToLive.unlimited()) .thenRespond(response().withBody("some_body")), expectation(request().withPath(calculatePath("some_path.*"))) .thenRespond(response().withBody("some_body")), expectation(request().withPath(calculatePath("some_other_path"))) .thenRespond(response().withBody("some_other_body")), expectation(request().withPath(calculatePath("some_forward_path"))) .thenForward(forward()) ) ); } @Test public void shouldVerifySequenceOfRequestsNotReceived() { // when mockServerClient.when(request().withPath(calculatePath("some_path.*")), exactly(6)).respond(response().withBody("some_body")); // then assertEquals( response("some_body"), makeRequest( request().withPath(calculatePath("some_path_one")), headersToIgnore) ); assertEquals( response("some_body"), makeRequest( request().withPath(calculatePath("some_path_two")), headersToIgnore) ); assertEquals( response("some_body"), makeRequest( request().withPath(calculatePath("some_path_three")), headersToIgnore) ); try { mockServerClient.verify(request(calculatePath("some_path_two")), request(calculatePath("some_path_one"))); fail(); } catch (AssertionError ae) { assertThat(ae.getMessage(), startsWith("Request sequence not found, expected:<[ {" + System.getProperty("line.separator") + " \"path\" : \"" + calculatePath("some_path_two") + "\"" + System.getProperty("line.separator") + "}, {" + System.getProperty("line.separator") + " \"path\" : \"" + calculatePath("some_path_one") + "\"" + System.getProperty("line.separator") + "} ]> but was:<[ {" + System.getProperty("line.separator") + " \"method\" : \"GET\"," + System.getProperty("line.separator") + " \"path\" : \"" + calculatePath("some_path_one") + "\"," + System.getProperty("line.separator"))); } try { mockServerClient.verify(request(calculatePath("some_path_three")), request(calculatePath("some_path_two"))); fail(); } catch (AssertionError ae) { assertThat(ae.getMessage(), startsWith("Request sequence not found, expected:<[ {" + System.getProperty("line.separator") + " \"path\" : \"" + calculatePath("some_path_three") + "\"" + System.getProperty("line.separator") + "}, {" + System.getProperty("line.separator") + " \"path\" : \"" + calculatePath("some_path_two") + "\"" + System.getProperty("line.separator") + "} ]> but was:<[ {" + System.getProperty("line.separator") + " \"method\" : \"GET\"," + System.getProperty("line.separator") + " \"path\" : \"" + calculatePath("some_path_one") + "\"," + System.getProperty("line.separator"))); } try { mockServerClient.verify(request(calculatePath("some_path_four"))); fail(); } catch (AssertionError ae) { assertThat(ae.getMessage(), startsWith("Request sequence not found, expected:<[ {" + System.getProperty("line.separator") + " \"path\" : \"" + calculatePath("some_path_four") + "\"" + System.getProperty("line.separator") + "} ]> but was:<[ {" + System.getProperty("line.separator") + " \"method\" : \"GET\"," + System.getProperty("line.separator") + " \"path\" : \"" + calculatePath("some_path_one") + "\"," + System.getProperty("line.separator"))); } } @Test public void shouldClearExpectationsAndLogs() { // given - some expectations mockServerClient .when( request() .withPath(calculatePath("some_path1")) ) .respond( response() .withBody("some_body1") ); mockServerClient .when( request() .withPath(calculatePath("some_path2")) ) .respond( response() .withBody("some_body2") ); // and - some matching requests assertEquals( response() .withStatusCode(HttpStatusCode.OK_200.code()) .withBody("some_body1"), makeRequest( request() .withPath(calculatePath("some_path1")), headersToIgnore) ); assertEquals( response() .withStatusCode(HttpStatusCode.OK_200.code()) .withBody("some_body2"), makeRequest( request() .withPath(calculatePath("some_path2")), headersToIgnore) ); // when mockServerClient .clear( request() .withPath(calculatePath("some_path1")) ); // then - expectations cleared assertThat( mockServerClient.retrieveExistingExpectations(null), arrayContaining( expectation( request() .withPath(calculatePath("some_path2")) ) .thenRespond( response() .withBody("some_body2") ) ) ); // and then - request log cleared verifyRequestMatches( mockServerClient.retrieveRecordedRequests(null), request(calculatePath("some_path2")) ); // and then - remaining expectations not cleared assertEquals( response() .withStatusCode(HttpStatusCode.OK_200.code()) .withBody("some_body2"), makeRequest( request() .withPath(calculatePath("some_path2")), headersToIgnore) ); assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()), makeRequest( request() .withPath(calculatePath("some_path1")), headersToIgnore) ); } @Test public void shouldClearExpectationsOnly() { // given - some expectations mockServerClient .when( request() .withPath(calculatePath("some_path1")) ) .respond( response() .withBody("some_body1") ); mockServerClient .when( request() .withPath(calculatePath("some_path2")) ) .respond( response() .withBody("some_body2") ); // and - some matching requests assertEquals( response() .withStatusCode(HttpStatusCode.OK_200.code()) .withBody("some_body1"), makeRequest( request() .withPath(calculatePath("some_path1")), headersToIgnore) ); assertEquals( response() .withStatusCode(HttpStatusCode.OK_200.code()) .withBody("some_body2"), makeRequest( request() .withPath(calculatePath("some_path2")), headersToIgnore) ); // when mockServerClient .clear( request() .withPath(calculatePath("some_path1")), MockServerClient.TYPE.EXPECTATION ); // then - expectations cleared assertThat( mockServerClient.retrieveExistingExpectations(null), arrayContaining( expectation( request() .withPath(calculatePath("some_path2")) ) .thenRespond( response() .withBody("some_body2") ) ) ); // and then - request log not cleared verifyRequestMatches( mockServerClient.retrieveRecordedRequests(null), request(calculatePath("some_path1")), request(calculatePath("some_path2")) ); } @Test public void shouldClearLogsOnly() { // given - some expectations mockServerClient .when( request() .withPath(calculatePath("some_path1")) ) .respond( response() .withBody("some_body1") ); mockServerClient .when( request() .withPath(calculatePath("some_path2")) ) .respond( response() .withBody("some_body2") ); // and - some matching requests assertEquals( response() .withStatusCode(HttpStatusCode.OK_200.code()) .withBody("some_body1"), makeRequest( request() .withPath(calculatePath("some_path1")), headersToIgnore) ); assertEquals( response() .withStatusCode(HttpStatusCode.OK_200.code()) .withBody("some_body2"), makeRequest( request() .withPath(calculatePath("some_path2")), headersToIgnore) ); // when mockServerClient .clear( request() .withPath(calculatePath("some_path1")), MockServerClient.TYPE.LOG ); // then - expectations cleared assertThat( mockServerClient.retrieveExistingExpectations(null), arrayContaining( expectation( request() .withPath(calculatePath("some_path1")) ) .thenRespond( response() .withBody("some_body1") ), expectation( request() .withPath(calculatePath("some_path2")) ) .thenRespond( response() .withBody("some_body2") ) ) ); // and then - request log cleared verifyRequestMatches( mockServerClient.retrieveRecordedRequests(null), request(calculatePath("some_path2")) ); } @Test public void shouldClearAllExpectationsWithNull() { // given mockServerClient .when( request() .withPath(calculatePath("some_path1")) ) .respond( response() .withBody("some_body1") ); mockServerClient .when( request() .withPath(calculatePath("some_path2")) ) .respond( response() .withBody("some_body2") ); assertEquals( response() .withStatusCode(HttpStatusCode.OK_200.code()) .withBody("some_body2"), makeRequest( request() .withPath(calculatePath("some_path2")), headersToIgnore) ); // when mockServerClient.clear(null); // then assertThat(mockServerClient.retrieveExistingExpectations(null), emptyArray()); assertThat(mockServerClient.retrieveRecordedRequests(null), emptyArray()); } @Test public void shouldClearAllExpectationsWithEmptyRequest() { // given mockServerClient .when( request() .withPath(calculatePath("some_path1")) ) .respond( response() .withBody("some_body1") ); mockServerClient .when( request() .withPath(calculatePath("some_path2")) ) .respond( response() .withBody("some_body2") ); assertEquals( response() .withStatusCode(HttpStatusCode.OK_200.code()) .withBody("some_body2"), makeRequest( request() .withPath(calculatePath("some_path2")), headersToIgnore) ); // when mockServerClient.clear(request()); // then assertThat(mockServerClient.retrieveExistingExpectations(null), emptyArray()); assertThat(mockServerClient.retrieveRecordedRequests(null), emptyArray()); } @Test public void shouldClearExpectationsWithXPathBody() { // given mockServerClient .when( request() .withBody(xpath("/bookstore/book[year=2005]/price")) ) .respond( response() .withBody("some_body1") ); mockServerClient .when( request() .withBody(xpath("/bookstore/book[year=2006]/price")) ) .respond( response() .withBody("some_body2") ); // and StringBody xmlBody = new StringBody("" + "<?xml version=\"1.0\" encoding=\"ISO-8859-1\"?>" + System.getProperty("line.separator") + "<bookstore>" + System.getProperty("line.separator") + " <book category=\"COOKING\">" + System.getProperty("line.separator") + " <title lang=\"en\">Everyday Italian</title>" + System.getProperty("line.separator") + " <author>Giada De Laurentiis</author>" + System.getProperty("line.separator") + " <year>2005</year>" + System.getProperty("line.separator") + " <price>30.00</price>" + System.getProperty("line.separator") + " </book>" + System.getProperty("line.separator") + " <book category=\"CHILDREN\">" + System.getProperty("line.separator") + " <title lang=\"en\">Harry Potter</title>" + System.getProperty("line.separator") + " <author>J K. Rowling</author>" + System.getProperty("line.separator") + " <year>2006</year>" + System.getProperty("line.separator") + " <price>29.99</price>" + System.getProperty("line.separator") + " </book>" + System.getProperty("line.separator") + " <book category=\"WEB\">" + System.getProperty("line.separator") + " <title lang=\"en\">Learning XML</title>" + System.getProperty("line.separator") + " <author>Erik T. Ray</author>" + System.getProperty("line.separator") + " <year>2003</year>" + System.getProperty("line.separator") + " <price>31.95</price>" + System.getProperty("line.separator") + " </book>" + System.getProperty("line.separator") + "</bookstore>"); // then assertEquals( response() .withStatusCode(HttpStatusCode.OK_200.code()) .withBody("some_body1"), makeRequest( request() .withBody(xmlBody), headersToIgnore) ); // when mockServerClient .clear( request() .withBody(xpath("/bookstore/book[year=2005]/price")) ); // then assertThat( mockServerClient.retrieveExistingExpectations(null), arrayContaining( expectation( request() .withBody(xpath("/bookstore/book[year=2006]/price")) ) .thenRespond( response() .withBody("some_body2") ) ) ); // - in http assertEquals( response() .withStatusCode(HttpStatusCode.OK_200.code()) .withBody("some_body2"), makeRequest( request() .withBody(xmlBody), headersToIgnore) ); // - in https assertEquals( response() .withStatusCode(HttpStatusCode.OK_200.code()) .withBody("some_body2"), makeRequest( request() .withSecure(true) .withBody(xmlBody), headersToIgnore) ); } @Test public void shouldClearExpectationsWithJsonSchemaBody() { // given JsonSchemaBody jsonSchemaBodyOne = jsonSchema("{" + System.getProperty("line.separator") + " \"$schema\": \"http://json-schema.org/draft-04/schema#\"," + System.getProperty("line.separator") + " \"title\": \"Product\"," + System.getProperty("line.separator") + " \"description\": \"A product from Acme's catalog\"," + System.getProperty("line.separator") + " \"type\": \"object\"," + System.getProperty("line.separator") + " \"properties\": {" + System.getProperty("line.separator") + " \"id\": {" + System.getProperty("line.separator") + " \"description\": \"The unique identifier for a product\"," + System.getProperty("line.separator") + " \"type\": \"integer\"" + System.getProperty("line.separator") + " }," + System.getProperty("line.separator") + " \"name\": {" + System.getProperty("line.separator") + " \"description\": \"Name of the product\"," + System.getProperty("line.separator") + " \"type\": \"string\"" + System.getProperty("line.separator") + " }," + System.getProperty("line.separator") + " \"price\": {" + System.getProperty("line.separator") + " \"type\": \"number\"," + System.getProperty("line.separator") + " \"minimum\": 0," + System.getProperty("line.separator") + " \"exclusiveMinimum\": true" + System.getProperty("line.separator") + " }," + System.getProperty("line.separator") + " \"tags\": {" + System.getProperty("line.separator") + " \"type\": \"array\"," + System.getProperty("line.separator") + " \"items\": {" + System.getProperty("line.separator") + " \"type\": \"string\"" + System.getProperty("line.separator") + " }," + System.getProperty("line.separator") + " \"minItems\": 1," + System.getProperty("line.separator") + " \"uniqueItems\": true" + System.getProperty("line.separator") + " }" + System.getProperty("line.separator") + " }," + System.getProperty("line.separator") + " \"required\": [\"id\", \"name\", \"price\"]" + System.getProperty("line.separator") + "}"); JsonSchemaBody jsonSchemaBodyTwo = jsonSchema("{" + System.getProperty("line.separator") + " \"$schema\": \"http://json-schema.org/draft-04/schema#\"," + System.getProperty("line.separator") + " \"title\": \"Product\"," + System.getProperty("line.separator") + " \"description\": \"A product from Acme's catalog\"," + System.getProperty("line.separator") + " \"type\": \"object\"," + System.getProperty("line.separator") + " \"properties\": {" + System.getProperty("line.separator") + " \"id\": {" + System.getProperty("line.separator") + " \"description\": \"The unique identifier for a product\"," + System.getProperty("line.separator") + " \"type\": \"integer\"" + System.getProperty("line.separator") + " }," + System.getProperty("line.separator") + " \"name\": {" + System.getProperty("line.separator") + " \"description\": \"Name of the product\"," + System.getProperty("line.separator") + " \"type\": \"string\"" + System.getProperty("line.separator") + " }," + System.getProperty("line.separator") + " \"price\": {" + System.getProperty("line.separator") + " \"type\": \"number\"," + System.getProperty("line.separator") + " \"minimum\": 10," + System.getProperty("line.separator") + " \"exclusiveMinimum\": true" + System.getProperty("line.separator") + " }," + System.getProperty("line.separator") + " \"tags\": {" + System.getProperty("line.separator") + " \"type\": \"array\"," + System.getProperty("line.separator") + " \"items\": {" + System.getProperty("line.separator") + " \"type\": \"string\"" + System.getProperty("line.separator") + " }," + System.getProperty("line.separator") + " \"minItems\": 1," + System.getProperty("line.separator") + " \"uniqueItems\": true" + System.getProperty("line.separator") + " }" + System.getProperty("line.separator") + " }," + System.getProperty("line.separator") + " \"required\": [\"id\", \"name\", \"price\"]" + System.getProperty("line.separator") + "}"); mockServerClient .when( request() .withBody(jsonSchemaBodyOne) ) .respond( response() .withBody("some_body1") ); mockServerClient .when( request() .withBody(jsonSchemaBodyTwo) ) .respond( response() .withBody("some_body2") ); // then assertEquals( response() .withStatusCode(HttpStatusCode.OK_200.code()) .withBody("some_body1"), makeRequest( request() .withBody("{" + System.getProperty("line.separator") + " \"id\": 1," + System.getProperty("line.separator") + " \"name\": \"A green door\"," + System.getProperty("line.separator") + " \"price\": 12.50," + System.getProperty("line.separator") + " \"tags\": [\"home\", \"green\"]" + System.getProperty("line.separator") + "}"), headersToIgnore) ); // when mockServerClient .clear( request() .withBody(jsonSchemaBodyOne) ); // then assertThat( mockServerClient.retrieveExistingExpectations(null), arrayContaining( expectation( request() .withBody(jsonSchemaBodyTwo) ) .thenRespond( response() .withBody("some_body2") ) ) ); // - in http assertEquals( response() .withStatusCode(HttpStatusCode.OK_200.code()) .withBody("some_body2"), makeRequest( request() .withBody("{" + System.getProperty("line.separator") + " \"id\": 1," + System.getProperty("line.separator") + " \"name\": \"A green door\"," + System.getProperty("line.separator") + " \"price\": 12.50," + System.getProperty("line.separator") + " \"tags\": [\"home\", \"green\"]" + System.getProperty("line.separator") + "}"), headersToIgnore) ); // - in https assertEquals( response() .withStatusCode(HttpStatusCode.OK_200.code()) .withBody("some_body2"), makeRequest( request() .withSecure(true) .withBody("{" + System.getProperty("line.separator") + " \"id\": 1," + System.getProperty("line.separator") + " \"name\": \"A green door\"," + System.getProperty("line.separator") + " \"price\": 12.50," + System.getProperty("line.separator") + " \"tags\": [\"home\", \"green\"]" + System.getProperty("line.separator") + "}"), headersToIgnore) ); } @Test public void shouldClearExpectationsWithParameterBody() { // given mockServerClient .when( request() .withBody(params(param("bodyParameterNameOne", "bodyParameterValueOne"))) ) .respond( response() .withBody("some_body1") ); mockServerClient .when( request() .withBody(params(param("bodyParameterNameTwo", "bodyParameterValueTwo"))) ) .respond( response() .withBody("some_body2") ); // then assertEquals( response() .withStatusCode(HttpStatusCode.OK_200.code()) .withBody("some_body1"), makeRequest( request() .withBody(params(param("bodyParameterName.*", "bodyParameterValue.*"))), headersToIgnore) ); // when mockServerClient .clear( request() .withBody(params(param("bodyParameterNameOne", "bodyParameterValueOne"))) ); // then assertThat( mockServerClient.retrieveExistingExpectations(null), arrayContaining( expectation( request() .withBody(params(param("bodyParameterNameTwo", "bodyParameterValueTwo"))) ) .thenRespond( response() .withBody("some_body2") ) ) ); // - in http assertEquals( response() .withStatusCode(HttpStatusCode.OK_200.code()) .withBody("some_body2"), makeRequest( request() .withBody(params(param("bodyParameterName.*", "bodyParameterValue.*"))), headersToIgnore) ); // - in https assertEquals( response() .withStatusCode(HttpStatusCode.OK_200.code()) .withBody("some_body2"), makeRequest( request() .withSecure(true) .withBody(params(param("bodyParameterName.*", "bodyParameterValue.*"))), headersToIgnore) ); } @Test public void shouldReset() { // given mockServerClient .when( request() .withPath(calculatePath("some_path1")) ) .respond( response() .withBody("some_body1") ); mockServerClient .when( request() .withPath(calculatePath("some_path2")) ) .respond( response() .withBody("some_body2") ); // when mockServerClient.reset(); // then // - in http assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()), makeRequest( request() .withPath(calculatePath("some_path1")), headersToIgnore) ); assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()), makeRequest( request() .withPath(calculatePath("some_path2")), headersToIgnore) ); // - in https assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()), makeRequest( request() .withSecure(true) .withPath(calculatePath("some_path1")), headersToIgnore) ); assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()), makeRequest( request() .withSecure(true) .withPath(calculatePath("some_path2")), headersToIgnore) ); } @Test public void shouldEnsureThatRequestDelaysDoNotAffectOtherRequests() throws Exception { mockServerClient .when( request("/slow") ) .respond( response("super slow") .withDelay(new Delay(TimeUnit.SECONDS, 8)) ); mockServerClient .when( request("/fast") ) .respond( response("quite fast") ); ExecutorService executorService = Executors.newFixedThreadPool(2); Future<Long> slowFuture = executorService.submit(new Callable<Long>() { @Override public Long call() throws Exception { long start = System.currentTimeMillis(); makeRequest(request("/slow")); return System.currentTimeMillis() - start; } }); // Let fast request come to the server slightly after slow request Uninterruptibles.sleepUninterruptibly(1, TimeUnit.SECONDS); Future<Long> fastFuture = executorService.submit(new Callable<Long>() { @Override public Long call() throws Exception { long start = System.currentTimeMillis(); makeRequest(request("/fast")); return System.currentTimeMillis() - start; } }); Long slowRequestElapsedMillis = slowFuture.get(); Long fastRequestElapsedMillis = fastFuture.get(); assertThat("Slow request takes less than expected", slowRequestElapsedMillis, is(greaterThan(7 * 1000L))); assertThat("Fast request takes longer than expected", fastRequestElapsedMillis, is(lessThan(3 * 1000L))); } protected void verifyRequestMatches(HttpRequest[] httpRequests, HttpRequest... httpRequestMatchers) { if (httpRequests.length != httpRequestMatchers.length) { throw new AssertionError("Number of request matchers does not match number of requests, expected:<" + httpRequestMatchers.length + "> but was:<" + httpRequests.length + ">"); } else { for (int i = 0; i < httpRequestMatchers.length; i++) { if (!new HttpRequestMatcher(httpRequestMatchers[i]).matches(httpRequests[i])) { throw new AssertionError("Request does not match request matcher, expected:<" + httpRequestMatchers[i] + "> but was:<" + httpRequests[i] + ">"); } } } } protected HttpResponse makeRequest(HttpRequest httpRequest) { return makeRequest(httpRequest, Collections.<String>emptySet()); } protected HttpResponse makeRequest(HttpRequest httpRequest, Collection<String> headersToIgnore) { int attemptsRemaining = 10; while (attemptsRemaining > 0) { try { boolean isSsl = httpRequest.isSecure() != null && httpRequest.isSecure(); int port = (isSsl ? getMockServerSecurePort() : getMockServerPort()); HttpResponse httpResponse = httpClient.sendRequest(outboundRequest("localhost", port, servletContext, httpRequest)); List<Header> headers = new ArrayList<Header>(); for (Header header : httpResponse.getHeaders()) { if (!headersToIgnore.contains(header.getName().getValue().toLowerCase())) { if (header.getName().getValue().equalsIgnoreCase(HttpHeaders.CONTENT_TYPE)) { // this fixes Tomcat which removes the space between // media type and charset in the Content-Type header for (NottableString value : new ArrayList<NottableString>(header.getValues())) { header.getValues().clear(); header.addValues(value.getValue().replace(";charset", "; charset")); } } headers.add(header); } } httpResponse.withHeaders(headers); return httpResponse; } catch (SocketConnectionException caught) { attemptsRemaining--; logger.info("Retrying connection to mock server, attempts remaining: " + attemptsRemaining); try { TimeUnit.MILLISECONDS.sleep(500); } catch (InterruptedException e) { // do nothing } } } throw new RuntimeException("Failed to send request:" + System.getProperty("line.separator") + httpRequest); } }
mbuffet/mockserver
mockserver-integration-testing/src/main/java/org/mockserver/integration/server/AbstractClientServerIntegrationTest.java
924
package org.mockserver.integration.server; import com.google.common.base.Charsets; import com.google.common.net.HttpHeaders; import com.google.common.net.MediaType; import com.google.common.util.concurrent.Uninterruptibles; import org.apache.commons.io.IOUtils; import org.junit.Before; import org.junit.Test; import org.mockserver.client.netty.NettyHttpClient; import org.mockserver.client.netty.SocketConnectionException; import org.mockserver.client.server.MockServerClient; import org.mockserver.echo.http.EchoServer; import org.mockserver.matchers.HttpRequestMatcher; import org.mockserver.matchers.MatchType; import org.mockserver.matchers.TimeToLive; import org.mockserver.matchers.Times; import org.mockserver.mock.Expectation; import org.mockserver.model.*; import org.mockserver.socket.PortFactory; import org.mockserver.verify.VerificationTimes; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.IOException; import java.util.*; import java.util.concurrent.*; import static org.hamcrest.Matchers.*; import static org.hamcrest.core.Is.is; import static org.hamcrest.core.StringStartsWith.startsWith; import static org.hamcrest.number.OrderingComparison.greaterThan; import static org.junit.Assert.*; import static org.mockserver.matchers.Times.exactly; import static org.mockserver.matchers.Times.once; import static org.mockserver.model.BinaryBody.binary; import static org.mockserver.model.Cookie.cookie; import static org.mockserver.model.Header.header; import static org.mockserver.model.HttpCallback.callback; import static org.mockserver.model.HttpForward.forward; import static org.mockserver.model.HttpRequest.request; import static org.mockserver.model.HttpResponse.notFoundResponse; import static org.mockserver.model.HttpResponse.response; import static org.mockserver.model.JsonBody.json; import static org.mockserver.model.JsonSchemaBody.jsonSchema; import static org.mockserver.model.NottableString.not; import static org.mockserver.model.NottableString.string; import static org.mockserver.model.OutboundHttpRequest.outboundRequest; import static org.mockserver.model.Parameter.param; import static org.mockserver.model.ParameterBody.params; import static org.mockserver.model.StringBody.exact; import static org.mockserver.model.XPathBody.xpath; import static org.mockserver.model.XmlBody.xml; /** * @author jamesdbloom */ public abstract class AbstractClientServerIntegrationTest { public static final String TEXT_PLAIN = MediaType.create("text", "plain").toString(); protected static MockServerClient mockServerClient; protected static String servletContext = ""; private final Logger logger = LoggerFactory.getLogger(this.getClass()); protected List<String> headersToIgnore = Arrays.asList( "server", "expires", "date", "host", "connection", "user-agent", "content-length", "accept-encoding", "transfer-encoding" ); private NettyHttpClient httpClient = new NettyHttpClient(); public static Expectation expectation(HttpRequest httpRequest) { return new Expectation(httpRequest, Times.unlimited(), TimeToLive.unlimited()); } public abstract int getMockServerPort(); public abstract int getMockServerSecurePort(); public abstract int getTestServerPort(); protected String calculatePath(String path) { return "/" + path; } @Before public void resetServer() { mockServerClient.reset(); } @Test public void shouldForwardRequestInHTTP() { // when mockServerClient .when( request() .withPath(calculatePath("echo")) ) .forward( forward() .withHost("127.0.0.1") .withPort(getTestServerPort()) ); // then // - in http assertEquals( response() .withStatusCode(HttpStatusCode.OK_200.code()) .withHeaders( header("x-test", "test_headers_and_body"), header(HttpHeaders.CONTENT_TYPE, TEXT_PLAIN) ) .withBody("an_example_body_http"), makeRequest( request() .withPath(calculatePath("echo")) .withMethod("POST") .withHeaders( header("x-test", "test_headers_and_body") ) .withBody("an_example_body_http"), headersToIgnore) ); // - in https assertEquals( response() .withStatusCode(HttpStatusCode.OK_200.code()) .withHeaders( header("x-test", "test_headers_and_body"), header(HttpHeaders.CONTENT_TYPE, TEXT_PLAIN) ) .withBody("an_example_body_https"), makeRequest( request() .withSecure(true) .withPath(calculatePath("echo")) .withMethod("POST") .withHeaders( header("x-test", "test_headers_and_body") ) .withBody("an_example_body_https"), headersToIgnore) ); } @Test public void shouldForwardRequestInHTTPS() { int testServerHttpsPort = PortFactory.findFreePort(); EchoServer secureEchoServer = new EchoServer(testServerHttpsPort, true); try { // when mockServerClient .when( request() .withPath(calculatePath("echo")) ) .forward( forward() .withHost("127.0.0.1") .withPort(testServerHttpsPort) .withScheme(HttpForward.Scheme.HTTPS) ); // then // - in http assertEquals( response() .withStatusCode(HttpStatusCode.OK_200.code()) .withHeaders( header("x-test", "test_headers_and_body"), header(HttpHeaders.CONTENT_TYPE, TEXT_PLAIN) ) .withBody("an_example_body_http"), makeRequest( request() .withPath(calculatePath("echo")) .withMethod("POST") .withHeaders( header("x-test", "test_headers_and_body") ) .withBody("an_example_body_http"), headersToIgnore) ); // - in https assertEquals( response() .withStatusCode(HttpStatusCode.OK_200.code()) .withHeaders( header("x-test", "test_headers_and_body"), header(HttpHeaders.CONTENT_TYPE, TEXT_PLAIN) ) .withBody("an_example_body_https"), makeRequest( request() .withSecure(true) .withPath(calculatePath("echo")) .withMethod("POST") .withHeaders( header("x-test", "test_headers_and_body") ) .withBody("an_example_body_https"), headersToIgnore) ); } finally { secureEchoServer.stop(); } } @Test public void shouldAllowSimultaneousForwardAndResponseExpectations() { // when mockServerClient .when( request() .withPath(calculatePath("echo")), once() ) .forward( forward() .withHost("127.0.0.1") .withPort(getTestServerPort()) ); mockServerClient .when( request() .withPath(calculatePath("test_headers_and_body")), once() ) .respond( response() .withBody("some_body") ); // then // - forward assertEquals( response() .withStatusCode(HttpStatusCode.OK_200.code()) .withHeaders( header("x-test", "test_headers_and_body"), header(HttpHeaders.CONTENT_TYPE, TEXT_PLAIN) ) .withBody("an_example_body"), makeRequest( request() .withPath(calculatePath("echo")) .withMethod("POST") .withHeaders( header("x-test", "test_headers_and_body") ) .withBody("an_example_body"), headersToIgnore) ); // - respond assertEquals( response() .withHeader(HttpHeaders.CONTENT_TYPE, TEXT_PLAIN) .withStatusCode(HttpStatusCode.OK_200.code()) .withBody("some_body"), makeRequest( request() .withPath(calculatePath("test_headers_and_body")), headersToIgnore) ); // - no response or forward assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()), makeRequest( request() .withPath(calculatePath("test_headers_and_body")), headersToIgnore) ); } @Test public void shouldCallbackToSpecifiedClassWithPrecannedResponse() { // when mockServerClient .when( request() .withPath(calculatePath("callback")) ) .callback( callback() .withCallbackClass("org.mockserver.integration.callback.PrecannedTestExpectationCallback") ); // then // - in http assertEquals( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withHeaders( header("x-callback", "test_callback_header"), header(HttpHeaders.CONTENT_TYPE, TEXT_PLAIN) ) .withBody("a_callback_response"), makeRequest( request() .withPath(calculatePath("callback")) .withMethod("POST") .withHeaders( header("x-test", "test_headers_and_body") ) .withBody("an_example_body_http"), headersToIgnore ) ); // - in https assertEquals( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withHeaders( header("x-callback", "test_callback_header"), header(HttpHeaders.CONTENT_TYPE, TEXT_PLAIN) ) .withBody("a_callback_response"), makeRequest( request() .withSecure(true) .withPath(calculatePath("callback")) .withMethod("POST") .withHeaders( header("x-test", "test_headers_and_body") ) .withBody("an_example_body_https"), headersToIgnore ) ); } @Test public void shouldReturnResponseWithOnlyBody() { // when mockServerClient.when(request()).respond(response().withBody("some_body")); // then // - in http assertEquals( response() .withHeader(HttpHeaders.CONTENT_TYPE, TEXT_PLAIN) .withStatusCode(HttpStatusCode.OK_200.code()) .withBody("some_body"), makeRequest( request() .withPath(calculatePath("")), headersToIgnore) ); // - in https assertEquals( response() .withHeader(HttpHeaders.CONTENT_TYPE, TEXT_PLAIN) .withStatusCode(HttpStatusCode.OK_200.code()) .withBody("some_body"), makeRequest( request() .withSecure(true) .withPath(calculatePath("")), headersToIgnore) ); } @Test public void shouldReturnResponseForRequestInSsl() { // when mockServerClient.when(request().withSecure(true)).respond(response().withBody("some_body")); // then // - in http assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()), makeRequest( request() .withPath(calculatePath("")), headersToIgnore) ); // - in https assertEquals( response() .withHeader(HttpHeaders.CONTENT_TYPE, TEXT_PLAIN) .withStatusCode(HttpStatusCode.OK_200.code()) .withBody("some_body"), makeRequest( request() .withSecure(true) .withPath(calculatePath("")), headersToIgnore) ); } @Test public void shouldReturnResponseForRequestNotInSsl() { // when mockServerClient.when(request().withSecure(false)).respond(response().withBody("some_body")); // then // - in http assertEquals( response() .withHeader(HttpHeaders.CONTENT_TYPE, TEXT_PLAIN) .withStatusCode(HttpStatusCode.OK_200.code()) .withBody("some_body"), makeRequest( request() .withPath(calculatePath("")), headersToIgnore) ); // - in https assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()), makeRequest( request() .withSecure(true) .withPath(calculatePath("")), headersToIgnore) ); } @Test public void shouldReturnMatchRequestWithBodyInUTF16() { // when String body = "我说中国话"; mockServerClient.when(request().withBody(body, Charsets.UTF_16)).respond(response().withBody(body, Charsets.UTF_8)); // then // - in http assertEquals( response() .withHeader(HttpHeaders.CONTENT_TYPE, MediaType.create("text", "plain").withCharset(Charsets.UTF_8).toString()) .withStatusCode(HttpStatusCode.OK_200.code()) .withBody(body), makeRequest( request() .withPath(calculatePath("")) .withBody(body, Charsets.UTF_16), headersToIgnore) ); // - in https assertEquals( response() .withHeader(HttpHeaders.CONTENT_TYPE, MediaType.create("text", "plain").withCharset(Charsets.UTF_8).toString()) .withStatusCode(HttpStatusCode.OK_200.code()) .withBody(body), makeRequest( request() .withSecure(true) .withPath(calculatePath("")) .withBody(body, Charsets.UTF_16), headersToIgnore) ); } @Test public void shouldReturnMatchRequestWithBodyInUTF16WithContentTypeHeader() { // when String body = "我说中国话"; mockServerClient .when( request() .withHeader(HttpHeaders.CONTENT_TYPE, MediaType.create("text", "plain").withCharset(Charsets.UTF_8).toString()) .withBody(body) ) .respond( response() .withBody(body, Charsets.UTF_8) ); // then // - in http assertEquals( response() .withHeader(HttpHeaders.CONTENT_TYPE, MediaType.create("text", "plain").withCharset(Charsets.UTF_8).toString()) .withStatusCode(HttpStatusCode.OK_200.code()) .withBody(body), makeRequest( request() .withHeader(HttpHeaders.CONTENT_TYPE, MediaType.create("text", "plain").withCharset(Charsets.UTF_8).toString()) .withPath(calculatePath("")) .withBody(body), headersToIgnore) ); // - in https assertEquals( response() .withHeader(HttpHeaders.CONTENT_TYPE, MediaType.create("text", "plain").withCharset(Charsets.UTF_8).toString()) .withStatusCode(HttpStatusCode.OK_200.code()) .withBody(body), makeRequest( request() .withHeader(HttpHeaders.CONTENT_TYPE, MediaType.create("text", "plain").withCharset(Charsets.UTF_8).toString()) .withSecure(true) .withPath(calculatePath("")) .withBody(body), headersToIgnore) ); } @Test public void shouldReturnResponseWithBodyInUTF8() { // when String body = "我说中国话"; mockServerClient.when(request()).respond(response().withBody(body, Charsets.UTF_16)); // then // - in http assertEquals( response() .withHeader(HttpHeaders.CONTENT_TYPE, MediaType.create("text", "plain").withCharset(Charsets.UTF_16).toString()) .withStatusCode(HttpStatusCode.OK_200.code()) .withBody(body), makeRequest( request() .withPath(calculatePath("")), headersToIgnore) ); // - in https assertEquals( response() .withHeader(HttpHeaders.CONTENT_TYPE, MediaType.create("text", "plain").withCharset(Charsets.UTF_16).toString()) .withStatusCode(HttpStatusCode.OK_200.code()) .withBody(body), makeRequest( request() .withSecure(true) .withPath(calculatePath("")), headersToIgnore) ); } @Test public void shouldReturnResponseWithBodyInUTF16WithContentTypeHeader() { // when String body = "我说中国话"; mockServerClient .when( request() ) .respond( response() .withHeader(HttpHeaders.CONTENT_TYPE, MediaType.create("text", "plain").withCharset(Charsets.UTF_8).toString()) .withBody(body) ); // then // - in http assertEquals( response() .withHeader(HttpHeaders.CONTENT_TYPE, MediaType.create("text", "plain").withCharset(Charsets.UTF_8).toString()) .withStatusCode(HttpStatusCode.OK_200.code()) .withBody(body), makeRequest( request() .withPath(calculatePath("")), headersToIgnore) ); // - in https assertEquals( response() .withHeader(HttpHeaders.CONTENT_TYPE, MediaType.create("text", "plain").withCharset(Charsets.UTF_8).toString()) .withStatusCode(HttpStatusCode.OK_200.code()) .withBody(body), makeRequest( request() .withSecure(true) .withPath(calculatePath("")), headersToIgnore) ); } @Test public void shouldReturnResponseWithOnlyStatusCode() { // when mockServerClient .when( request() .withMethod("POST") .withPath(calculatePath("some_path")) ) .respond( response() .withStatusCode(200) ); // then // - in http assertEquals( response() .withStatusCode(HttpStatusCode.OK_200.code()), makeRequest( request() .withPath(calculatePath("some_path")) .withMethod("POST"), headersToIgnore) ); // - in https assertEquals( response() .withStatusCode(HttpStatusCode.OK_200.code()), makeRequest( request() .withSecure(true) .withPath(calculatePath("some_path")) .withMethod("POST"), headersToIgnore) ); } @Test public void shouldReturnResponseByMatchingPath() { // when mockServerClient .when( request() .withPath(calculatePath("some_path1")) ) .respond( response() .withBody("some_body1") ); mockServerClient .when( request() .withPath(calculatePath("some_path2")) ) .respond( response() .withBody("some_body2") ); // then // - in http assertEquals( response() .withHeader(HttpHeaders.CONTENT_TYPE, TEXT_PLAIN) .withStatusCode(HttpStatusCode.OK_200.code()) .withBody("some_body2"), makeRequest( request() .withPath(calculatePath("some_path2")), headersToIgnore) ); assertEquals( response() .withHeader(HttpHeaders.CONTENT_TYPE, TEXT_PLAIN) .withStatusCode(HttpStatusCode.OK_200.code()) .withBody("some_body1"), makeRequest( request() .withPath(calculatePath("some_path1")), headersToIgnore) ); // - in https assertEquals( response() .withHeader(HttpHeaders.CONTENT_TYPE, TEXT_PLAIN) .withStatusCode(HttpStatusCode.OK_200.code()) .withBody("some_body2"), makeRequest( request() .withSecure(true) .withPath(calculatePath("some_path2")), headersToIgnore) ); assertEquals( response() .withHeader(HttpHeaders.CONTENT_TYPE, TEXT_PLAIN) .withStatusCode(HttpStatusCode.OK_200.code()) .withBody("some_body1"), makeRequest( request() .withSecure(true) .withPath(calculatePath("some_path1")), headersToIgnore) ); } @Test public void shouldReturnResponseByMatchingPathExactTimes() { // when mockServerClient .when( request() .withPath(calculatePath("some_path")), exactly(2) ) .respond( response() .withBody("some_body") ); // then // - in http assertEquals( response() .withHeader(HttpHeaders.CONTENT_TYPE, TEXT_PLAIN) .withStatusCode(HttpStatusCode.OK_200.code()) .withBody("some_body"), makeRequest( request() .withPath(calculatePath("some_path")), headersToIgnore) ); // - in https assertEquals( response() .withHeader(HttpHeaders.CONTENT_TYPE, TEXT_PLAIN) .withStatusCode(HttpStatusCode.OK_200.code()) .withBody("some_body"), makeRequest( request() .withSecure(true) .withPath(calculatePath("some_path")), headersToIgnore) ); // - in http assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()), makeRequest( request() .withPath(calculatePath("some_path")), headersToIgnore) ); // - in https assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()), makeRequest( request() .withSecure(true) .withPath(calculatePath("some_path")), headersToIgnore) ); } @Test public void shouldReturnResponseWhenTimeToLiveHasNotExpired() { // when mockServerClient .when( request().withPath(calculatePath("some_path")), exactly(2), TimeToLive.exactly(TimeUnit.HOURS, 1L) ) .respond( response().withBody("some_body") ); // then // - in http assertEquals( response() .withHeader(HttpHeaders.CONTENT_TYPE, TEXT_PLAIN) .withStatusCode(HttpStatusCode.OK_200.code()) .withBody("some_body"), makeRequest( request() .withPath(calculatePath("some_path")), headersToIgnore) ); // - in https assertEquals( response() .withHeader(HttpHeaders.CONTENT_TYPE, TEXT_PLAIN) .withStatusCode(HttpStatusCode.OK_200.code()) .withBody("some_body"), makeRequest( request() .withSecure(true) .withPath(calculatePath("some_path")), headersToIgnore) ); // - in http assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()), makeRequest( request() .withPath(calculatePath("some_path")), headersToIgnore) ); // - in https assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()), makeRequest( request() .withSecure(true) .withPath(calculatePath("some_path")), headersToIgnore) ); } @Test public void shouldReturnResponseByMatchingBodyWithXPath() { // when mockServerClient.when(request().withBody(xpath("/bookstore/book[price>30]/price")), exactly(2)).respond(response().withBody("some_body")); // then // - in http assertEquals( response() .withHeader(HttpHeaders.CONTENT_TYPE, TEXT_PLAIN) .withStatusCode(HttpStatusCode.OK_200.code()) .withBody("some_body"), makeRequest( request() .withPath(calculatePath("some_path")) .withMethod("POST") .withBody(new StringBody("" + "<?xml version=\"1.0\" encoding=\"ISO-8859-1\"?>" + System.getProperty("line.separator") + "<bookstore>" + System.getProperty("line.separator") + " <book category=\"COOKING\">" + System.getProperty("line.separator") + " <title lang=\"en\">Everyday Italian</title>" + System.getProperty("line.separator") + " <author>Giada De Laurentiis</author>" + System.getProperty("line.separator") + " <year>2005</year>" + System.getProperty("line.separator") + " <price>30.00</price>" + System.getProperty("line.separator") + " </book>" + System.getProperty("line.separator") + " <book category=\"CHILDREN\">" + System.getProperty("line.separator") + " <title lang=\"en\">Harry Potter</title>" + System.getProperty("line.separator") + " <author>J K. Rowling</author>" + System.getProperty("line.separator") + " <year>2005</year>" + System.getProperty("line.separator") + " <price>29.99</price>" + System.getProperty("line.separator") + " </book>" + System.getProperty("line.separator") + " <book category=\"WEB\">" + System.getProperty("line.separator") + " <title lang=\"en\">Learning XML</title>" + System.getProperty("line.separator") + " <author>Erik T. Ray</author>" + System.getProperty("line.separator") + " <year>2003</year>" + System.getProperty("line.separator") + " <price>31.95</price>" + System.getProperty("line.separator") + " </book>" + System.getProperty("line.separator") + "</bookstore>")), headersToIgnore) ); // - in https assertEquals( response() .withHeader(HttpHeaders.CONTENT_TYPE, TEXT_PLAIN) .withStatusCode(HttpStatusCode.OK_200.code()) .withBody("some_body"), makeRequest( request() .withSecure(true) .withPath(calculatePath("some_path")) .withMethod("POST") .withBody(new StringBody("" + "<?xml version=\"1.0\" encoding=\"ISO-8859-1\"?>" + System.getProperty("line.separator") + "<bookstore>" + System.getProperty("line.separator") + " <book category=\"COOKING\">" + System.getProperty("line.separator") + " <title lang=\"en\">Everyday Italian</title>" + System.getProperty("line.separator") + " <author>Giada De Laurentiis</author>" + System.getProperty("line.separator") + " <year>2005</year>" + System.getProperty("line.separator") + " <price>30.00</price>" + System.getProperty("line.separator") + " </book>" + System.getProperty("line.separator") + " <book category=\"CHILDREN\">" + System.getProperty("line.separator") + " <title lang=\"en\">Harry Potter</title>" + System.getProperty("line.separator") + " <author>J K. Rowling</author>" + System.getProperty("line.separator") + " <year>2005</year>" + System.getProperty("line.separator") + " <price>29.99</price>" + System.getProperty("line.separator") + " </book>" + System.getProperty("line.separator") + " <book category=\"WEB\">" + System.getProperty("line.separator") + " <title lang=\"en\">Learning XML</title>" + System.getProperty("line.separator") + " <author>Erik T. Ray</author>" + System.getProperty("line.separator") + " <year>2003</year>" + System.getProperty("line.separator") + " <price>31.95</price>" + System.getProperty("line.separator") + " </book>" + System.getProperty("line.separator") + "</bookstore>")), headersToIgnore) ); } @Test public void shouldReturnResponseByMatchingBodyWithXml() { // when mockServerClient.when(request().withBody(xml("" + "<bookstore>" + System.getProperty("line.separator") + " <book nationality=\"ITALIAN\" category=\"COOKING\"><title lang=\"en\">Everyday Italian</title><author>Giada De Laurentiis</author><year>2005</year><price>30.00</price></book>" + System.getProperty("line.separator") + "</bookstore>")), exactly(2)).respond(response().withBody("some_body")); // then // - in http assertEquals( response() .withHeader(HttpHeaders.CONTENT_TYPE, TEXT_PLAIN) .withStatusCode(HttpStatusCode.OK_200.code()) .withBody("some_body"), makeRequest( request() .withPath(calculatePath("some_path")) .withMethod("POST") .withBody(new StringBody("" + "<?xml version=\"1.0\" encoding=\"ISO-8859-1\"?>" + System.getProperty("line.separator") + "<bookstore>" + System.getProperty("line.separator") + " <book category=\"COOKING\" nationality=\"ITALIAN\">" + System.getProperty("line.separator") + " <title lang=\"en\">Everyday Italian</title>" + System.getProperty("line.separator") + " <author>Giada De Laurentiis</author>" + System.getProperty("line.separator") + " <year>2005</year>" + System.getProperty("line.separator") + " <price>30.00</price>" + System.getProperty("line.separator") + " </book>" + System.getProperty("line.separator") + "</bookstore>")), headersToIgnore) ); // - in https assertEquals( response() .withHeader(HttpHeaders.CONTENT_TYPE, TEXT_PLAIN) .withStatusCode(HttpStatusCode.OK_200.code()) .withBody("some_body"), makeRequest( request() .withSecure(true) .withPath(calculatePath("some_path")) .withMethod("POST") .withBody(new StringBody("" + "<?xml version=\"1.0\" encoding=\"ISO-8859-1\"?>" + System.getProperty("line.separator") + "<bookstore>" + System.getProperty("line.separator") + " <book category=\"COOKING\" nationality=\"ITALIAN\">" + System.getProperty("line.separator") + " <title lang=\"en\">Everyday Italian</title>" + System.getProperty("line.separator") + " <author>Giada De Laurentiis</author>" + System.getProperty("line.separator") + " <year>2005</year>" + System.getProperty("line.separator") + " <price>30.00</price>" + System.getProperty("line.separator") + " </book>" + System.getProperty("line.separator") + "</bookstore>")), headersToIgnore) ); } @Test public void shouldReturnResponseByMatchingBodyWithJson() { // when mockServerClient .when( request() .withBody(json("{" + System.getProperty("line.separator") + " \"id\": 1," + System.getProperty("line.separator") + " \"name\": \"A green door\"," + System.getProperty("line.separator") + " \"price\": 12.50," + System.getProperty("line.separator") + " \"tags\": [\"home\", \"green\"]" + System.getProperty("line.separator") + "}")), exactly(2) ) .respond( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body") ); // then // - in http assertEquals( response() .withHeader(HttpHeaders.CONTENT_TYPE, TEXT_PLAIN) .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body"), makeRequest( request() .withPath(calculatePath("some_path")) .withMethod("POST") .withBody("{" + System.getProperty("line.separator") + " \"id\": 1," + System.getProperty("line.separator") + " \"extra ignored field\": \"some value\"," + System.getProperty("line.separator") + " \"name\": \"A green door\"," + System.getProperty("line.separator") + " \"price\": 12.50," + System.getProperty("line.separator") + " \"tags\": [\"home\", \"green\"]" + System.getProperty("line.separator") + "}"), headersToIgnore) ); // - in https assertEquals( response() .withHeader(HttpHeaders.CONTENT_TYPE, TEXT_PLAIN) .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body"), makeRequest( request() .withSecure(true) .withPath(calculatePath("some_path")) .withMethod("POST") .withBody("{" + System.getProperty("line.separator") + " \"id\": 1," + System.getProperty("line.separator") + " \"extra ignored array\": [\"one\", \"two\"]," + System.getProperty("line.separator") + " \"name\": \"A green door\"," + System.getProperty("line.separator") + " \"price\": 12.50," + System.getProperty("line.separator") + " \"tags\": [\"home\", \"green\"]" + System.getProperty("line.separator") + "}"), headersToIgnore) ); } @Test public void shouldReturnResponseByMatchingBodyWithJsonWithCharsetUTF8() { // when mockServerClient .when( request() .withBody(json("{" + System.getProperty("line.separator") + " \"ταυτότητα\": 1," + System.getProperty("line.separator") + " \"όνομα\": \"μια πράσινη πόρτα\"," + System.getProperty("line.separator") + " \"τιμή\": 12.50," + System.getProperty("line.separator") + " \"ετικέτες\": [\"σπίτι\", \"πράσινος\"]" + System.getProperty("line.separator") + "}", Charsets.UTF_16, MatchType.ONLY_MATCHING_FIELDS)), exactly(2) ) .respond( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body") ); // then // - in http assertEquals( response() .withHeader(HttpHeaders.CONTENT_TYPE, TEXT_PLAIN) .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body"), makeRequest( request() .withPath(calculatePath("some_path")) .withMethod("POST") .withBody(json("{" + System.getProperty("line.separator") + " \"ταυτότητα\": 1," + System.getProperty("line.separator") + " \"επιπλέον αγνοούνται τομέα\": \"κάποια αξία\"," + System.getProperty("line.separator") + " \"όνομα\": \"μια πράσινη πόρτα\"," + System.getProperty("line.separator") + " \"τιμή\": 12.50," + System.getProperty("line.separator") + " \"ετικέτες\": [\"σπίτι\", \"πράσινος\"]" + System.getProperty("line.separator") + "}", Charsets.UTF_16, MatchType.ONLY_MATCHING_FIELDS)), headersToIgnore) ); // - in https assertEquals( response() .withHeader(HttpHeaders.CONTENT_TYPE, TEXT_PLAIN) .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body"), makeRequest( request() .withSecure(true) .withPath(calculatePath("some_path")) .withMethod("POST") .withBody(json("{" + System.getProperty("line.separator") + " \"ταυτότητα\": 1," + System.getProperty("line.separator") + " \"επιπλέον αγνοούνται σειρά\": [\"ένας\", \"δυο\"]," + System.getProperty("line.separator") + " \"όνομα\": \"μια πράσινη πόρτα\"," + System.getProperty("line.separator") + " \"τιμή\": 12.50," + System.getProperty("line.separator") + " \"ετικέτες\": [\"σπίτι\", \"πράσινος\"]" + System.getProperty("line.separator") + "}", Charsets.UTF_16, MatchType.ONLY_MATCHING_FIELDS)), headersToIgnore) ); } @Test public void shouldReturnResponseByMatchingBodyWithJsonWithContentTypeHeader() { // when mockServerClient .when( request() .withBody(json("{" + System.getProperty("line.separator") + " \"ταυτότητα\": 1," + System.getProperty("line.separator") + " \"όνομα\": \"μια πράσινη πόρτα\"," + System.getProperty("line.separator") + " \"τιμή\": 12.50," + System.getProperty("line.separator") + " \"ετικέτες\": [\"σπίτι\", \"πράσινος\"]" + System.getProperty("line.separator") + "}", Charsets.UTF_16, MatchType.ONLY_MATCHING_FIELDS)), exactly(2) ) .respond( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body") ); // then // - in http assertEquals( response() .withHeader(HttpHeaders.CONTENT_TYPE, TEXT_PLAIN) .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body"), makeRequest( request() .withHeader(HttpHeaders.CONTENT_TYPE, MediaType.create("text", "plain").withCharset(Charsets.UTF_16).toString()) .withPath(calculatePath("some_path")) .withMethod("POST") .withBody(json("{" + System.getProperty("line.separator") + " \"ταυτότητα\": 1," + System.getProperty("line.separator") + " \"επιπλέον αγνοούνται τομέα\": \"κάποια αξία\"," + System.getProperty("line.separator") + " \"όνομα\": \"μια πράσινη πόρτα\"," + System.getProperty("line.separator") + " \"τιμή\": 12.50," + System.getProperty("line.separator") + " \"ετικέτες\": [\"σπίτι\", \"πράσινος\"]" + System.getProperty("line.separator") + "}")), headersToIgnore) ); // - in https assertEquals( response() .withHeader(HttpHeaders.CONTENT_TYPE, TEXT_PLAIN) .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body"), makeRequest( request() .withSecure(true) .withHeader(HttpHeaders.CONTENT_TYPE, MediaType.create("text", "plain").withCharset(Charsets.UTF_16).toString()) .withPath(calculatePath("some_path")) .withMethod("POST") .withBody(json("{" + System.getProperty("line.separator") + " \"ταυτότητα\": 1," + System.getProperty("line.separator") + " \"επιπλέον αγνοούνται σειρά\": [\"ένας\", \"δυο\"]," + System.getProperty("line.separator") + " \"όνομα\": \"μια πράσινη πόρτα\"," + System.getProperty("line.separator") + " \"τιμή\": 12.50," + System.getProperty("line.separator") + " \"ετικέτες\": [\"σπίτι\", \"πράσινος\"]" + System.getProperty("line.separator") + "}")), headersToIgnore) ); } @Test public void shouldReturnResponseByMatchingBodyWithJsonWithMatchType() { // when mockServerClient .when( request() .withBody(json("{" + System.getProperty("line.separator") + " \"id\": 1," + System.getProperty("line.separator") + " \"name\": \"A green door\"," + System.getProperty("line.separator") + " \"price\": 12.50," + System.getProperty("line.separator") + " \"tags\": [\"home\", \"green\"]" + System.getProperty("line.separator") + "}", MatchType.ONLY_MATCHING_FIELDS)), exactly(2) ) .respond( response() .withBody("some_body") ); // then // - in http assertEquals( response("some_body").withHeader(HttpHeaders.CONTENT_TYPE, TEXT_PLAIN), makeRequest( request() .withPath(calculatePath("some_path")) .withMethod("POST") .withBody("{" + System.getProperty("line.separator") + " \"id\": 1," + System.getProperty("line.separator") + " \"extra field\": \"some value\"," + System.getProperty("line.separator") + " \"name\": \"A green door\"," + System.getProperty("line.separator") + " \"price\": 12.50," + System.getProperty("line.separator") + " \"tags\": [\"home\", \"green\"]" + System.getProperty("line.separator") + "}"), headersToIgnore) ); // - in https assertEquals( response("some_body").withHeader(HttpHeaders.CONTENT_TYPE, TEXT_PLAIN), makeRequest( request() .withSecure(true) .withPath(calculatePath("some_path")) .withMethod("POST") .withBody("{" + System.getProperty("line.separator") + " \"id\": 1," + System.getProperty("line.separator") + " \"extra field\": \"some value\"," + System.getProperty("line.separator") + " \"name\": \"A green door\"," + System.getProperty("line.separator") + " \"price\": 12.50," + System.getProperty("line.separator") + " \"tags\": [\"home\", \"green\"]" + System.getProperty("line.separator") + "}"), headersToIgnore) ); } @Test public void shouldReturnResponseByMatchingBodyWithJsonSchema() { // when mockServerClient.when(request().withBody(jsonSchema("{" + System.getProperty("line.separator") + " \"$schema\": \"http://json-schema.org/draft-04/schema#\"," + System.getProperty("line.separator") + " \"title\": \"Product\"," + System.getProperty("line.separator") + " \"description\": \"A product from Acme's catalog\"," + System.getProperty("line.separator") + " \"type\": \"object\"," + System.getProperty("line.separator") + " \"properties\": {" + System.getProperty("line.separator") + " \"id\": {" + System.getProperty("line.separator") + " \"description\": \"The unique identifier for a product\"," + System.getProperty("line.separator") + " \"type\": \"integer\"" + System.getProperty("line.separator") + " }," + System.getProperty("line.separator") + " \"name\": {" + System.getProperty("line.separator") + " \"description\": \"Name of the product\"," + System.getProperty("line.separator") + " \"type\": \"string\"" + System.getProperty("line.separator") + " }," + System.getProperty("line.separator") + " \"price\": {" + System.getProperty("line.separator") + " \"type\": \"number\"," + System.getProperty("line.separator") + " \"minimum\": 0," + System.getProperty("line.separator") + " \"exclusiveMinimum\": true" + System.getProperty("line.separator") + " }," + System.getProperty("line.separator") + " \"tags\": {" + System.getProperty("line.separator") + " \"type\": \"array\"," + System.getProperty("line.separator") + " \"items\": {" + System.getProperty("line.separator") + " \"type\": \"string\"" + System.getProperty("line.separator") + " }," + System.getProperty("line.separator") + " \"minItems\": 1," + System.getProperty("line.separator") + " \"uniqueItems\": true" + System.getProperty("line.separator") + " }" + System.getProperty("line.separator") + " }," + System.getProperty("line.separator") + " \"required\": [\"id\", \"name\", \"price\"]" + System.getProperty("line.separator") + "}")), exactly(2)).respond(response().withBody("some_body")); // then // - in http assertEquals( response() .withHeader(HttpHeaders.CONTENT_TYPE, TEXT_PLAIN) .withStatusCode(HttpStatusCode.OK_200.code()) .withBody("some_body"), makeRequest( request() .withPath(calculatePath("some_path")) .withMethod("POST") .withBody("{" + System.getProperty("line.separator") + " \"id\": 1," + System.getProperty("line.separator") + " \"name\": \"A green door\"," + System.getProperty("line.separator") + " \"price\": 12.50," + System.getProperty("line.separator") + " \"tags\": [\"home\", \"green\"]" + System.getProperty("line.separator") + "}"), headersToIgnore) ); // - in https assertEquals( response() .withHeader(HttpHeaders.CONTENT_TYPE, TEXT_PLAIN) .withStatusCode(HttpStatusCode.OK_200.code()) .withBody("some_body"), makeRequest( request() .withSecure(true) .withPath(calculatePath("some_path")) .withMethod("POST") .withBody("{" + System.getProperty("line.separator") + " \"id\": 1," + System.getProperty("line.separator") + " \"name\": \"A green door\"," + System.getProperty("line.separator") + " \"price\": 12.50," + System.getProperty("line.separator") + " \"tags\": [\"home\", \"green\"]" + System.getProperty("line.separator") + "}"), headersToIgnore) ); } @Test public void shouldReturnPDFResponseByMatchingPath() throws IOException { // when byte[] pdfBytes = IOUtils.toByteArray(getClass().getClassLoader().getResourceAsStream("test.pdf")); mockServerClient .when( request() .withPath(calculatePath("ws/rest/user/[0-9]+/document/[0-9]+\\.pdf")) ) .respond( response() .withStatusCode(HttpStatusCode.OK_200.code()) .withHeaders( header(HttpHeaders.CONTENT_TYPE, MediaType.PDF.toString()), header(HttpHeaders.CONTENT_DISPOSITION, "form-data; name=\"test.pdf\"; filename=\"test.pdf\""), header(HttpHeaders.CACHE_CONTROL, "must-revalidate, post-check=0, pre-check=0") ) .withBody(binary(pdfBytes)) ); // then // - in http assertEquals( response() .withStatusCode(HttpStatusCode.OK_200.code()) .withHeaders( header(HttpHeaders.CONTENT_DISPOSITION, "form-data; name=\"test.pdf\"; filename=\"test.pdf\""), header(HttpHeaders.CACHE_CONTROL, "must-revalidate, post-check=0, pre-check=0"), header(HttpHeaders.CONTENT_TYPE, MediaType.PDF.toString()) ) .withBody(binary(pdfBytes)), makeRequest( request() .withPath(calculatePath("ws/rest/user/1/document/2.pdf")) .withMethod("GET"), headersToIgnore) ); // - in https assertEquals( response() .withStatusCode(HttpStatusCode.OK_200.code()) .withHeaders( header(HttpHeaders.CONTENT_DISPOSITION, "form-data; name=\"test.pdf\"; filename=\"test.pdf\""), header(HttpHeaders.CACHE_CONTROL, "must-revalidate, post-check=0, pre-check=0"), header(HttpHeaders.CONTENT_TYPE, MediaType.PDF.toString()) ) .withBody(binary(pdfBytes)), makeRequest( request() .withSecure(true) .withPath(calculatePath("ws/rest/user/1/document/2.pdf")) .withMethod("GET"), headersToIgnore) ); } @Test public void shouldReturnPNGResponseByMatchingPath() throws IOException { // when byte[] pngBytes = IOUtils.toByteArray(getClass().getClassLoader().getResourceAsStream("test.png")); mockServerClient .when( request() .withPath(calculatePath("ws/rest/user/[0-9]+/icon/[0-9]+\\.png")) ) .respond( response() .withStatusCode(HttpStatusCode.OK_200.code()) .withHeaders( header(HttpHeaders.CONTENT_TYPE, MediaType.PNG.toString()), header(HttpHeaders.CONTENT_DISPOSITION, "form-data; name=\"test.png\"; filename=\"test.png\"") ) .withBody(binary(pngBytes)) ); // then // - in http assertEquals( response() .withStatusCode(HttpStatusCode.OK_200.code()) .withHeaders( header(HttpHeaders.CONTENT_DISPOSITION, "form-data; name=\"test.png\"; filename=\"test.png\""), header(HttpHeaders.CONTENT_TYPE, MediaType.PNG.toString()) ) .withBody(binary(pngBytes)), makeRequest( request() .withPath(calculatePath("ws/rest/user/1/icon/1.png")) .withMethod("GET"), headersToIgnore) ); // - in https assertEquals( response() .withStatusCode(HttpStatusCode.OK_200.code()) .withHeaders( header(HttpHeaders.CONTENT_DISPOSITION, "form-data; name=\"test.png\"; filename=\"test.png\""), header(HttpHeaders.CONTENT_TYPE, MediaType.PNG.toString()) ) .withBody(binary(pngBytes)), makeRequest( request() .withSecure(true) .withPath(calculatePath("ws/rest/user/1/icon/1.png")) .withMethod("GET"), headersToIgnore) ); } @Test public void shouldReturnPDFResponseByMatchingBinaryPDFBody() throws IOException { // when byte[] pdfBytes = IOUtils.toByteArray(getClass().getClassLoader().getResourceAsStream("test.pdf")); mockServerClient .when( request().withBody(binary(pdfBytes)) ) .respond( response() .withStatusCode(HttpStatusCode.OK_200.code()) .withHeaders( header(HttpHeaders.CONTENT_TYPE, MediaType.PDF.toString()), header(HttpHeaders.CONTENT_DISPOSITION, "form-data; name=\"test.pdf\"; filename=\"test.pdf\""), header(HttpHeaders.CACHE_CONTROL, "must-revalidate, post-check=0, pre-check=0") ) .withBody(binary(pdfBytes)) ); // then // - in http assertEquals( response() .withStatusCode(HttpStatusCode.OK_200.code()) .withHeaders( header(HttpHeaders.CONTENT_DISPOSITION, "form-data; name=\"test.pdf\"; filename=\"test.pdf\""), header(HttpHeaders.CACHE_CONTROL, "must-revalidate, post-check=0, pre-check=0"), header(HttpHeaders.CONTENT_TYPE, MediaType.PDF.toString()) ) .withBody(binary(pdfBytes)), makeRequest( request() .withPath(calculatePath("ws/rest/user/1/document/2.pdf")) .withBody(binary(pdfBytes)) .withMethod("POST"), headersToIgnore) ); // - in https assertEquals( response() .withStatusCode(HttpStatusCode.OK_200.code()) .withHeaders( header(HttpHeaders.CONTENT_DISPOSITION, "form-data; name=\"test.pdf\"; filename=\"test.pdf\""), header(HttpHeaders.CACHE_CONTROL, "must-revalidate, post-check=0, pre-check=0"), header(HttpHeaders.CONTENT_TYPE, MediaType.PDF.toString()) ) .withBody(binary(pdfBytes)), makeRequest( request() .withSecure(true) .withPath(calculatePath("ws/rest/user/1/document/2.pdf")) .withBody(binary(pdfBytes)) .withMethod("POST"), headersToIgnore) ); } @Test public void shouldReturnPNGResponseByMatchingBinaryPNGBody() throws IOException { // when byte[] pngBytes = IOUtils.toByteArray(getClass().getClassLoader().getResourceAsStream("test.png")); mockServerClient .when( request().withBody(binary(pngBytes)) ) .respond( response() .withStatusCode(HttpStatusCode.OK_200.code()) .withHeaders( header(HttpHeaders.CONTENT_TYPE, MediaType.PNG.toString()), header(HttpHeaders.CONTENT_DISPOSITION, "form-data; name=\"test.png\"; filename=\"test.png\"") ) .withBody(binary(pngBytes)) ); // then // - in http assertEquals( response() .withStatusCode(HttpStatusCode.OK_200.code()) .withHeaders( header(HttpHeaders.CONTENT_DISPOSITION, "form-data; name=\"test.png\"; filename=\"test.png\""), header(HttpHeaders.CONTENT_TYPE, MediaType.PNG.toString()) ) .withBody(binary(pngBytes)), makeRequest( request() .withPath(calculatePath("ws/rest/user/1/icon/1.png")) .withBody(binary(pngBytes)) .withMethod("POST"), headersToIgnore) ); // - in https assertEquals( response() .withStatusCode(HttpStatusCode.OK_200.code()) .withHeaders( header(HttpHeaders.CONTENT_DISPOSITION, "form-data; name=\"test.png\"; filename=\"test.png\""), header(HttpHeaders.CONTENT_TYPE, MediaType.PNG.toString()) ) .withBody(binary(pngBytes)), makeRequest( request() .withSecure(true) .withPath(calculatePath("ws/rest/user/1/icon/1.png")) .withBody(binary(pngBytes)) .withMethod("POST"), headersToIgnore) ); } @Test public void shouldReturnResponseForExpectationWithDelay() { // when mockServerClient .when( request() .withPath(calculatePath("some_path1")) ) .respond( response() .withBody("some_body1") .withDelay(new Delay(TimeUnit.MILLISECONDS, 10)) ); mockServerClient .when( request() .withPath(calculatePath("some_path2")) ) .respond( response() .withBody("some_body2") .withDelay(new Delay(TimeUnit.MILLISECONDS, 20)) ); // then // - in http assertEquals( response() .withHeader(HttpHeaders.CONTENT_TYPE, TEXT_PLAIN) .withStatusCode(HttpStatusCode.OK_200.code()) .withBody("some_body2"), makeRequest( request() .withPath(calculatePath("some_path2")), headersToIgnore) ); assertEquals( response() .withHeader(HttpHeaders.CONTENT_TYPE, TEXT_PLAIN) .withStatusCode(HttpStatusCode.OK_200.code()) .withBody("some_body1"), makeRequest( request() .withPath(calculatePath("some_path1")), headersToIgnore) ); // - in https assertEquals( response() .withHeader(HttpHeaders.CONTENT_TYPE, TEXT_PLAIN) .withStatusCode(HttpStatusCode.OK_200.code()) .withBody("some_body2"), makeRequest( request() .withSecure(true) .withPath(calculatePath("some_path2")), headersToIgnore) ); assertEquals( response() .withHeader(HttpHeaders.CONTENT_TYPE, TEXT_PLAIN) .withStatusCode(HttpStatusCode.OK_200.code()) .withBody("some_body1"), makeRequest( request() .withSecure(true) .withPath(calculatePath("some_path1")), headersToIgnore) ); } @Test public void shouldReturnResponseByMatchingPathAndMethod() { // when mockServerClient .when( request() .withMethod("GET") .withPath(calculatePath("some_pathRequest")) ) .respond( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body_response") ); // then // - in http assertEquals( response() .withHeader(HttpHeaders.CONTENT_TYPE, TEXT_PLAIN) .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body_response"), makeRequest( request() .withMethod("GET") .withPath(calculatePath("some_pathRequest")) .withQueryStringParameters( param("queryStringParameterOneName", "queryStringParameterOneValue"), param("queryStringParameterTwoName", "queryStringParameterTwoValue") ) .withHeaders(header("headerNameRequest", "headerValueRequest")) .withCookies(cookie("cookieNameRequest", "cookieValueRequest")), headersToIgnore) ); // - in https assertEquals( response() .withHeader(HttpHeaders.CONTENT_TYPE, TEXT_PLAIN) .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body_response"), makeRequest( request() .withMethod("GET") .withSecure(true) .withPath(calculatePath("some_pathRequest")) .withQueryStringParameters( param("queryStringParameterOneName", "queryStringParameterOneValue"), param("queryStringParameterTwoName", "queryStringParameterTwoValue") ) .withHeaders(header("headerNameRequest", "headerValueRequest")) .withCookies(cookie("cookieNameRequest", "cookieValueRequest")), headersToIgnore) ); } @Test public void shouldReturnResponseByNotMatchingPathWithNotOperator() { // when mockServerClient .when( request() .withPath(not(calculatePath("some_path"))) ) .respond( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body_response") ); // then // - in http assertEquals( response() .withHeader(HttpHeaders.CONTENT_TYPE, TEXT_PLAIN) .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body_response"), makeRequest( request() .withPath(calculatePath("some_other_path")), headersToIgnore) ); // - in https assertEquals( response() .withHeader(HttpHeaders.CONTENT_TYPE, TEXT_PLAIN) .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body_response"), makeRequest( request() .withPath(calculatePath("some_other_path")), headersToIgnore) ); } @Test public void shouldReturnResponseByNotMatchingMethodWithNotOperator() { // when mockServerClient .when( request() .withMethod(not("GET")) ) .respond( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body_response") ); // then // - in http assertEquals( response() .withHeader(HttpHeaders.CONTENT_TYPE, TEXT_PLAIN) .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body_response"), makeRequest( request() .withMethod("POST"), headersToIgnore) ); // - in https assertEquals( response() .withHeader(HttpHeaders.CONTENT_TYPE, TEXT_PLAIN) .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body_response"), makeRequest( request() .withMethod("POST"), headersToIgnore) ); } @Test public void shouldReturnResponseByMatchingPathAndMethodAndBody() { // when mockServerClient .when( request() .withMethod("POST") .withPath(calculatePath("some_pathRequest")) .withBody("some_bodyRequest") ) .respond( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body_response") .withHeaders(header("headerNameResponse", "headerValueResponse")) ); // then // - in http assertEquals( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body_response") .withHeaders( header("headerNameResponse", "headerValueResponse"), header(HttpHeaders.CONTENT_TYPE, TEXT_PLAIN) ), makeRequest( request() .withMethod("POST") .withPath(calculatePath("some_pathRequest")) .withQueryStringParameters( param("queryStringParameterOneName", "queryStringParameterOneValue"), param("queryStringParameterTwoName", "queryStringParameterTwoValue") ) .withBody("some_bodyRequest") .withHeaders(header("headerNameRequest", "headerValueRequest")) .withCookies(cookie("cookieNameRequest", "cookieValueRequest")), headersToIgnore) ); // - in https assertEquals( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body_response") .withHeaders( header("headerNameResponse", "headerValueResponse"), header(HttpHeaders.CONTENT_TYPE, TEXT_PLAIN) ), makeRequest( request() .withMethod("POST") .withSecure(true) .withPath(calculatePath("some_pathRequest")) .withQueryStringParameters( param("queryStringParameterOneName", "queryStringParameterOneValue"), param("queryStringParameterTwoName", "queryStringParameterTwoValue") ) .withBody("some_bodyRequest") .withHeaders(header("headerNameRequest", "headerValueRequest")) .withCookies(cookie("cookieNameRequest", "cookieValueRequest")), headersToIgnore) ); } @Test public void shouldReturnResponseByMatchingPathAndMethodAndQueryStringParameters() { // when mockServerClient .when( request() .withMethod("GET") .withPath(calculatePath("some_pathRequest")) .withQueryStringParameters( param("queryStringParameterOneName", "queryStringParameterOneValue"), param("queryStringParameterTwoName", "queryStringParameterTwoValue") ) ) .respond( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body_response") .withCookies(cookie("cookieNameResponse", "cookieValueResponse")) ); // then // - in http assertEquals( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body_response") .withCookies(cookie("cookieNameResponse", "cookieValueResponse")) .withHeaders( header("Set-Cookie", "cookieNameResponse=cookieValueResponse"), header(HttpHeaders.CONTENT_TYPE, TEXT_PLAIN) ), makeRequest( request() .withMethod("GET") .withPath(calculatePath("some_pathRequest")) .withQueryStringParameters( param("queryStringParameterOneName", "queryStringParameterOneValue"), param("queryStringParameterTwoName", "queryStringParameterTwoValue") ) .withHeaders(header("headerNameRequest", "headerValueRequest")) .withCookies(cookie("cookieNameRequest", "cookieValueRequest")), headersToIgnore) ); // - in https assertEquals( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body_response") .withCookies(cookie("cookieNameResponse", "cookieValueResponse")) .withHeaders( header("Set-Cookie", "cookieNameResponse=cookieValueResponse"), header(HttpHeaders.CONTENT_TYPE, TEXT_PLAIN) ), makeRequest( request() .withMethod("GET") .withSecure(true) .withPath(calculatePath("some_pathRequest")) .withQueryStringParameters( param("queryStringParameterOneName", "queryStringParameterOneValue"), param("queryStringParameterTwoName", "queryStringParameterTwoValue") ) .withHeaders(header("headerNameRequest", "headerValueRequest")) .withCookies(cookie("cookieNameRequest", "cookieValueRequest")), headersToIgnore) ); } @Test public void shouldReturnResponseByMatchingPathAndMethodAndHeaders() { // when mockServerClient .when( request() .withMethod("GET") .withPath(calculatePath("some_pathRequest")) .withHeaders( header("requestHeaderNameOne", "requestHeaderValueOne_One", "requestHeaderValueOne_Two"), header("requestHeaderNameTwo", "requestHeaderValueTwo") ) ) .respond( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body_response") .withCookies(cookie("cookieNameResponse", "cookieValueResponse")) ); // then // - in http assertEquals( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body_response") .withCookies(cookie("cookieNameResponse", "cookieValueResponse")) .withHeaders( header("Set-Cookie", "cookieNameResponse=cookieValueResponse"), header(HttpHeaders.CONTENT_TYPE, TEXT_PLAIN) ), makeRequest( request() .withMethod("GET") .withPath(calculatePath("some_pathRequest")) .withHeaders( header("requestHeaderNameOne", "requestHeaderValueOne_One", "requestHeaderValueOne_Two"), header("requestHeaderNameTwo", "requestHeaderValueTwo") ) .withCookies(cookie("cookieNameRequest", "cookieValueRequest")), headersToIgnore) ); // - in https assertEquals( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body_response") .withCookies(cookie("cookieNameResponse", "cookieValueResponse")) .withHeaders( header("Set-Cookie", "cookieNameResponse=cookieValueResponse"), header(HttpHeaders.CONTENT_TYPE, TEXT_PLAIN) ), makeRequest( request() .withMethod("GET") .withSecure(true) .withPath(calculatePath("some_pathRequest")) .withHeaders( header("requestHeaderNameOne", "requestHeaderValueOne_One", "requestHeaderValueOne_Two"), header("requestHeaderNameTwo", "requestHeaderValueTwo") ) .withCookies(cookie("cookieNameRequest", "cookieValueRequest")), headersToIgnore) ); } @Test public void shouldReturnResponseByMatchingPathAndMethodAndCookies() { // when mockServerClient .when( request() .withMethod("GET") .withPath(calculatePath("some_pathRequest")) .withCookies( cookie("requestCookieNameOne", "requestCookieValueOne"), cookie("requestCookieNameTwo", "requestCookieValueTwo") ) ) .respond( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body_response") .withCookies( cookie("responseCookieNameOne", "responseCookieValueOne"), cookie("responseCookieNameTwo", "responseCookieValueTwo") ) ); // then // - in http - cookie objects assertEquals( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body_response") .withCookies( cookie("responseCookieNameOne", "responseCookieValueOne"), cookie("responseCookieNameTwo", "responseCookieValueTwo") ) .withHeaders( header("Set-Cookie", "responseCookieNameOne=responseCookieValueOne", "responseCookieNameTwo=responseCookieValueTwo"), header(HttpHeaders.CONTENT_TYPE, TEXT_PLAIN) ), makeRequest( request() .withMethod("GET") .withPath(calculatePath("some_pathRequest")) .withHeaders( header("headerNameRequest", "headerValueRequest"), header(HttpHeaders.CONTENT_TYPE, TEXT_PLAIN) ) .withCookies( cookie("requestCookieNameOne", "requestCookieValueOne"), cookie("requestCookieNameTwo", "requestCookieValueTwo") ), headersToIgnore) ); // - in http - cookie header assertEquals( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body_response") .withCookies( cookie("responseCookieNameOne", "responseCookieValueOne"), cookie("responseCookieNameTwo", "responseCookieValueTwo") ) .withHeaders( header("Set-Cookie", "responseCookieNameOne=responseCookieValueOne", "responseCookieNameTwo=responseCookieValueTwo"), header(HttpHeaders.CONTENT_TYPE, TEXT_PLAIN) ), makeRequest( request() .withMethod("GET") .withPath(calculatePath("some_pathRequest")) .withHeaders( header("headerNameRequest", "headerValueRequest"), header("Cookie", "requestCookieNameOne=requestCookieValueOne; requestCookieNameTwo=requestCookieValueTwo") ), headersToIgnore) ); // - in https - cookie objects assertEquals( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body_response") .withCookies( cookie("responseCookieNameOne", "responseCookieValueOne"), cookie("responseCookieNameTwo", "responseCookieValueTwo") ) .withHeaders( header("Set-Cookie", "responseCookieNameOne=responseCookieValueOne", "responseCookieNameTwo=responseCookieValueTwo"), header(HttpHeaders.CONTENT_TYPE, TEXT_PLAIN) ), makeRequest( request() .withMethod("GET") .withSecure(true) .withPath(calculatePath("some_pathRequest")) .withHeaders( header("headerNameRequest", "headerValueRequest") ) .withCookies( cookie("requestCookieNameOne", "requestCookieValueOne"), cookie("requestCookieNameTwo", "requestCookieValueTwo") ), headersToIgnore) ); // - in https - cookie header assertEquals( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body_response") .withCookies( cookie("responseCookieNameOne", "responseCookieValueOne"), cookie("responseCookieNameTwo", "responseCookieValueTwo") ) .withHeaders( header("Set-Cookie", "responseCookieNameOne=responseCookieValueOne", "responseCookieNameTwo=responseCookieValueTwo"), header(HttpHeaders.CONTENT_TYPE, TEXT_PLAIN) ), makeRequest( request() .withMethod("GET") .withSecure(true) .withPath(calculatePath("some_pathRequest")) .withHeaders( header("headerNameRequest", "headerValueRequest"), header("Cookie", "requestCookieNameOne=requestCookieValueOne; requestCookieNameTwo=requestCookieValueTwo") ), headersToIgnore) ); } @Test public void shouldReturnResponseByMatchingPathAndMethodAndQueryStringParametersAndBodyParameters() { // when mockServerClient .when( request() .withMethod("POST") .withPath(calculatePath("some_pathRequest")) .withQueryStringParameters( param("queryStringParameterOneName", "queryStringParameterOneValueOne", "queryStringParameterOneValueTwo"), param("queryStringParameterTwoName", "queryStringParameterTwoValue") ) .withBody(params(param("bodyParameterName", "bodyParameterValue"))) ) .respond( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body") ); // then // - in http - url query string assertEquals( response() .withHeader(HttpHeaders.CONTENT_TYPE, TEXT_PLAIN) .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body"), makeRequest( request() .withMethod("POST") .withPath(calculatePath("some_pathRequest")) .withQueryStringParameters( param("queryStringParameterOneName", "queryStringParameterOneValueOne", "queryStringParameterOneValueTwo"), param("queryStringParameterTwoName", "queryStringParameterTwoValue") ) .withBody(params(param("bodyParameterName", "bodyParameterValue"))), headersToIgnore) ); // - in https - query string parameter objects assertEquals( response() .withHeader(HttpHeaders.CONTENT_TYPE, TEXT_PLAIN) .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body"), makeRequest( request() .withSecure(true) .withMethod("POST") .withPath(calculatePath("some_pathRequest")) .withQueryStringParameters( param("queryStringParameterOneName", "queryStringParameterOneValueOne", "queryStringParameterOneValueTwo"), param("queryStringParameterTwoName", "queryStringParameterTwoValue") ) .withBody(params(param("bodyParameterName", "bodyParameterValue"))), headersToIgnore) ); } @Test public void shouldReturnResponseByMatchingPathAndMethodAndQueryStringParametersAndBody() { // when mockServerClient .when( request() .withMethod("POST") .withPath(calculatePath("some_pathRequest")) .withQueryStringParameters( param("queryStringParameterOneName", "queryStringParameterOneValueOne", "queryStringParameterOneValueTwo"), param("queryStringParameterTwoName", "queryStringParameterTwoValue") ) .withBody("some_bodyRequest") ) .respond( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body_response") .withHeaders(header("headerNameResponse", "headerValueResponse")) .withCookies(cookie("cookieNameResponse", "cookieValueResponse")) ); // then // - in http - url query string assertEquals( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body_response") .withCookies(cookie("cookieNameResponse", "cookieValueResponse")) .withHeaders( header("headerNameResponse", "headerValueResponse"), header("Set-Cookie", "cookieNameResponse=cookieValueResponse"), header(HttpHeaders.CONTENT_TYPE, TEXT_PLAIN) ), makeRequest( request() .withMethod("POST") .withPath(calculatePath("some_pathRequest")) .withQueryStringParameters( param("queryStringParameterOneName", "queryStringParameterOneValueOne", "queryStringParameterOneValueTwo"), param("queryStringParameterTwoName", "queryStringParameterTwoValue") ) .withBody("some_bodyRequest") .withHeaders(header("headerNameRequest", "headerValueRequest")) .withCookies(cookie("cookieNameRequest", "cookieValueRequest")), headersToIgnore) ); // - in http - query string parameter objects assertEquals( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body_response") .withCookies(cookie("cookieNameResponse", "cookieValueResponse")) .withHeaders( header("headerNameResponse", "headerValueResponse"), header("Set-Cookie", "cookieNameResponse=cookieValueResponse"), header(HttpHeaders.CONTENT_TYPE, TEXT_PLAIN) ), makeRequest( request() .withMethod("POST") .withPath(calculatePath("some_pathRequest")) .withQueryStringParameters( param("queryStringParameterOneName", "queryStringParameterOneValueOne", "queryStringParameterOneValueTwo"), param("queryStringParameterTwoName", "queryStringParameterTwoValue") ) .withBody("some_bodyRequest") .withHeaders(header("headerNameRequest", "headerValueRequest")) .withCookies(cookie("cookieNameRequest", "cookieValueRequest")), headersToIgnore) ); // - in https - url string and query string parameter objects assertEquals( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body_response") .withCookies(cookie("cookieNameResponse", "cookieValueResponse")) .withHeaders( header("headerNameResponse", "headerValueResponse"), header("Set-Cookie", "cookieNameResponse=cookieValueResponse"), header(HttpHeaders.CONTENT_TYPE, TEXT_PLAIN) ), makeRequest( request() .withMethod("POST") .withPath(calculatePath("some_pathRequest")) .withQueryStringParameters( param("queryStringParameterOneName", "queryStringParameterOneValueOne", "queryStringParameterOneValueTwo"), param("queryStringParameterTwoName", "queryStringParameterTwoValue") ) .withBody("some_bodyRequest") .withHeaders(header("headerNameRequest", "headerValueRequest")) .withCookies(cookie("cookieNameRequest", "cookieValueRequest")), headersToIgnore) ); } @Test public void shouldReturnResponseByMatchingPathAndMethodAndBodyParameters() { // when mockServerClient .when( request() .withMethod("POST") .withPath(calculatePath("some_pathRequest")) .withBody(params( param("bodyParameterOneName", "Parameter One Value One", "Parameter One Value Two"), param("bodyParameterTwoName", "Parameter Two") )) ) .respond( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body_response") .withHeaders(header("headerNameResponse", "headerValueResponse")) .withCookies(cookie("cookieNameResponse", "cookieValueResponse")) ); // then // - in http - body string assertEquals( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body_response") .withCookies(cookie("cookieNameResponse", "cookieValueResponse")) .withHeaders( header("headerNameResponse", "headerValueResponse"), header("Set-Cookie", "cookieNameResponse=cookieValueResponse"), header(HttpHeaders.CONTENT_TYPE, TEXT_PLAIN) ), makeRequest( request() .withMethod("POST") .withPath(calculatePath("some_pathRequest")) .withBody(new StringBody("bodyParameterOneName=Parameter+One+Value+One" + "&bodyParameterOneName=Parameter+One+Value+Two" + "&bodyParameterTwoName=Parameter+Two")) .withHeaders(header("headerNameRequest", "headerValueRequest")) .withCookies(cookie("cookieNameRequest", "cookieValueRequest")), headersToIgnore) ); // - in http - body parameter objects assertEquals( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body_response") .withCookies(cookie("cookieNameResponse", "cookieValueResponse")) .withHeaders( header("headerNameResponse", "headerValueResponse"), header("Set-Cookie", "cookieNameResponse=cookieValueResponse"), header(HttpHeaders.CONTENT_TYPE, TEXT_PLAIN) ), makeRequest( request() .withMethod("POST") .withPath(calculatePath("some_pathRequest")) .withBody(params( param("bodyParameterOneName", "Parameter One Value One", "Parameter One Value Two"), param("bodyParameterTwoName", "Parameter Two") )) .withHeaders(header("headerNameRequest", "headerValueRequest")) .withCookies(cookie("cookieNameRequest", "cookieValueRequest")), headersToIgnore) ); // - in https - url string and query string parameter objects assertEquals( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body_response") .withCookies(cookie("cookieNameResponse", "cookieValueResponse")) .withHeaders( header("headerNameResponse", "headerValueResponse"), header("Set-Cookie", "cookieNameResponse=cookieValueResponse"), header(HttpHeaders.CONTENT_TYPE, TEXT_PLAIN) ), makeRequest( request() .withMethod("POST") .withPath(calculatePath("some_pathRequest")) .withBody(params( param("bodyParameterOneName", "Parameter One Value One", "Parameter One Value Two"), param("bodyParameterTwoName", "Parameter Two") )) .withHeaders(header("headerNameRequest", "headerValueRequest")) .withCookies(cookie("cookieNameRequest", "cookieValueRequest")), headersToIgnore) ); } @Test public void shouldReturnResponseByMatchingPathAndMethodAndParametersAndHeadersAndCookies() { // when mockServerClient .when( request() .withMethod("PUT") .withPath(calculatePath("some_pathRequest")) .withBody(new StringBody("bodyParameterOneName=Parameter+One+Value+One" + "&bodyParameterOneName=Parameter+One+Value+Two" + "&bodyParameterTwoName=Parameter+Two")) .withHeaders(header("headerNameRequest", "headerValueRequest")) .withCookies(cookie("cookieNameRequest", "cookieValueRequest")) ) .respond( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body_response") .withHeaders(header("headerNameResponse", "headerValueResponse")) .withCookies(cookie("cookieNameResponse", "cookieValueResponse")) ); // then // - in http - body string assertEquals( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body_response") .withCookies(cookie("cookieNameResponse", "cookieValueResponse")) .withHeaders( header("headerNameResponse", "headerValueResponse"), header("Set-Cookie", "cookieNameResponse=cookieValueResponse"), header(HttpHeaders.CONTENT_TYPE, TEXT_PLAIN) ), makeRequest( request() .withMethod("PUT") .withPath(calculatePath("some_pathRequest")) .withBody(new StringBody("bodyParameterOneName=Parameter+One+Value+One" + "&bodyParameterOneName=Parameter+One+Value+Two" + "&bodyParameterTwoName=Parameter+Two")) .withHeaders( header("headerNameRequest", "headerValueRequest"), header("Cookie", "cookieNameRequest=cookieValueRequest") ), headersToIgnore) ); // - in http - body parameter objects assertEquals( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body_response") .withCookies(cookie("cookieNameResponse", "cookieValueResponse")) .withHeaders( header("headerNameResponse", "headerValueResponse"), header("Set-Cookie", "cookieNameResponse=cookieValueResponse"), header(HttpHeaders.CONTENT_TYPE, TEXT_PLAIN) ), makeRequest( request() .withMethod("PUT") .withPath(calculatePath("some_pathRequest")) .withBody(params( param("bodyParameterOneName", "Parameter One Value One", "Parameter One Value Two"), param("bodyParameterTwoName", "Parameter Two") )) .withHeaders(header("headerNameRequest", "headerValueRequest")) .withCookies(cookie("cookieNameRequest", "cookieValueRequest")), headersToIgnore) ); } @Test public void shouldReturnResponseByNotMatchingBodyParameterWithNotOperatorForNameAndValue() { // when mockServerClient .when( request() .withMethod("POST") .withPath(calculatePath("some_pathRequest")) .withBody(params( param(not("bodyParameterOneName"), not("Parameter One Value One"), not("Parameter One Value Two")), param("bodyParameterTwoName", "Parameter Two") )) ) .respond( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body_response") ); // then // wrong query string parameter name assertEquals( response() .withHeader(HttpHeaders.CONTENT_TYPE, TEXT_PLAIN) .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body_response"), makeRequest( request() .withMethod("POST") .withPath(calculatePath("some_pathRequest")) .withBody(params( param("OTHERBodyParameterOneName", "Parameter One Value One", "Parameter One Value Two"), param("bodyParameterTwoName", "Parameter Two") )) .withHeaders(header("headerNameRequest", "headerValueRequest")) .withCookies(cookie("cookieNameRequest", "cookieValueRequest")), headersToIgnore) ); // wrong query string parameter name assertEquals( response() .withHeader(HttpHeaders.CONTENT_TYPE, TEXT_PLAIN) .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body_response"), makeRequest( request() .withMethod("POST") .withPath(calculatePath("some_pathRequest")) .withBody(new StringBody("OTHERBodyParameterOneName=Parameter+One+Value+One" + "&OTHERBodyParameterOneName=Parameter+One+Value+Two" + "&bodyParameterTwoName=Parameter+Two")) .withHeaders(header("headerNameRequest", "headerValueRequest")) .withCookies(cookie("cookieNameRequest", "cookieValueRequest")), headersToIgnore) ); // wrong query string parameter value assertEquals( response() .withHeader(HttpHeaders.CONTENT_TYPE, TEXT_PLAIN) .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body_response"), makeRequest( request() .withMethod("POST") .withPath(calculatePath("some_pathRequest")) .withBody(params( param("bodyParameterOneName", "OTHER Parameter One Value One", "OTHER Parameter One Value Two"), param("bodyParameterTwoName", "Parameter Two") )) .withHeaders(header("headerNameRequest", "headerValueRequest")) .withCookies(cookie("cookieNameRequest", "cookieValueRequest")), headersToIgnore) ); // wrong query string parameter value assertEquals( response() .withHeader(HttpHeaders.CONTENT_TYPE, TEXT_PLAIN) .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body_response"), makeRequest( request() .withMethod("POST") .withPath(calculatePath("some_pathRequest")) .withBody(new StringBody("bodyParameterOneName=OTHER Parameter+One+Value+One" + "&bodyParameterOneName=OTHER Parameter+One+Value+Two" + "&bodyParameterTwoName=Parameter+Two")) .withHeaders(header("headerNameRequest", "headerValueRequest")) .withCookies(cookie("cookieNameRequest", "cookieValueRequest")), headersToIgnore) ); } @Test public void shouldReturnResponseByNotMatchingBodyParameterWithNotOperatorForName() { // when mockServerClient .when( request() .withMethod("POST") .withPath(calculatePath("some_pathRequest")) .withBody(params( param(not("bodyParameterOneName"), string("Parameter One Value One"), string("Parameter One Value Two")), param("bodyParameterTwoName", "Parameter Two") )) ) .respond( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body_response") ); // then // wrong query string parameter name assertEquals( response() .withHeader(HttpHeaders.CONTENT_TYPE, TEXT_PLAIN) .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body_response"), makeRequest( request() .withMethod("POST") .withPath(calculatePath("some_pathRequest")) .withBody(params( param("OTHERBodyParameterOneName", "Parameter One Value One", "Parameter One Value Two"), param("bodyParameterTwoName", "Parameter Two") )) .withHeaders(header("headerNameRequest", "headerValueRequest")) .withCookies(cookie("cookieNameRequest", "cookieValueRequest")), headersToIgnore) ); // wrong query string parameter name assertEquals( response() .withHeader(HttpHeaders.CONTENT_TYPE, TEXT_PLAIN) .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body_response"), makeRequest( request() .withMethod("POST") .withPath(calculatePath("some_pathRequest")) .withBody(new StringBody("OTHERBodyParameterOneName=Parameter+One+Value+One" + "&OTHERBodyParameterOneName=Parameter+One+Value+Two" + "&bodyParameterTwoName=Parameter+Two")) .withHeaders(header("headerNameRequest", "headerValueRequest")) .withCookies(cookie("cookieNameRequest", "cookieValueRequest")), headersToIgnore) ); } @Test public void shouldReturnResponseByNotMatchingBodyParameterWithNotOperatorForValue() { // when mockServerClient .when( request() .withMethod("POST") .withPath(calculatePath("some_pathRequest")) .withBody(params( param(string("bodyParameterOneName"), not("Parameter One Value One"), not("Parameter One Value Two")), param("bodyParameterTwoName", "Parameter Two") )) ) .respond( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body_response") ); // then // wrong query string parameter value assertEquals( response() .withHeader(HttpHeaders.CONTENT_TYPE, TEXT_PLAIN) .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body_response"), makeRequest( request() .withMethod("POST") .withPath(calculatePath("some_pathRequest")) .withBody(params( param("bodyParameterOneName", "OTHER Parameter One Value One", "OTHER Parameter One Value Two"), param("bodyParameterTwoName", "Parameter Two") )) .withHeaders(header("headerNameRequest", "headerValueRequest")) .withCookies(cookie("cookieNameRequest", "cookieValueRequest")), headersToIgnore) ); // wrong query string parameter value assertEquals( response() .withHeader(HttpHeaders.CONTENT_TYPE, TEXT_PLAIN) .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body_response"), makeRequest( request() .withMethod("POST") .withPath(calculatePath("some_pathRequest")) .withBody(new StringBody("bodyParameterOneName=OTHER Parameter+One+Value+One" + "&bodyParameterOneName=OTHER Parameter+One+Value+Two" + "&bodyParameterTwoName=Parameter+Two")) .withHeaders(header("headerNameRequest", "headerValueRequest")) .withCookies(cookie("cookieNameRequest", "cookieValueRequest")), headersToIgnore) ); } @Test public void shouldReturnResponseByNotMatchingQueryStringParameterWithNotOperatorForNameAndValue() { // when mockServerClient .when( request() .withMethod("POST") .withPath(calculatePath("some_pathRequest")) .withQueryStringParameters( param(not("queryStringParameterOneName"), not("Parameter One Value One"), not("Parameter One Value Two")), param("queryStringParameterTwoName", "Parameter Two") ) ) .respond( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body_response") ); // then // wrong query string parameter name assertEquals( response() .withHeader(HttpHeaders.CONTENT_TYPE, TEXT_PLAIN) .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body_response"), makeRequest( request() .withMethod("POST") .withPath(calculatePath("some_pathRequest")) .withQueryStringParameters( param("OTHERQueryStringParameterOneName", "Parameter One Value One", "Parameter One Value Two"), param("queryStringParameterTwoName", "Parameter Two") ), headersToIgnore) ); // wrong query string parameter value assertEquals( response() .withHeader(HttpHeaders.CONTENT_TYPE, TEXT_PLAIN) .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body_response"), makeRequest( request() .withMethod("POST") .withPath(calculatePath("some_pathRequest")) .withQueryStringParameters( param("queryStringParameterOneName", "OTHER Parameter One Value One", "OTHER Parameter One Value Two"), param("queryStringParameterTwoName", "Parameter Two") ), headersToIgnore) ); } @Test public void shouldReturnResponseByNotMatchingQueryStringParameterWithNotOperatorForName() { // when mockServerClient .when( request() .withMethod("POST") .withPath(calculatePath("some_pathRequest")) .withQueryStringParameters( param(not("queryStringParameterOneName"), string("Parameter One Value One"), string("Parameter One Value Two")), param("queryStringParameterTwoName", "Parameter Two") ) ) .respond( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body_response") ); // then // wrong query string parameter name assertEquals( response() .withHeader(HttpHeaders.CONTENT_TYPE, TEXT_PLAIN) .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body_response"), makeRequest( request() .withMethod("POST") .withPath(calculatePath("some_pathRequest")) .withQueryStringParameters( param("OTHERQueryStringParameterOneName", "Parameter One Value One", "Parameter One Value Two"), param("queryStringParameterTwoName", "Parameter Two") ), headersToIgnore) ); } @Test public void shouldReturnResponseByNotMatchingQueryStringParameterWithNotOperatorForValue() { // when mockServerClient .when( request() .withMethod("POST") .withPath(calculatePath("some_pathRequest")) .withQueryStringParameters( param(string("queryStringParameterOneName"), not("Parameter One Value One"), not("Parameter One Value Two")), param("queryStringParameterTwoName", "Parameter Two") ) ) .respond( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body_response") ); // then // wrong query string parameter value assertEquals( response() .withHeader(HttpHeaders.CONTENT_TYPE, TEXT_PLAIN) .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body_response"), makeRequest( request() .withMethod("POST") .withPath(calculatePath("some_pathRequest")) .withQueryStringParameters( param("queryStringParameterOneName", "OTHER Parameter One Value One", "OTHER Parameter One Value Two"), param("queryStringParameterTwoName", "Parameter Two") ), headersToIgnore) ); } @Test public void shouldReturnResponseByNotMatchingCookieWithNotOperatorForNameAndValue() { // when mockServerClient .when( request() .withMethod("GET") .withPath(calculatePath("some_pathRequest")) .withCookies( cookie(not("requestCookieNameOne"), not("requestCookieValueOne")), cookie("requestCookieNameTwo", "requestCookieValueTwo") ) ) .respond( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body_response") ); // then // wrong query string cookie name assertEquals( response() .withHeader(HttpHeaders.CONTENT_TYPE, TEXT_PLAIN) .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body_response"), makeRequest( request() .withMethod("GET") .withPath(calculatePath("some_pathRequest")) .withCookies( cookie("OTHERrequestCookieNameOne", "requestCookieValueOne"), cookie("requestCookieNameTwo", "requestCookieValueTwo") ), headersToIgnore) ); // wrong query string cookie value assertEquals( response() .withHeader(HttpHeaders.CONTENT_TYPE, TEXT_PLAIN) .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body_response"), makeRequest( request() .withMethod("GET") .withPath(calculatePath("some_pathRequest")) .withCookies( cookie("requestCookieNameOne", "OTHERrequestCookieValueOne"), cookie("requestCookieNameTwo", "requestCookieValueTwo") ), headersToIgnore) ); } @Test public void shouldReturnResponseByNotMatchingCookieWithNotOperatorForName() { // when mockServerClient .when( request() .withMethod("GET") .withPath(calculatePath("some_pathRequest")) .withCookies( cookie(not("requestCookieNameOne"), string("requestCookieValueOne")), cookie("requestCookieNameTwo", "requestCookieValueTwo") ) ) .respond( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body_response") ); // then // wrong query string cookie name assertEquals( response() .withHeader(HttpHeaders.CONTENT_TYPE, TEXT_PLAIN) .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body_response"), makeRequest( request() .withMethod("GET") .withPath(calculatePath("some_pathRequest")) .withCookies( cookie("OTHERrequestCookieNameOne", "requestCookieValueOne"), cookie("requestCookieNameTwo", "requestCookieValueTwo") ), headersToIgnore) ); } @Test public void shouldReturnResponseByNotMatchingCookieWithNotOperatorForValue() { // when mockServerClient .when( request() .withMethod("GET") .withPath(calculatePath("some_pathRequest")) .withCookies( cookie(string("requestCookieNameOne"), not("requestCookieValueOne")), cookie("requestCookieNameTwo", "requestCookieValueTwo") ) ) .respond( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body_response") ); // then // wrong query string cookie value assertEquals( response() .withHeader(HttpHeaders.CONTENT_TYPE, TEXT_PLAIN) .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body_response"), makeRequest( request() .withMethod("GET") .withPath(calculatePath("some_pathRequest")) .withCookies( cookie("requestCookieNameOne", "OTHERrequestCookieValueOne"), cookie("requestCookieNameTwo", "requestCookieValueTwo") ), headersToIgnore) ); } @Test public void shouldReturnResponseByNotMatchingHeaderWithNotOperatorForNameAndValue() { // when mockServerClient .when( request() .withMethod("GET") .withPath(calculatePath("some_pathRequest")) .withHeaders( header(not("requestHeaderNameOne"), not("requestHeaderValueOne")), header("requestHeaderNameTwo", "requestHeaderValueTwo") ) ) .respond( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body_response") ); // then // wrong query string header name assertEquals( response() .withHeader(HttpHeaders.CONTENT_TYPE, TEXT_PLAIN) .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body_response"), makeRequest( request() .withMethod("GET") .withPath(calculatePath("some_pathRequest")) .withHeaders( header("OTHERrequestHeaderNameOne", "requestHeaderValueOne"), header("requestHeaderNameTwo", "requestHeaderValueTwo") ), headersToIgnore) ); // wrong query string header value assertEquals( response() .withHeader(HttpHeaders.CONTENT_TYPE, TEXT_PLAIN) .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body_response"), makeRequest( request() .withMethod("GET") .withPath(calculatePath("some_pathRequest")) .withHeaders( header("requestHeaderNameOne", "OTHERrequestHeaderValueOne"), header("requestHeaderNameTwo", "requestHeaderValueTwo") ), headersToIgnore) ); } @Test public void shouldReturnResponseByNotMatchingHeaderWithNotOperatorForName() { // when mockServerClient .when( request() .withMethod("GET") .withPath(calculatePath("some_pathRequest")) .withHeaders( header(not("requestHeaderNameOne"), string("requestHeaderValueOne")), header("requestHeaderNameTwo", "requestHeaderValueTwo") ) ) .respond( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body_response") ); // then // wrong query string header name assertEquals( response() .withHeader(HttpHeaders.CONTENT_TYPE, TEXT_PLAIN) .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body_response"), makeRequest( request() .withMethod("GET") .withPath(calculatePath("some_pathRequest")) .withHeaders( header("OTHERrequestHeaderNameOne", "requestHeaderValueOne"), header("requestHeaderNameTwo", "requestHeaderValueTwo") ), headersToIgnore) ); } @Test public void shouldReturnResponseByNotMatchingHeaderWithNotOperatorForValue() { // when mockServerClient .when( request() .withMethod("GET") .withPath(calculatePath("some_pathRequest")) .withHeaders( header(string("requestHeaderNameOne"), not("requestHeaderValueOne")), header("requestHeaderNameTwo", "requestHeaderValueTwo") ) ) .respond( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body_response") ); // then // wrong query string header value assertEquals( response() .withHeader(HttpHeaders.CONTENT_TYPE, TEXT_PLAIN) .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body_response"), makeRequest( request() .withMethod("GET") .withPath(calculatePath("some_pathRequest")) .withHeaders( header("requestHeaderNameOne", "OTHERrequestHeaderValueOne"), header("requestHeaderNameTwo", "requestHeaderValueTwo") ), headersToIgnore) ); } @Test public void shouldNotReturnResponseForWhenTimeToLiveExpired() { // when mockServerClient .when( request().withPath(calculatePath("some_path")), exactly(2), TimeToLive.exactly(TimeUnit.SECONDS, 5L) ) .respond( response().withBody("some_body").withDelay(TimeUnit.SECONDS, 5L) ); // then assertEquals( response() .withHeader(HttpHeaders.CONTENT_TYPE, TEXT_PLAIN) .withStatusCode(HttpStatusCode.OK_200.code()) .withBody("some_body"), makeRequest( request() .withPath(calculatePath("some_path")), headersToIgnore) ); // - in http assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()), makeRequest( request() .withPath(calculatePath("some_path")), headersToIgnore) ); // - in https assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()), makeRequest( request() .withSecure(true) .withPath(calculatePath("some_path")), headersToIgnore) ); } @Test public void shouldNotReturnResponseForNonMatchingBody() { // when mockServerClient .when( request() .withMethod("GET") .withPath(calculatePath("some_path")) .withQueryStringParameters( param("queryStringParameterOneName", "queryStringParameterOneValue"), param("queryStringParameterTwoName", "queryStringParameterTwoValue") ) .withBody(exact("some_body")) .withHeaders(header("headerName", "headerValue")) .withCookies(cookie("cookieName", "cookieValue")) ) .respond( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body") .withHeaders(header("headerName", "headerValue")) .withCookies(cookie("cookieName", "cookieValue")) ); // then // - in http assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()), makeRequest( request() .withMethod("GET") .withPath(calculatePath("some_path")) .withQueryStringParameters( param("queryStringParameterOneName", "queryStringParameterOneValue"), param("queryStringParameterTwoName", "queryStringParameterTwoValue") ) .withBody(exact("some_other_body")) .withHeaders(header("headerName", "headerValue")) .withCookies(cookie("cookieName", "cookieValue")), headersToIgnore) ); // - in https assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()), makeRequest( request() .withMethod("GET") .withSecure(true) .withPath(calculatePath("some_path")) .withQueryStringParameters( param("queryStringParameterOneName", "queryStringParameterOneValue"), param("queryStringParameterTwoName", "queryStringParameterTwoValue") ) .withBody(exact("some_other_body")) .withHeaders(header("headerName", "headerValue")) .withCookies(cookie("cookieName", "cookieValue")), headersToIgnore) ); } @Test public void shouldNotReturnResponseForMatchingBodyWithNotOperator() { // when mockServerClient .when( request() .withBody(Not.not(json("{" + System.getProperty("line.separator") + " \"id\": 1," + System.getProperty("line.separator") + " \"name\": \"A green door\"," + System.getProperty("line.separator") + " \"price\": 12.50," + System.getProperty("line.separator") + " \"tags\": [\"home\", \"green\"]" + System.getProperty("line.separator") + "}"))), exactly(2) ) .respond( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body") ); // then // - in http assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()), makeRequest( request() .withPath(calculatePath("some_path")) .withMethod("POST") .withBody("{" + System.getProperty("line.separator") + " \"id\": 1," + System.getProperty("line.separator") + " \"extra_ignored_field\": \"some value\"," + System.getProperty("line.separator") + " \"name\": \"A green door\"," + System.getProperty("line.separator") + " \"price\": 12.50," + System.getProperty("line.separator") + " \"tags\": [\"home\", \"green\"]" + System.getProperty("line.separator") + "}"), headersToIgnore) ); // - in https assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()), makeRequest( request() .withSecure(true) .withPath(calculatePath("some_path")) .withMethod("POST") .withBody("{" + System.getProperty("line.separator") + " \"id\": 1," + System.getProperty("line.separator") + " \"extra_ignored_array\": [\"one\", \"two\"]," + System.getProperty("line.separator") + " \"name\": \"A green door\"," + System.getProperty("line.separator") + " \"price\": 12.50," + System.getProperty("line.separator") + " \"tags\": [\"home\", \"green\"]" + System.getProperty("line.separator") + "}"), headersToIgnore) ); } @Test public void shouldNotReturnResponseForNonMatchingXPathBody() { // when mockServerClient.when(request().withBody(new XPathBody("/bookstore/book[price>35]/price")), exactly(2)).respond(response().withBody("some_body")); // then // - in http assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()), makeRequest( request() .withSecure(true) .withPath(calculatePath("some_path")) .withMethod("POST") .withBody(new StringBody("" + "<?xml version=\"1.0\" encoding=\"ISO-8859-1\"?>" + System.getProperty("line.separator") + "<bookstore>" + System.getProperty("line.separator") + " <book category=\"COOKING\">" + System.getProperty("line.separator") + " <title lang=\"en\">Everyday Italian</title>" + System.getProperty("line.separator") + " <author>Giada De Laurentiis</author>" + System.getProperty("line.separator") + " <year>2005</year>" + System.getProperty("line.separator") + " <price>30.00</price>" + System.getProperty("line.separator") + " </book>" + System.getProperty("line.separator") + " <book category=\"CHILDREN\">" + System.getProperty("line.separator") + " <title lang=\"en\">Harry Potter</title>" + System.getProperty("line.separator") + " <author>J K. Rowling</author>" + System.getProperty("line.separator") + " <year>2005</year>" + System.getProperty("line.separator") + " <price>29.99</price>" + System.getProperty("line.separator") + " </book>" + System.getProperty("line.separator") + " <book category=\"WEB\">" + System.getProperty("line.separator") + " <title lang=\"en\">Learning XML</title>" + System.getProperty("line.separator") + " <author>Erik T. Ray</author>" + System.getProperty("line.separator") + " <year>2003</year>" + System.getProperty("line.separator") + " <price>31.95</price>" + System.getProperty("line.separator") + " </book>" + System.getProperty("line.separator") + "</bookstore>")), headersToIgnore) ); // - in https assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()), makeRequest( request() .withSecure(true) .withPath(calculatePath("some_path")) .withMethod("POST") .withBody(new StringBody("" + "<?xml version=\"1.0\" encoding=\"ISO-8859-1\"?>" + System.getProperty("line.separator") + "<bookstore>" + System.getProperty("line.separator") + " <book category=\"COOKING\">" + System.getProperty("line.separator") + " <title lang=\"en\">Everyday Italian</title>" + System.getProperty("line.separator") + " <author>Giada De Laurentiis</author>" + System.getProperty("line.separator") + " <year>2005</year>" + System.getProperty("line.separator") + " <price>30.00</price>" + System.getProperty("line.separator") + " </book>" + System.getProperty("line.separator") + " <book category=\"CHILDREN\">" + System.getProperty("line.separator") + " <title lang=\"en\">Harry Potter</title>" + System.getProperty("line.separator") + " <author>J K. Rowling</author>" + System.getProperty("line.separator") + " <year>2005</year>" + System.getProperty("line.separator") + " <price>29.99</price>" + System.getProperty("line.separator") + " </book>" + System.getProperty("line.separator") + " <book category=\"WEB\">" + System.getProperty("line.separator") + " <title lang=\"en\">Learning XML</title>" + System.getProperty("line.separator") + " <author>Erik T. Ray</author>" + System.getProperty("line.separator") + " <year>2003</year>" + System.getProperty("line.separator") + " <price>31.95</price>" + System.getProperty("line.separator") + " </book>" + System.getProperty("line.separator") + "</bookstore>")), headersToIgnore) ); } @Test public void shouldNotReturnResponseForNonMatchingXmlBody() { // when mockServerClient.when(request().withBody(xml("" + "<?xml version=\"1.0\" encoding=\"ISO-8859-1\"?>" + System.getProperty("line.separator") + "<bookstore>" + System.getProperty("line.separator") + " <book category=\"COOKING\" nationality=\"ITALIAN\">" + System.getProperty("line.separator") + " <title lang=\"en\">Everyday Italian</title>" + System.getProperty("line.separator") + " <author>Giada De Laurentiis</author>" + System.getProperty("line.separator") + " <year>2005</year>" + System.getProperty("line.separator") + " <price>30.00</price>" + System.getProperty("line.separator") + " </book>" + System.getProperty("line.separator") + "</bookstore>")), exactly(2)).respond(response().withBody("some_body")); // then // - in http assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()), makeRequest( request() .withSecure(true) .withPath(calculatePath("some_path")) .withMethod("POST") .withBody(new StringBody("" + "<?xml version=\"1.0\" encoding=\"ISO-8859-1\"?>" + System.getProperty("line.separator") + "<bookstore>" + System.getProperty("line.separator") + " <book category=\"COOKING\">" + System.getProperty("line.separator") + " <title lang=\"en\">Everyday Italian</title>" + System.getProperty("line.separator") + " <author>Giada De Laurentiis</author>" + System.getProperty("line.separator") + " <year>2005</year>" + System.getProperty("line.separator") + " <price>30.00</price>" + System.getProperty("line.separator") + " </book>" + System.getProperty("line.separator") + "</bookstore>")), headersToIgnore) ); // - in https assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()), makeRequest( request() .withSecure(true) .withPath(calculatePath("some_path")) .withMethod("POST") .withBody(new StringBody("" + "<?xml version=\"1.0\" encoding=\"ISO-8859-1\"?>" + System.getProperty("line.separator") + "<bookstore>" + System.getProperty("line.separator") + " <book category=\"COOKING\">" + System.getProperty("line.separator") + " <title lang=\"en\">Everyday Italian</title>" + System.getProperty("line.separator") + " <author>Giada De Laurentiis</author>" + System.getProperty("line.separator") + " <year>2005</year>" + System.getProperty("line.separator") + " <price>30.00</price>" + System.getProperty("line.separator") + " </book>" + System.getProperty("line.separator") + "</bookstore>")), headersToIgnore) ); } @Test public void shouldNotReturnResponseForNonMatchingJsonBody() { // when mockServerClient.when(request().withBody(json("{" + System.getProperty("line.separator") + " \"id\": 1," + System.getProperty("line.separator") + " \"name\": \"A green door\"," + System.getProperty("line.separator") + " \"price\": 12.50," + System.getProperty("line.separator") + " \"tags\": [\"home\", \"green\"]" + System.getProperty("line.separator") + "}")), exactly(2)).respond(response().withBody("some_body")); // then // - in http assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()), makeRequest( request() .withPath(calculatePath("some_path")) .withMethod("POST") .withBody("{" + System.getProperty("line.separator") + " \"id\": 1," + System.getProperty("line.separator") + " \"name\": \"---- XXXX WRONG VALUE XXXX ----\"," + System.getProperty("line.separator") + " \"price\": 12.50," + System.getProperty("line.separator") + " \"tags\": [\"home\", \"green\"]" + System.getProperty("line.separator") + "}"), headersToIgnore) ); // - in https assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()), makeRequest( request() .withSecure(true) .withPath(calculatePath("some_path")) .withMethod("POST") .withBody("{" + System.getProperty("line.separator") + " \"id\": 1," + System.getProperty("line.separator") + " \"name\": \"---- XXXX WRONG VALUE XXXX ----\"," + System.getProperty("line.separator") + " \"price\": 12.50," + System.getProperty("line.separator") + " \"tags\": [\"home\", \"green\"]" + System.getProperty("line.separator") + "}"), headersToIgnore) ); } @Test public void shouldNotReturnResponseForNonMatchingJsonBodyWithMatchType() { // when mockServerClient .when( request() .withBody(json("{" + System.getProperty("line.separator") + " \"id\": 1," + System.getProperty("line.separator") + " \"name\": \"A green door\"," + System.getProperty("line.separator") + " \"price\": 12.50," + System.getProperty("line.separator") + " \"tags\": [\"home\", \"green\"]" + System.getProperty("line.separator") + "}", MatchType.STRICT)), exactly(2)) .respond( response() .withBody("some_body") ); // then // - in http assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()), makeRequest( request() .withPath(calculatePath("some_path")) .withMethod("POST") .withBody("{" + System.getProperty("line.separator") + " \"id\": 1," + System.getProperty("line.separator") + " \"extra field\": \"some value\"," + System.getProperty("line.separator") + " \"name\": \"A green door\"," + System.getProperty("line.separator") + " \"price\": 12.50," + System.getProperty("line.separator") + " \"tags\": [\"home\", \"green\"]" + System.getProperty("line.separator") + "}"), headersToIgnore) ); // - in https assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()), makeRequest( request() .withSecure(true) .withPath(calculatePath("some_path")) .withMethod("POST") .withBody("{" + System.getProperty("line.separator") + " \"id\": 1," + System.getProperty("line.separator") + " \"extra field\": \"some value\"," + System.getProperty("line.separator") + " \"name\": \"A green door\"," + System.getProperty("line.separator") + " \"price\": 12.50," + System.getProperty("line.separator") + " \"tags\": [\"home\", \"green\"]" + System.getProperty("line.separator") + "}"), headersToIgnore) ); } @Test public void shouldNotReturnResponseForNonMatchingJsonSchema() { // when mockServerClient.when(request().withBody(jsonSchema("{" + System.getProperty("line.separator") + " \"$schema\": \"http://json-schema.org/draft-04/schema#\"," + System.getProperty("line.separator") + " \"title\": \"Product\"," + System.getProperty("line.separator") + " \"description\": \"A product from Acme's catalog\"," + System.getProperty("line.separator") + " \"type\": \"object\"," + System.getProperty("line.separator") + " \"properties\": {" + System.getProperty("line.separator") + " \"id\": {" + System.getProperty("line.separator") + " \"description\": \"The unique identifier for a product\"," + System.getProperty("line.separator") + " \"type\": \"integer\"" + System.getProperty("line.separator") + " }," + System.getProperty("line.separator") + " \"name\": {" + System.getProperty("line.separator") + " \"description\": \"Name of the product\"," + System.getProperty("line.separator") + " \"type\": \"string\"" + System.getProperty("line.separator") + " }," + System.getProperty("line.separator") + " \"price\": {" + System.getProperty("line.separator") + " \"type\": \"number\"," + System.getProperty("line.separator") + " \"minimum\": 0," + System.getProperty("line.separator") + " \"exclusiveMinimum\": true" + System.getProperty("line.separator") + " }," + System.getProperty("line.separator") + " \"tags\": {" + System.getProperty("line.separator") + " \"type\": \"array\"," + System.getProperty("line.separator") + " \"items\": {" + System.getProperty("line.separator") + " \"type\": \"string\"" + System.getProperty("line.separator") + " }," + System.getProperty("line.separator") + " \"minItems\": 1," + System.getProperty("line.separator") + " \"uniqueItems\": true" + System.getProperty("line.separator") + " }" + System.getProperty("line.separator") + " }," + System.getProperty("line.separator") + " \"required\": [\"id\", \"name\", \"price\"]" + System.getProperty("line.separator") + "}")), exactly(2)).respond(response().withBody("some_body")); // then // - in http assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()), makeRequest( request() .withPath(calculatePath("some_path")) .withMethod("POST") .withBody("{" + System.getProperty("line.separator") + " \"id\": 1," + System.getProperty("line.separator") + " \"wrong field name\": \"A green door\"," + System.getProperty("line.separator") + " \"price\": 12.50," + System.getProperty("line.separator") + " \"tags\": [\"home\", \"green\"]" + System.getProperty("line.separator") + "}"), headersToIgnore) ); // - in https assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()), makeRequest( request() .withSecure(true) .withPath(calculatePath("some_path")) .withMethod("POST") .withBody("{" + System.getProperty("line.separator") + " \"id\": 1," + System.getProperty("line.separator") + " \"name\": \"A green door\"," + System.getProperty("line.separator") + " \"wrong field name\": 12.50," + System.getProperty("line.separator") + " \"tags\": [\"home\", \"green\"]" + System.getProperty("line.separator") + "}"), headersToIgnore) ); } @Test public void shouldNotReturnResponseForNonMatchingPath() { // when mockServerClient .when( request() .withMethod("GET") .withPath(calculatePath("some_path")) .withQueryStringParameters( param("queryStringParameterOneName", "queryStringParameterOneValue"), param("queryStringParameterTwoName", "queryStringParameterTwoValue") ) .withBody(exact("some_body")) .withHeaders(header("headerName", "headerValue")) .withCookies(cookie("cookieName", "cookieValue")) ) .respond( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body") .withHeaders(header("headerName", "headerValue")) .withCookies(cookie("cookieName", "cookieValue")) ); // then // - in http assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()), makeRequest( request() .withMethod("GET") .withPath(calculatePath("some_other_path")) .withQueryStringParameters( param("queryStringParameterOneName", "queryStringParameterOneValue"), param("queryStringParameterTwoName", "queryStringParameterTwoValue") ) .withBody(exact("some_body")) .withHeaders(header("headerName", "headerValue")) .withCookies(cookie("cookieName", "cookieValue")), headersToIgnore) ); // - in https assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()), makeRequest( request() .withMethod("GET") .withSecure(true) .withPath(calculatePath("some_other_path")) .withQueryStringParameters( param("queryStringParameterOneName", "queryStringParameterOneValue"), param("queryStringParameterTwoName", "queryStringParameterTwoValue") ) .withBody(exact("some_body")) .withHeaders(header("headerName", "headerValue")) .withCookies(cookie("cookieName", "cookieValue")), headersToIgnore) ); } @Test public void shouldNotReturnResponseForMatchingPathWithNotOperator() { // when mockServerClient .when( request() .withPath(not(calculatePath("some_path"))) ) .respond( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body_response") ); // then // - in http assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()), makeRequest( request() .withPath(calculatePath("some_path")), headersToIgnore) ); // - in https assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()), makeRequest( request() .withPath(calculatePath("some_path")), headersToIgnore) ); } @Test public void shouldNotReturnResponseForMatchingMethodWithNotOperator() { // when mockServerClient .when( request() .withMethod(not("GET")) ) .respond( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body_response") ); // then // - in http assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()), makeRequest( request() .withMethod("GET"), headersToIgnore) ); // - in https assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()), makeRequest( request() .withMethod("GET"), headersToIgnore) ); } @Test public void shouldNotReturnResponseForNonMatchingBodyParameterName() { // when mockServerClient .when( request() .withMethod("POST") .withPath(calculatePath("some_pathRequest")) .withBody(params( param("bodyParameterOneName", "Parameter One Value One", "Parameter One Value Two"), param("bodyParameterTwoName", "Parameter Two") )) ) .respond( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body_response") .withHeaders(header("headerNameResponse", "headerValueResponse")) .withCookies(cookie("cookieNameResponse", "cookieValueResponse")) ); // then // wrong query string parameter name assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()), makeRequest( request() .withMethod("POST") .withPath(calculatePath("some_pathRequest")) .withBody(params( param("OTHERBodyParameterOneName", "Parameter One Value One", "Parameter One Value Two"), param("bodyParameterTwoName", "Parameter Two") )) .withHeaders(header("headerNameRequest", "headerValueRequest")) .withCookies(cookie("cookieNameRequest", "cookieValueRequest")), headersToIgnore) ); // wrong query string parameter name assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()), makeRequest( request() .withMethod("POST") .withPath(calculatePath("some_pathRequest")) .withBody(new StringBody("OTHERBodyParameterOneName=Parameter+One+Value+One" + "&bodyParameterOneName=Parameter+One+Value+Two" + "&bodyParameterTwoName=Parameter+Two")) .withHeaders(header("headerNameRequest", "headerValueRequest")) .withCookies(cookie("cookieNameRequest", "cookieValueRequest")), headersToIgnore) ); } @Test public void shouldNotReturnResponseForMatchingBodyParameterWithNotOperator() { // when mockServerClient .when( request() .withMethod("POST") .withPath(calculatePath("some_pathRequest")) .withBody(params( param(not("bodyParameterOneName"), not("Parameter One Value One"), not("Parameter One Value Two")), param("bodyParameterTwoName", "Parameter Two") )) ) .respond( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body_response") ); // then // wrong query string parameter name assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()), makeRequest( request() .withMethod("POST") .withPath(calculatePath("some_pathRequest")) .withBody(params( param("bodyParameterOneName", "Parameter One Value One", "Parameter One Value Two"), param("bodyParameterTwoName", "Parameter Two") )) .withHeaders(header("headerNameRequest", "headerValueRequest")) .withCookies(cookie("cookieNameRequest", "cookieValueRequest")), headersToIgnore) ); // wrong query string parameter name assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()), makeRequest( request() .withMethod("POST") .withPath(calculatePath("some_pathRequest")) .withBody(new StringBody("bodyParameterOneName=Other Parameter+One+Value+One" + "&bodyParameterOneName=Parameter+One+Value+Two" + "&bodyParameterTwoName=Parameter+Two")) .withHeaders(header("headerNameRequest", "headerValueRequest")) .withCookies(cookie("cookieNameRequest", "cookieValueRequest")), headersToIgnore) ); } @Test public void shouldNotReturnResponseForNonMatchingBodyParameterValue() { // when mockServerClient .when( request() .withMethod("POST") .withPath(calculatePath("some_pathRequest")) .withBody(params( param("bodyParameterOneName", "Parameter One Value One", "Parameter One Value Two"), param("bodyParameterTwoName", "Parameter Two") )) ) .respond( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body_response") .withHeaders(header("headerNameResponse", "headerValueResponse")) .withCookies(cookie("cookieNameResponse", "cookieValueResponse")) ); // then // wrong body parameter value assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()), makeRequest( request() .withMethod("POST") .withPath(calculatePath("some_pathRequest")) .withBody(params( param("bodyParameterOneName", "Other Parameter One Value One", "Parameter One Value Two"), param("bodyParameterTwoName", "Parameter Two") )) .withHeaders(header("headerNameRequest", "headerValueRequest")) .withCookies(cookie("cookieNameRequest", "cookieValueRequest")), headersToIgnore) ); // wrong body parameter value assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()), makeRequest( request() .withMethod("POST") .withPath(calculatePath("some_pathRequest")) .withBody(new StringBody("bodyParameterOneName=Other Parameter+One+Value+One" + "&bodyParameterOneName=Parameter+One+Value+Two" + "&bodyParameterTwoName=Parameter+Two")) .withHeaders(header("headerNameRequest", "headerValueRequest")) .withCookies(cookie("cookieNameRequest", "cookieValueRequest")), headersToIgnore) ); } @Test public void shouldNotReturnResponseForNonMatchingQueryStringParameterName() { // when mockServerClient .when( request() .withMethod("POST") .withPath(calculatePath("some_pathRequest")) .withQueryStringParameters( param("queryStringParameterOneName", "queryStringParameterOneValueOne", "queryStringParameterOneValueTwo"), param("queryStringParameterTwoName", "queryStringParameterTwoValue") ) .withBody("some_bodyRequest") ) .respond( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body_response") .withHeaders(header("headerNameResponse", "headerValueResponse")) .withCookies(cookie("cookieNameResponse", "cookieValueResponse")) ); // then // wrong query string parameter name assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()), makeRequest( request() .withMethod("POST") .withPath(calculatePath("some_pathRequest")) .withQueryStringParameters( param("OTHERQueryStringParameterOneName", "queryStringParameterOneValueOne", "queryStringParameterOneValueTwo"), param("queryStringParameterTwoName", "queryStringParameterTwoValue") ) .withBody("some_bodyRequest") .withHeaders( header("headerNameRequest", "headerValueRequest") ) .withCookies(cookie("cookieNameRequest", "cookieValueRequest")), headersToIgnore) ); } @Test public void shouldNotReturnResponseForNonMatchingQueryStringParameterValue() { // when mockServerClient .when( request() .withMethod("POST") .withPath(calculatePath("some_pathRequest")) .withQueryStringParameters( param("queryStringParameterOneName", "queryStringParameterOneValueOne", "queryStringParameterOneValueTwo"), param("queryStringParameterTwoName", "queryStringParameterTwoValue") ) .withBody("some_bodyRequest") ) .respond( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body_response") .withHeaders(header("headerNameResponse", "headerValueResponse")) .withCookies(cookie("cookieNameResponse", "cookieValueResponse")) ); // then // wrong query string parameter value assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()), makeRequest( request() .withMethod("POST") .withPath(calculatePath("some_pathRequest")) .withQueryStringParameters( param("queryStringParameterOneName", "OTHERqueryStringParameterOneValueOne", "queryStringParameterOneValueTwo"), param("queryStringParameterTwoName", "queryStringParameterTwoValue") ) .withBody("some_bodyRequest") .withHeaders(header("headerNameRequest", "headerValueRequest")) .withCookies(cookie("cookieNameRequest", "cookieValueRequest")), headersToIgnore) ); } @Test public void shouldNotReturnResponseForMatchingQueryStringParameterWithNotOperator() { // when mockServerClient .when( request() .withMethod("POST") .withPath(calculatePath("some_pathRequest")) .withQueryStringParameters( param(not("queryStringParameterOneName"), not("Parameter One Value One"), not("Parameter One Value Two")), param("queryStringParameterTwoName", "Parameter Two") ) ) .respond( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body_response") ); // then // wrong query string parameter name assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()), makeRequest( request() .withMethod("POST") .withPath(calculatePath("some_pathRequest")) .withQueryStringParameters( param("queryStringParameterOneName", "Parameter One Value One", "Parameter One Value Two"), param("queryStringParameterTwoName", "Parameter Two") ), headersToIgnore) ); // wrong query string parameter name assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()), makeRequest( request() .withMethod("POST") .withPath(calculatePath("some_pathRequest")) .withQueryStringParameters( param("queryStringParameterOneName", "Parameter One Value One", "Parameter One Value Two"), param("queryStringParameterTwoName", "Parameter Two") ), headersToIgnore) ); } @Test public void shouldNotReturnResponseForNonMatchingCookieName() { // when mockServerClient .when( request() .withMethod("GET") .withPath(calculatePath("some_path")) .withQueryStringParameters( param("queryStringParameterOneName", "queryStringParameterOneValue"), param("queryStringParameterTwoName", "queryStringParameterTwoValue") ) .withBody(exact("some_body")) .withHeaders(header("headerName", "headerValue")) .withCookies(cookie("cookieName", "cookieValue")) ) .respond( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body") .withHeaders(header("headerName", "headerValue")) .withCookies(cookie("cookieName", "cookieValue")) ); // then // - in http assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()), makeRequest( request() .withMethod("GET") .withPath(calculatePath("some_path")) .withQueryStringParameters( param("queryStringParameterOneName", "queryStringParameterOneValue"), param("queryStringParameterTwoName", "queryStringParameterTwoValue") ) .withBody(exact("some_body")) .withHeaders(header("headerName", "headerValue")) .withCookies(cookie("cookieOtherName", "cookieValue")), headersToIgnore) ); // - in https assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()), makeRequest( request() .withMethod("GET") .withSecure(true) .withPath(calculatePath("some_path")) .withQueryStringParameters( param("queryStringParameterOneName", "queryStringParameterOneValue"), param("queryStringParameterTwoName", "queryStringParameterTwoValue") ) .withBody(exact("some_body")) .withHeaders(header("headerName", "headerValue")) .withCookies(cookie("cookieOtherName", "cookieValue")), headersToIgnore) ); } @Test public void shouldNotReturnResponseForNonMatchingCookieValue() { // when mockServerClient .when( request() .withMethod("GET") .withPath(calculatePath("some_path")) .withQueryStringParameters( param("queryStringParameterOneName", "queryStringParameterOneValue"), param("queryStringParameterTwoName", "queryStringParameterTwoValue") ) .withBody(exact("some_body")) .withHeaders(header("headerName", "headerValue")) .withCookies(cookie("cookieName", "cookieValue")) ) .respond( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body") .withHeaders(header("headerName", "headerValue")) .withCookies(cookie("cookieName", "cookieValue")) ); // then // - in http assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()), makeRequest( request() .withMethod("GET") .withPath(calculatePath("some_path")) .withQueryStringParameters( param("queryStringParameterOneName", "queryStringParameterOneValue"), param("queryStringParameterTwoName", "queryStringParameterTwoValue") ) .withBody(exact("some_body")) .withHeaders(header("headerName", "headerValue")) .withCookies(cookie("cookieName", "cookieOtherValue")), headersToIgnore) ); // - in https assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()), makeRequest( request() .withMethod("GET") .withSecure(true) .withPath(calculatePath("some_path")) .withQueryStringParameters( param("queryStringParameterOneName", "queryStringParameterOneValue"), param("queryStringParameterTwoName", "queryStringParameterTwoValue") ) .withBody(exact("some_body")) .withHeaders(header("headerName", "headerValue")) .withCookies(cookie("cookieName", "cookieOtherValue")), headersToIgnore) ); } @Test public void shouldNotReturnResponseForMatchingCookieWithNotOperator() { // when mockServerClient .when( request() .withMethod("GET") .withPath(calculatePath("some_pathRequest")) .withCookies( cookie(not("requestCookieNameOne"), not("requestCookieValueOne")), cookie("requestCookieNameTwo", "requestCookieValueTwo") ) ) .respond( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body_response") ); // then // wrong query string parameter name assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()), makeRequest( request() .withMethod("GET") .withPath(calculatePath("some_pathRequest")) .withCookies( cookie("requestCookieNameOne", "requestCookieValueOne"), cookie("requestCookieNameTwo", "requestCookieValueTwo") ), headersToIgnore) ); // wrong query string parameter name assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()), makeRequest( request() .withMethod("GET") .withPath(calculatePath("some_pathRequest")) .withCookies( cookie("requestCookieNameOne", "requestCookieValueOne"), cookie("requestCookieNameTwo", "requestCookieValueTwo") ), headersToIgnore) ); } @Test public void shouldNotReturnResponseForNonMatchingHeaderName() { // when mockServerClient .when( request() .withMethod("GET") .withPath(calculatePath("some_path")) .withQueryStringParameters( param("queryStringParameterOneName", "queryStringParameterOneValue"), param("queryStringParameterTwoName", "queryStringParameterTwoValue") ) .withBody(exact("some_body")) .withHeaders(header("headerName", "headerValue")) .withCookies(cookie("cookieName", "cookieValue")) ) .respond( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body") .withHeaders(header("headerName", "headerValue")) .withCookies(cookie("cookieName", "cookieValue")) ); // then // - in http assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()), makeRequest( request() .withMethod("GET") .withPath(calculatePath("some_path")) .withQueryStringParameters( param("queryStringParameterOneName", "queryStringParameterOneValue"), param("queryStringParameterTwoName", "queryStringParameterTwoValue") ) .withBody(exact("some_body")) .withHeaders(header("headerOtherName", "headerValue")) .withCookies(cookie("cookieName", "cookieValue")), headersToIgnore) ); // - in https assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()), makeRequest( request() .withMethod("GET") .withSecure(true) .withPath(calculatePath("some_path")) .withQueryStringParameters( param("queryStringParameterOneName", "queryStringParameterOneValue"), param("queryStringParameterTwoName", "queryStringParameterTwoValue") ) .withBody(exact("some_body")) .withHeaders(header("headerOtherName", "headerValue")) .withCookies(cookie("cookieName", "cookieValue")), headersToIgnore) ); } @Test public void shouldNotReturnResponseForNonMatchingHeaderValue() { // when mockServerClient .when( request() .withMethod("GET") .withPath(calculatePath("some_path")) .withQueryStringParameters( param("queryStringParameterOneName", "queryStringParameterOneValue"), param("queryStringParameterTwoName", "queryStringParameterTwoValue") ) .withBody(exact("some_body")) .withHeaders(header("headerName", "headerValue")) .withCookies(cookie("cookieName", "cookieValue")) ) .respond( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body") .withHeaders(header("headerName", "headerValue")) .withCookies(cookie("cookieName", "cookieValue")) ); // then // - in http assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()), makeRequest( request() .withMethod("GET") .withPath(calculatePath("some_path")) .withQueryStringParameters( param("queryStringParameterOneName", "queryStringParameterOneValue"), param("queryStringParameterTwoName", "queryStringParameterTwoValue") ) .withBody(exact("some_body")) .withHeaders(header("headerName", "headerOtherValue")) .withCookies(cookie("cookieName", "cookieValue")), headersToIgnore) ); // - in https assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()), makeRequest( request() .withMethod("GET") .withSecure(true) .withPath(calculatePath("some_path")) .withQueryStringParameters( param("queryStringParameterOneName", "queryStringParameterOneValue"), param("queryStringParameterTwoName", "queryStringParameterTwoValue") ) .withBody(exact("some_body")) .withHeaders(header("headerName", "headerOtherValue")) .withCookies(cookie("cookieName", "cookieValue")), headersToIgnore) ); } @Test public void shouldNotReturnResponseForMatchingHeaderWithNotOperator() { // when mockServerClient .when( request() .withMethod("GET") .withPath(calculatePath("some_pathRequest")) .withHeaders( header(not("requestHeaderNameOne"), not("requestHeaderValueOne")), header("requestHeaderNameTwo", "requestHeaderValueTwo") ) ) .respond( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body_response") ); // then // wrong query string parameter name assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()), makeRequest( request() .withMethod("GET") .withPath(calculatePath("some_pathRequest")) .withHeaders( header("requestHeaderNameOne", "requestHeaderValueOne"), header("requestHeaderNameTwo", "requestHeaderValueTwo") ), headersToIgnore) ); // wrong query string parameter name assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()), makeRequest( request() .withMethod("GET") .withPath(calculatePath("some_pathRequest")) .withHeaders( header("requestHeaderNameOne", "requestHeaderValueOne"), header("requestHeaderNameTwo", "requestHeaderValueTwo") ), headersToIgnore) ); } @Test public void shouldVerifyReceivedRequests() { // when mockServerClient .when( request() .withPath(calculatePath("some_path")), exactly(2) ) .respond( response() .withBody("some_body") ); // then // - in http assertEquals( response() .withHeader(HttpHeaders.CONTENT_TYPE, TEXT_PLAIN) .withStatusCode(HttpStatusCode.OK_200.code()) .withBody("some_body"), makeRequest( request() .withPath(calculatePath("some_path")), headersToIgnore) ); mockServerClient.verify(request() .withPath(calculatePath("some_path"))); mockServerClient.verify(request() .withPath(calculatePath("some_path")), VerificationTimes.exactly(1)); // - in https assertEquals( response() .withHeader(HttpHeaders.CONTENT_TYPE, TEXT_PLAIN) .withStatusCode(HttpStatusCode.OK_200.code()) .withBody("some_body"), makeRequest( request() .withSecure(true) .withPath(calculatePath("some_path")), headersToIgnore) ); mockServerClient.verify(request().withPath(calculatePath("some_path")), VerificationTimes.atLeast(1)); mockServerClient.verify(request().withPath(calculatePath("some_path")), VerificationTimes.exactly(2)); } @Test public void shouldVerifyReceivedRequestInSsl() { // when mockServerClient .when( request() .withPath(calculatePath("some.*path")), exactly(2) ) .respond( response() .withBody("some_body") ); // then // - in http assertEquals( response() .withHeader(HttpHeaders.CONTENT_TYPE, TEXT_PLAIN) .withStatusCode(HttpStatusCode.OK_200.code()) .withBody("some_body"), makeRequest( request() .withPath(calculatePath("some_path")), headersToIgnore) ); mockServerClient.verify(request() .withPath(calculatePath("some_path")) .withSecure(false)); mockServerClient.verify(request() .withPath(calculatePath("some_path")) .withSecure(false), VerificationTimes.exactly(1)); // - in https assertEquals( response() .withHeader(HttpHeaders.CONTENT_TYPE, TEXT_PLAIN) .withStatusCode(HttpStatusCode.OK_200.code()) .withBody("some_body"), makeRequest( request() .withPath(calculatePath("some_secure_path")) .withSecure(true), headersToIgnore) ); mockServerClient.verify(request() .withPath(calculatePath("some_secure_path")) .withSecure(true)); mockServerClient.verify(request() .withPath(calculatePath("some_secure_path")) .withSecure(true), VerificationTimes.exactly(1)); } @Test public void shouldVerifyReceivedRequestsWithNoBody() { // when mockServerClient.when(request().withPath(calculatePath("some_path")), exactly(2)).respond(response()); // then // - in http assertEquals( response() .withStatusCode(HttpStatusCode.OK_200.code()), makeRequest( request() .withPath(calculatePath("some_path")), headersToIgnore) ); mockServerClient.verify(request() .withPath(calculatePath("some_path"))); mockServerClient.verify(request() .withPath(calculatePath("some_path")), VerificationTimes.exactly(1)); } @Test public void shouldVerifyNotEnoughRequestsReceived() { // when mockServerClient.when(request().withPath(calculatePath("some_path")), exactly(2)).respond(response().withBody("some_body")); // then assertEquals( response() .withHeader(HttpHeaders.CONTENT_TYPE, TEXT_PLAIN) .withStatusCode(HttpStatusCode.OK_200.code()) .withBody("some_body"), makeRequest( request() .withPath(calculatePath("some_path")), headersToIgnore) ); try { mockServerClient.verify(request() .withPath(calculatePath("some_path")), VerificationTimes.atLeast(2)); fail(); } catch (AssertionError ae) { assertThat(ae.getMessage(), startsWith("Request not found at least 2 times, expected:<{" + System.getProperty("line.separator") + " \"path\" : \"" + calculatePath("some_path") + "\"" + System.getProperty("line.separator") + "}> but was:<{" + System.getProperty("line.separator") + " \"method\" : \"GET\"," + System.getProperty("line.separator") + " \"path\" : \"" + calculatePath("some_path") + "\"," + System.getProperty("line.separator"))); } } @Test public void shouldVerifyTooManyRequestsReceived() { // when mockServerClient.when(request().withPath(calculatePath("some_path")), exactly(2)).respond(response().withBody("some_body")); // then assertEquals( response() .withHeader(HttpHeaders.CONTENT_TYPE, TEXT_PLAIN) .withStatusCode(HttpStatusCode.OK_200.code()) .withBody("some_body"), makeRequest( request() .withPath(calculatePath("some_path")), headersToIgnore) ); try { mockServerClient.verify(request() .withPath(calculatePath("some_path")), VerificationTimes.exactly(0)); fail(); } catch (AssertionError ae) { assertThat(ae.getMessage(), startsWith("Request not found exactly 0 times, expected:<{" + System.getProperty("line.separator") + " \"path\" : \"" + calculatePath("some_path") + "\"" + System.getProperty("line.separator") + "}> but was:<{" + System.getProperty("line.separator") + " \"method\" : \"GET\"," + System.getProperty("line.separator") + " \"path\" : \"" + calculatePath("some_path") + "\"," + System.getProperty("line.separator"))); } } @Test public void shouldVerifyNoMatchingRequestsReceived() { // when mockServerClient.when(request().withPath(calculatePath("some_path")), exactly(2)).respond(response().withBody("some_body")); // then assertEquals( response() .withHeader(HttpHeaders.CONTENT_TYPE, TEXT_PLAIN) .withStatusCode(HttpStatusCode.OK_200.code()) .withBody("some_body"), makeRequest( request() .withPath(calculatePath("some_path")), headersToIgnore) ); try { mockServerClient.verify(request() .withPath(calculatePath("some_other_path")), VerificationTimes.exactly(2)); fail(); } catch (AssertionError ae) { assertThat(ae.getMessage(), startsWith("Request not found exactly 2 times, expected:<{" + System.getProperty("line.separator") + " \"path\" : \"" + calculatePath("some_other_path") + "\"" + System.getProperty("line.separator") + "}> but was:<{" + System.getProperty("line.separator") + " \"method\" : \"GET\"," + System.getProperty("line.separator") + " \"path\" : \"" + calculatePath("some_path") + "\"," + System.getProperty("line.separator"))); } } @Test public void shouldVerifyNoRequestsReceived() { // when mockServerClient.reset(); // then mockServerClient.verifyZeroInteractions(); } @Test public void shouldNotVerifyNoRequestsReceived() { // when mockServerClient.when(request().withPath(calculatePath("some_path")), exactly(2)).respond(response().withBody("some_body")); // then assertEquals( response() .withHeader(HttpHeaders.CONTENT_TYPE, TEXT_PLAIN) .withStatusCode(HttpStatusCode.OK_200.code()) .withBody("some_body"), makeRequest( request() .withPath(calculatePath("some_path")), headersToIgnore) ); try { mockServerClient.verifyZeroInteractions(); fail(); } catch (AssertionError ae) { assertThat(ae.getMessage(), startsWith("Request not found exactly 0 times, expected:<{ }> but was:<{" + System.getProperty("line.separator") + " \"method\" : \"GET\"," + System.getProperty("line.separator") + " \"path\" : \"" + calculatePath("some_path") + "\"," + System.getProperty("line.separator"))); } } @Test public void shouldVerifyNoMatchingRequestsReceivedInSsl() { // when mockServerClient.when(request().withPath(calculatePath("some.*path")), exactly(2)).respond(response().withBody("some_body")); // then // - in http assertEquals( response() .withHeader(HttpHeaders.CONTENT_TYPE, TEXT_PLAIN) .withStatusCode(HttpStatusCode.OK_200.code()) .withBody("some_body"), makeRequest( request() .withPath(calculatePath("some_path")), headersToIgnore) ); try { mockServerClient.verify( request() .withPath(calculatePath("some_path")) .withSecure(true), VerificationTimes.atLeast(1) ); fail(); } catch (AssertionError ae) { assertThat(ae.getMessage(), startsWith("Request not found at least once, expected:<{" + System.getProperty("line.separator") + " \"path\" : \"" + calculatePath("some_path") + "\"," + System.getProperty("line.separator") + " \"secure\" : true" + System.getProperty("line.separator") + "}> but was:<{" + System.getProperty("line.separator") + " \"method\" : \"GET\"," + System.getProperty("line.separator") + " \"path\" : \"" + calculatePath("some_path") + "\"," + System.getProperty("line.separator"))); } // - in https assertEquals( response() .withHeader(HttpHeaders.CONTENT_TYPE, TEXT_PLAIN) .withStatusCode(HttpStatusCode.OK_200.code()) .withBody("some_body"), makeRequest( request() .withPath(calculatePath("some_secure_path")) .withSecure(true), headersToIgnore) ); try { mockServerClient.verify( request() .withPath(calculatePath("some_secure_path")) .withSecure(false), VerificationTimes.atLeast(1) ); fail(); } catch (AssertionError ae) { assertThat(ae.getMessage(), startsWith("Request not found at least once, expected:<{" + System.getProperty("line.separator") + " \"path\" : \"" + calculatePath("some_secure_path") + "\"," + System.getProperty("line.separator") + " \"secure\" : false" + System.getProperty("line.separator") + "}> but was:<[ {" + System.getProperty("line.separator") + " \"method\" : \"GET\"," + System.getProperty("line.separator") + " \"path\" : \"" + calculatePath("some_path") + "\"," + System.getProperty("line.separator"))); } } @Test public void shouldVerifySequenceOfRequestsReceived() { // when mockServerClient.when(request().withPath(calculatePath("some_path.*")), exactly(6)).respond(response().withBody("some_body")); // then assertEquals( response("some_body").withHeader(HttpHeaders.CONTENT_TYPE, TEXT_PLAIN), makeRequest( request().withPath(calculatePath("some_path_one")), headersToIgnore) ); assertEquals( response("some_body").withHeader(HttpHeaders.CONTENT_TYPE, TEXT_PLAIN), makeRequest( request().withPath(calculatePath("some_path_two")), headersToIgnore) ); assertEquals( response("some_body").withHeader(HttpHeaders.CONTENT_TYPE, TEXT_PLAIN), makeRequest( request().withPath(calculatePath("some_path_three")), headersToIgnore) ); mockServerClient.verify(request(calculatePath("some_path_one")), request(calculatePath("some_path_three"))); mockServerClient.verify(request(calculatePath("some_path_one")), request(calculatePath("some_path_two"))); mockServerClient.verify(request(calculatePath("some_path_one")), request(calculatePath("some_path_two")), request(calculatePath("some_path_three"))); } @Test public void shouldVerifySequenceOfRequestsReceivedIncludingThoseNotMatchingAnException() { // when mockServerClient.when(request().withPath(calculatePath("some_path.*")), exactly(4)).respond(response().withBody("some_body")); // then assertEquals( response("some_body").withHeader(HttpHeaders.CONTENT_TYPE, TEXT_PLAIN), makeRequest( request().withPath(calculatePath("some_path_one")), headersToIgnore) ); assertEquals( notFoundResponse(), makeRequest( request().withPath(calculatePath("not_found")), headersToIgnore) ); assertEquals( response("some_body").withHeader(HttpHeaders.CONTENT_TYPE, TEXT_PLAIN), makeRequest( request().withPath(calculatePath("some_path_three")), headersToIgnore) ); mockServerClient.verify(request(calculatePath("some_path_one")), request(calculatePath("some_path_three"))); mockServerClient.verify(request(calculatePath("some_path_one")), request(calculatePath("not_found"))); mockServerClient.verify(request(calculatePath("some_path_one")), request(calculatePath("not_found")), request(calculatePath("some_path_three"))); mockServerClient.verify(request(calculatePath("some_path_one")), request(calculatePath("not_found")), request(calculatePath("some_path_three"))); } @Test public void shouldRetrieveSequenceOfRequestsReceivedIncludingThoseNotMatchingAnException() { // when mockServerClient.when(request().withPath(calculatePath("some_path.*")), exactly(4)).respond(response().withBody("some_body")); assertEquals( response("some_body").withHeader(HttpHeaders.CONTENT_TYPE, TEXT_PLAIN), makeRequest( request().withPath(calculatePath("some_path_one")), headersToIgnore) ); assertEquals( notFoundResponse(), makeRequest( request().withPath(calculatePath("not_found")), headersToIgnore) ); assertEquals( response("some_body").withHeader(HttpHeaders.CONTENT_TYPE, TEXT_PLAIN), makeRequest( request().withPath(calculatePath("some_path_three")), headersToIgnore) ); // then verifyRequestMatches( mockServerClient.retrieveRecordedRequests(request().withPath(calculatePath("some_path.*"))), request(calculatePath("some_path_one")), request(calculatePath("some_path_three")) ); verifyRequestMatches( mockServerClient.retrieveRecordedRequests(request()), request(calculatePath("some_path_one")), request(calculatePath("not_found")), request(calculatePath("some_path_three")) ); verifyRequestMatches( mockServerClient.retrieveRecordedRequests(null), request(calculatePath("some_path_one")), request(calculatePath("not_found")), request(calculatePath("some_path_three")) ); } @Test public void shouldRetrieveSequenceOfExpectationsSetup() { // when mockServerClient.when(request().withPath(calculatePath("some_path.*")), exactly(4)) .respond(response().withBody("some_body")); mockServerClient.when(request().withPath(calculatePath("some_path.*"))) .respond(response().withBody("some_body")); mockServerClient.when(request().withPath(calculatePath("some_other_path"))) .respond(response().withBody("some_other_body")); mockServerClient.when(request().withPath(calculatePath("some_forward_path"))) .forward(forward()); // then assertThat( mockServerClient.retrieveExistingExpectations(request().withPath(calculatePath("some_path.*"))), arrayContaining( new Expectation(request().withPath(calculatePath("some_path.*")), exactly(4), TimeToLive.unlimited()) .thenRespond(response().withBody("some_body")), expectation(request().withPath(calculatePath("some_path.*"))) .thenRespond(response().withBody("some_body")) ) ); assertThat( mockServerClient.retrieveExistingExpectations(null), arrayContaining( new Expectation(request().withPath(calculatePath("some_path.*")), exactly(4), TimeToLive.unlimited()) .thenRespond(response().withBody("some_body")), expectation(request().withPath(calculatePath("some_path.*"))) .thenRespond(response().withBody("some_body")), expectation(request().withPath(calculatePath("some_other_path"))) .thenRespond(response().withBody("some_other_body")), expectation(request().withPath(calculatePath("some_forward_path"))) .thenForward(forward()) ) ); assertThat( mockServerClient.retrieveExistingExpectations(request()), arrayContaining( new Expectation(request().withPath(calculatePath("some_path.*")), exactly(4), TimeToLive.unlimited()) .thenRespond(response().withBody("some_body")), expectation(request().withPath(calculatePath("some_path.*"))) .thenRespond(response().withBody("some_body")), expectation(request().withPath(calculatePath("some_other_path"))) .thenRespond(response().withBody("some_other_body")), expectation(request().withPath(calculatePath("some_forward_path"))) .thenForward(forward()) ) ); } @Test public void shouldVerifySequenceOfRequestsNotReceived() { // when mockServerClient.when(request().withPath(calculatePath("some_path.*")), exactly(6)).respond(response().withBody("some_body")); // then assertEquals( response("some_body").withHeader(HttpHeaders.CONTENT_TYPE, TEXT_PLAIN), makeRequest( request().withPath(calculatePath("some_path_one")), headersToIgnore) ); assertEquals( response("some_body").withHeader(HttpHeaders.CONTENT_TYPE, TEXT_PLAIN), makeRequest( request().withPath(calculatePath("some_path_two")), headersToIgnore) ); assertEquals( response("some_body").withHeader(HttpHeaders.CONTENT_TYPE, TEXT_PLAIN), makeRequest( request().withPath(calculatePath("some_path_three")), headersToIgnore) ); try { mockServerClient.verify(request(calculatePath("some_path_two")), request(calculatePath("some_path_one"))); fail(); } catch (AssertionError ae) { assertThat(ae.getMessage(), startsWith("Request sequence not found, expected:<[ {" + System.getProperty("line.separator") + " \"path\" : \"" + calculatePath("some_path_two") + "\"" + System.getProperty("line.separator") + "}, {" + System.getProperty("line.separator") + " \"path\" : \"" + calculatePath("some_path_one") + "\"" + System.getProperty("line.separator") + "} ]> but was:<[ {" + System.getProperty("line.separator") + " \"method\" : \"GET\"," + System.getProperty("line.separator") + " \"path\" : \"" + calculatePath("some_path_one") + "\"," + System.getProperty("line.separator"))); } try { mockServerClient.verify(request(calculatePath("some_path_three")), request(calculatePath("some_path_two"))); fail(); } catch (AssertionError ae) { assertThat(ae.getMessage(), startsWith("Request sequence not found, expected:<[ {" + System.getProperty("line.separator") + " \"path\" : \"" + calculatePath("some_path_three") + "\"" + System.getProperty("line.separator") + "}, {" + System.getProperty("line.separator") + " \"path\" : \"" + calculatePath("some_path_two") + "\"" + System.getProperty("line.separator") + "} ]> but was:<[ {" + System.getProperty("line.separator") + " \"method\" : \"GET\"," + System.getProperty("line.separator") + " \"path\" : \"" + calculatePath("some_path_one") + "\"," + System.getProperty("line.separator"))); } try { mockServerClient.verify(request(calculatePath("some_path_four"))); fail(); } catch (AssertionError ae) { assertThat(ae.getMessage(), startsWith("Request sequence not found, expected:<[ {" + System.getProperty("line.separator") + " \"path\" : \"" + calculatePath("some_path_four") + "\"" + System.getProperty("line.separator") + "} ]> but was:<[ {" + System.getProperty("line.separator") + " \"method\" : \"GET\"," + System.getProperty("line.separator") + " \"path\" : \"" + calculatePath("some_path_one") + "\"," + System.getProperty("line.separator"))); } } @Test public void shouldClearExpectations() { // given - some expectations mockServerClient .when( request() .withPath(calculatePath("some_path1")) ) .respond( response() .withBody("some_body1") ); mockServerClient .when( request() .withPath(calculatePath("some_path2")) ) .respond( response() .withBody("some_body2") ); // and - some matching requests assertEquals( response() .withHeader(HttpHeaders.CONTENT_TYPE, TEXT_PLAIN) .withStatusCode(HttpStatusCode.OK_200.code()) .withBody("some_body1"), makeRequest( request() .withPath(calculatePath("some_path1")), headersToIgnore) ); assertEquals( response() .withHeader(HttpHeaders.CONTENT_TYPE, TEXT_PLAIN) .withStatusCode(HttpStatusCode.OK_200.code()) .withBody("some_body2"), makeRequest( request() .withPath(calculatePath("some_path2")), headersToIgnore) ); // when mockServerClient .clear( request() .withPath(calculatePath("some_path1")) ); // then - expectations cleared assertThat( mockServerClient.retrieveExistingExpectations(null), arrayContaining( expectation( request() .withPath(calculatePath("some_path2")) ) .thenRespond( response() .withBody("some_body2") ) ) ); // and then - request log cleared verifyRequestMatches( mockServerClient.retrieveRecordedRequests(null), request(calculatePath("some_path2")) ); // and then - remaining expectations not cleared assertEquals( response() .withHeader(HttpHeaders.CONTENT_TYPE, TEXT_PLAIN) .withStatusCode(HttpStatusCode.OK_200.code()) .withBody("some_body2"), makeRequest( request() .withPath(calculatePath("some_path2")), headersToIgnore) ); assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()), makeRequest( request() .withPath(calculatePath("some_path1")), headersToIgnore) ); } @Test public void shouldClearAllExpectationsWithNull() { // given mockServerClient .when( request() .withPath(calculatePath("some_path1")) ) .respond( response() .withBody("some_body1") ); mockServerClient .when( request() .withPath(calculatePath("some_path2")) ) .respond( response() .withBody("some_body2") ); assertEquals( response() .withHeader(HttpHeaders.CONTENT_TYPE, TEXT_PLAIN) .withStatusCode(HttpStatusCode.OK_200.code()) .withBody("some_body2"), makeRequest( request() .withPath(calculatePath("some_path2")), headersToIgnore) ); // when mockServerClient.clear(null); // then assertThat(mockServerClient.retrieveExistingExpectations(null), emptyArray()); assertThat(mockServerClient.retrieveRecordedRequests(null), emptyArray()); } @Test public void shouldClearAllExpectationsWithEmptyRequest() { // given mockServerClient .when( request() .withPath(calculatePath("some_path1")) ) .respond( response() .withBody("some_body1") ); mockServerClient .when( request() .withPath(calculatePath("some_path2")) ) .respond( response() .withBody("some_body2") ); assertEquals( response() .withHeader(HttpHeaders.CONTENT_TYPE, TEXT_PLAIN) .withStatusCode(HttpStatusCode.OK_200.code()) .withBody("some_body2"), makeRequest( request() .withPath(calculatePath("some_path2")), headersToIgnore) ); // when mockServerClient.clear(request()); // then assertThat(mockServerClient.retrieveExistingExpectations(null), emptyArray()); assertThat(mockServerClient.retrieveRecordedRequests(null), emptyArray()); } @Test public void shouldClearExpectationsWithXPathBody() { // given mockServerClient .when( request() .withBody(xpath("/bookstore/book[year=2005]/price")) ) .respond( response() .withBody("some_body1") ); mockServerClient .when( request() .withBody(xpath("/bookstore/book[year=2006]/price")) ) .respond( response() .withBody("some_body2") ); // and StringBody xmlBody = new StringBody("" + "<?xml version=\"1.0\" encoding=\"ISO-8859-1\"?>" + System.getProperty("line.separator") + "<bookstore>" + System.getProperty("line.separator") + " <book category=\"COOKING\">" + System.getProperty("line.separator") + " <title lang=\"en\">Everyday Italian</title>" + System.getProperty("line.separator") + " <author>Giada De Laurentiis</author>" + System.getProperty("line.separator") + " <year>2005</year>" + System.getProperty("line.separator") + " <price>30.00</price>" + System.getProperty("line.separator") + " </book>" + System.getProperty("line.separator") + " <book category=\"CHILDREN\">" + System.getProperty("line.separator") + " <title lang=\"en\">Harry Potter</title>" + System.getProperty("line.separator") + " <author>J K. Rowling</author>" + System.getProperty("line.separator") + " <year>2006</year>" + System.getProperty("line.separator") + " <price>29.99</price>" + System.getProperty("line.separator") + " </book>" + System.getProperty("line.separator") + " <book category=\"WEB\">" + System.getProperty("line.separator") + " <title lang=\"en\">Learning XML</title>" + System.getProperty("line.separator") + " <author>Erik T. Ray</author>" + System.getProperty("line.separator") + " <year>2003</year>" + System.getProperty("line.separator") + " <price>31.95</price>" + System.getProperty("line.separator") + " </book>" + System.getProperty("line.separator") + "</bookstore>"); // then assertEquals( response() .withHeader(HttpHeaders.CONTENT_TYPE, TEXT_PLAIN) .withStatusCode(HttpStatusCode.OK_200.code()) .withBody("some_body1"), makeRequest( request() .withBody(xmlBody), headersToIgnore) ); // when mockServerClient .clear( request() .withBody(xpath("/bookstore/book[year=2005]/price")) ); // then assertThat( mockServerClient.retrieveExistingExpectations(null), arrayContaining( expectation( request() .withBody(xpath("/bookstore/book[year=2006]/price")) ) .thenRespond( response() .withBody("some_body2") ) ) ); // - in http assertEquals( response() .withHeader(HttpHeaders.CONTENT_TYPE, TEXT_PLAIN) .withStatusCode(HttpStatusCode.OK_200.code()) .withBody("some_body2"), makeRequest( request() .withBody(xmlBody), headersToIgnore) ); // - in https assertEquals( response() .withHeader(HttpHeaders.CONTENT_TYPE, TEXT_PLAIN) .withStatusCode(HttpStatusCode.OK_200.code()) .withBody("some_body2"), makeRequest( request() .withSecure(true) .withBody(xmlBody), headersToIgnore) ); } @Test public void shouldClearExpectationsWithJsonSchemaBody() { // given JsonSchemaBody jsonSchemaBodyOne = jsonSchema("{" + System.getProperty("line.separator") + " \"$schema\": \"http://json-schema.org/draft-04/schema#\"," + System.getProperty("line.separator") + " \"title\": \"Product\"," + System.getProperty("line.separator") + " \"description\": \"A product from Acme's catalog\"," + System.getProperty("line.separator") + " \"type\": \"object\"," + System.getProperty("line.separator") + " \"properties\": {" + System.getProperty("line.separator") + " \"id\": {" + System.getProperty("line.separator") + " \"description\": \"The unique identifier for a product\"," + System.getProperty("line.separator") + " \"type\": \"integer\"" + System.getProperty("line.separator") + " }," + System.getProperty("line.separator") + " \"name\": {" + System.getProperty("line.separator") + " \"description\": \"Name of the product\"," + System.getProperty("line.separator") + " \"type\": \"string\"" + System.getProperty("line.separator") + " }," + System.getProperty("line.separator") + " \"price\": {" + System.getProperty("line.separator") + " \"type\": \"number\"," + System.getProperty("line.separator") + " \"minimum\": 0," + System.getProperty("line.separator") + " \"exclusiveMinimum\": true" + System.getProperty("line.separator") + " }," + System.getProperty("line.separator") + " \"tags\": {" + System.getProperty("line.separator") + " \"type\": \"array\"," + System.getProperty("line.separator") + " \"items\": {" + System.getProperty("line.separator") + " \"type\": \"string\"" + System.getProperty("line.separator") + " }," + System.getProperty("line.separator") + " \"minItems\": 1," + System.getProperty("line.separator") + " \"uniqueItems\": true" + System.getProperty("line.separator") + " }" + System.getProperty("line.separator") + " }," + System.getProperty("line.separator") + " \"required\": [\"id\", \"name\", \"price\"]" + System.getProperty("line.separator") + "}"); JsonSchemaBody jsonSchemaBodyTwo = jsonSchema("{" + System.getProperty("line.separator") + " \"$schema\": \"http://json-schema.org/draft-04/schema#\"," + System.getProperty("line.separator") + " \"title\": \"Product\"," + System.getProperty("line.separator") + " \"description\": \"A product from Acme's catalog\"," + System.getProperty("line.separator") + " \"type\": \"object\"," + System.getProperty("line.separator") + " \"properties\": {" + System.getProperty("line.separator") + " \"id\": {" + System.getProperty("line.separator") + " \"description\": \"The unique identifier for a product\"," + System.getProperty("line.separator") + " \"type\": \"integer\"" + System.getProperty("line.separator") + " }," + System.getProperty("line.separator") + " \"name\": {" + System.getProperty("line.separator") + " \"description\": \"Name of the product\"," + System.getProperty("line.separator") + " \"type\": \"string\"" + System.getProperty("line.separator") + " }," + System.getProperty("line.separator") + " \"price\": {" + System.getProperty("line.separator") + " \"type\": \"number\"," + System.getProperty("line.separator") + " \"minimum\": 10," + System.getProperty("line.separator") + " \"exclusiveMinimum\": true" + System.getProperty("line.separator") + " }," + System.getProperty("line.separator") + " \"tags\": {" + System.getProperty("line.separator") + " \"type\": \"array\"," + System.getProperty("line.separator") + " \"items\": {" + System.getProperty("line.separator") + " \"type\": \"string\"" + System.getProperty("line.separator") + " }," + System.getProperty("line.separator") + " \"minItems\": 1," + System.getProperty("line.separator") + " \"uniqueItems\": true" + System.getProperty("line.separator") + " }" + System.getProperty("line.separator") + " }," + System.getProperty("line.separator") + " \"required\": [\"id\", \"name\", \"price\"]" + System.getProperty("line.separator") + "}"); mockServerClient .when( request() .withBody(jsonSchemaBodyOne) ) .respond( response() .withBody("some_body1") ); mockServerClient .when( request() .withBody(jsonSchemaBodyTwo) ) .respond( response() .withBody("some_body2") ); // then assertEquals( response() .withHeader(HttpHeaders.CONTENT_TYPE, TEXT_PLAIN) .withStatusCode(HttpStatusCode.OK_200.code()) .withBody("some_body1"), makeRequest( request() .withBody("{" + System.getProperty("line.separator") + " \"id\": 1," + System.getProperty("line.separator") + " \"name\": \"A green door\"," + System.getProperty("line.separator") + " \"price\": 12.50," + System.getProperty("line.separator") + " \"tags\": [\"home\", \"green\"]" + System.getProperty("line.separator") + "}"), headersToIgnore) ); // when mockServerClient .clear( request() .withBody(jsonSchemaBodyOne) ); // then assertThat( mockServerClient.retrieveExistingExpectations(null), arrayContaining( expectation( request() .withBody(jsonSchemaBodyTwo) ) .thenRespond( response() .withBody("some_body2") ) ) ); // - in http assertEquals( response() .withHeader(HttpHeaders.CONTENT_TYPE, TEXT_PLAIN) .withStatusCode(HttpStatusCode.OK_200.code()) .withBody("some_body2"), makeRequest( request() .withBody("{" + System.getProperty("line.separator") + " \"id\": 1," + System.getProperty("line.separator") + " \"name\": \"A green door\"," + System.getProperty("line.separator") + " \"price\": 12.50," + System.getProperty("line.separator") + " \"tags\": [\"home\", \"green\"]" + System.getProperty("line.separator") + "}"), headersToIgnore) ); // - in https assertEquals( response() .withHeader(HttpHeaders.CONTENT_TYPE, TEXT_PLAIN) .withStatusCode(HttpStatusCode.OK_200.code()) .withBody("some_body2"), makeRequest( request() .withSecure(true) .withBody("{" + System.getProperty("line.separator") + " \"id\": 1," + System.getProperty("line.separator") + " \"name\": \"A green door\"," + System.getProperty("line.separator") + " \"price\": 12.50," + System.getProperty("line.separator") + " \"tags\": [\"home\", \"green\"]" + System.getProperty("line.separator") + "}"), headersToIgnore) ); } @Test public void shouldClearExpectationsWithParameterBody() { // given mockServerClient .when( request() .withBody(params(param("bodyParameterNameOne", "bodyParameterValueOne"))) ) .respond( response() .withBody("some_body1") ); mockServerClient .when( request() .withBody(params(param("bodyParameterNameTwo", "bodyParameterValueTwo"))) ) .respond( response() .withBody("some_body2") ); // then assertEquals( response() .withHeader(HttpHeaders.CONTENT_TYPE, TEXT_PLAIN) .withStatusCode(HttpStatusCode.OK_200.code()) .withBody("some_body1"), makeRequest( request() .withBody(params(param("bodyParameterName.*", "bodyParameterValue.*"))), headersToIgnore) ); // when mockServerClient .clear( request() .withBody(params(param("bodyParameterNameOne", "bodyParameterValueOne"))) ); // then assertThat( mockServerClient.retrieveExistingExpectations(null), arrayContaining( expectation( request() .withBody(params(param("bodyParameterNameTwo", "bodyParameterValueTwo"))) ) .thenRespond( response() .withBody("some_body2") ) ) ); // - in http assertEquals( response() .withHeader(HttpHeaders.CONTENT_TYPE, TEXT_PLAIN) .withStatusCode(HttpStatusCode.OK_200.code()) .withBody("some_body2"), makeRequest( request() .withBody(params(param("bodyParameterName.*", "bodyParameterValue.*"))), headersToIgnore) ); // - in https assertEquals( response() .withHeader(HttpHeaders.CONTENT_TYPE, TEXT_PLAIN) .withStatusCode(HttpStatusCode.OK_200.code()) .withBody("some_body2"), makeRequest( request() .withSecure(true) .withBody(params(param("bodyParameterName.*", "bodyParameterValue.*"))), headersToIgnore) ); } @Test public void shouldReset() { // given mockServerClient .when( request() .withPath(calculatePath("some_path1")) ) .respond( response() .withBody("some_body1") ); mockServerClient .when( request() .withPath(calculatePath("some_path2")) ) .respond( response() .withBody("some_body2") ); // when mockServerClient.reset(); // then // - in http assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()), makeRequest( request() .withPath(calculatePath("some_path1")), headersToIgnore) ); assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()), makeRequest( request() .withPath(calculatePath("some_path2")), headersToIgnore) ); // - in https assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()), makeRequest( request() .withSecure(true) .withPath(calculatePath("some_path1")), headersToIgnore) ); assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()), makeRequest( request() .withSecure(true) .withPath(calculatePath("some_path2")), headersToIgnore) ); } @Test public void shouldEnsureThatRequestDelaysDoNotAffectOtherRequests() throws Exception { mockServerClient .when( request("/slow") ) .respond( response("super slow") .withDelay(new Delay(TimeUnit.SECONDS, 8)) ); mockServerClient .when( request("/fast") ) .respond( response("quite fast") ); ExecutorService executorService = Executors.newFixedThreadPool(2); Future<Long> slowFuture = executorService.submit(new Callable<Long>() { @Override public Long call() throws Exception { long start = System.currentTimeMillis(); makeRequest(request("/slow")); return System.currentTimeMillis() - start; } }); // Let fast request come to the server slightly after slow request Uninterruptibles.sleepUninterruptibly(1, TimeUnit.SECONDS); Future<Long> fastFuture = executorService.submit(new Callable<Long>() { @Override public Long call() throws Exception { long start = System.currentTimeMillis(); makeRequest(request("/fast")); return System.currentTimeMillis() - start; } }); Long slowRequestElapsedMillis = slowFuture.get(); Long fastRequestElapsedMillis = fastFuture.get(); assertThat("Slow request takes less than expected", slowRequestElapsedMillis, is(greaterThan(7 * 1000L))); assertThat("Fast request takes longer than expected", fastRequestElapsedMillis, is(lessThan(3 * 1000L))); } protected void verifyRequestMatches(HttpRequest[] httpRequests, HttpRequest... httpRequestMatchers) { if (httpRequests.length != httpRequestMatchers.length) { throw new AssertionError("Number of request matchers does not match number of requests, expected:<" + httpRequestMatchers.length + "> but was:<" + httpRequests.length + ">"); } else { for (int i = 0; i < httpRequestMatchers.length; i++) { if (!new HttpRequestMatcher(httpRequestMatchers[i]).matches(httpRequests[i])) { throw new AssertionError("Request does not match request matcher, expected:<" + httpRequestMatchers[i] + "> but was:<" + httpRequests[i] + ">"); } } } } protected HttpResponse makeRequest(HttpRequest httpRequest) { return makeRequest(httpRequest, Collections.<String>emptySet()); } protected HttpResponse makeRequest(HttpRequest httpRequest, Collection<String> headersToIgnore) { int attemptsRemaining = 10; while (attemptsRemaining > 0) { try { boolean isSsl = httpRequest.isSecure() != null && httpRequest.isSecure(); int port = (isSsl ? getMockServerSecurePort() : getMockServerPort()); HttpResponse httpResponse = httpClient.sendRequest(outboundRequest("localhost", port, servletContext, httpRequest)); List<Header> headers = new ArrayList<Header>(); for (Header header : httpResponse.getHeaders()) { if (!headersToIgnore.contains(header.getName().getValue().toLowerCase())) { if (header.getName().getValue().equalsIgnoreCase(HttpHeaders.CONTENT_TYPE)) { // this fixes Tomcat which removes the space between // media type and charset in the Content-Type header for (NottableString value : new ArrayList<NottableString>(header.getValues())) { header.getValues().clear(); header.addValues(value.getValue().replace(";charset", "; charset")); } } headers.add(header); } } httpResponse.withHeaders(headers); return httpResponse; } catch (SocketConnectionException caught) { attemptsRemaining--; logger.info("Retrying connection to mock server, attempts remaining: " + attemptsRemaining); try { TimeUnit.MILLISECONDS.sleep(500); } catch (InterruptedException e) { // do nothing } } } throw new RuntimeException("Failed to send request:" + System.getProperty("line.separator") + httpRequest); } }
emidander/mockserver
mockserver-integration-testing/src/main/java/org/mockserver/integration/server/AbstractClientServerIntegrationTest.java
925
package org.mockserver.integration.server; import com.google.common.base.Charsets; import com.google.common.net.HttpHeaders; import com.google.common.net.MediaType; import com.google.common.util.concurrent.Uninterruptibles; import org.apache.commons.io.IOUtils; import org.junit.Before; import org.junit.Test; import org.mockserver.client.netty.NettyHttpClient; import org.mockserver.client.netty.SocketConnectionException; import org.mockserver.client.server.MockServerClient; import org.mockserver.echo.http.EchoServer; import org.mockserver.matchers.HttpRequestMatcher; import org.mockserver.matchers.MatchType; import org.mockserver.matchers.TimeToLive; import org.mockserver.matchers.Times; import org.mockserver.mock.Expectation; import org.mockserver.model.*; import org.mockserver.socket.PortFactory; import org.mockserver.verify.VerificationTimes; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.IOException; import java.util.*; import java.util.concurrent.*; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.*; import static org.hamcrest.core.Is.is; import static org.hamcrest.core.StringStartsWith.startsWith; import static org.hamcrest.number.OrderingComparison.greaterThan; import static org.junit.Assert.*; import static org.mockserver.matchers.Times.exactly; import static org.mockserver.matchers.Times.once; import static org.mockserver.model.BinaryBody.binary; import static org.mockserver.model.Cookie.cookie; import static org.mockserver.model.Header.header; import static org.mockserver.model.HttpCallback.callback; import static org.mockserver.model.HttpForward.forward; import static org.mockserver.model.HttpRequest.request; import static org.mockserver.model.HttpResponse.notFoundResponse; import static org.mockserver.model.HttpResponse.response; import static org.mockserver.model.JsonBody.json; import static org.mockserver.model.JsonSchemaBody.jsonSchema; import static org.mockserver.model.NottableString.not; import static org.mockserver.model.NottableString.string; import static org.mockserver.model.OutboundHttpRequest.outboundRequest; import static org.mockserver.model.Parameter.param; import static org.mockserver.model.ParameterBody.params; import static org.mockserver.model.StringBody.exact; import static org.mockserver.model.XPathBody.xpath; import static org.mockserver.model.XmlBody.xml; /** * @author jamesdbloom */ public abstract class AbstractClientServerIntegrationTest { protected static final String TEXT_PLAIN = MediaType.create("text", "plain").toString(); protected static MockServerClient mockServerClient; protected static String servletContext = ""; private final Logger logger = LoggerFactory.getLogger(this.getClass()); protected List<String> headersToIgnore = Arrays.asList( "server", "expires", "date", "host", "connection", "user-agent", "content-length", "accept-encoding", "transfer-encoding", "access-control-allow-origin", "access-control-allow-methods", "x-cors" ); private NettyHttpClient httpClient = new NettyHttpClient(); public static Expectation expectation(HttpRequest httpRequest) { return new Expectation(httpRequest, Times.unlimited(), TimeToLive.unlimited()); } public abstract int getMockServerPort(); public abstract int getMockServerSecurePort(); public abstract int getTestServerPort(); protected String calculatePath(String path) { return "/" + path; } @Before public void resetServer() { mockServerClient.reset(); } @Test public void shouldForwardRequestInHTTP() { // when mockServerClient .when( request() .withPath(calculatePath("echo")) ) .forward( forward() .withHost("127.0.0.1") .withPort(getTestServerPort()) ); // then // - in http assertEquals( response() .withStatusCode(HttpStatusCode.OK_200.code()) .withHeaders( header("x-test", "test_headers_and_body"), header(HttpHeaders.CONTENT_TYPE, TEXT_PLAIN) ) .withBody("an_example_body_http"), makeRequest( request() .withPath(calculatePath("echo")) .withMethod("POST") .withHeaders( header("x-test", "test_headers_and_body") ) .withBody("an_example_body_http"), headersToIgnore) ); // - in https assertEquals( response() .withStatusCode(HttpStatusCode.OK_200.code()) .withHeaders( header("x-test", "test_headers_and_body"), header(HttpHeaders.CONTENT_TYPE, TEXT_PLAIN) ) .withBody("an_example_body_https"), makeRequest( request() .withSecure(true) .withPath(calculatePath("echo")) .withMethod("POST") .withHeaders( header("x-test", "test_headers_and_body") ) .withBody("an_example_body_https"), headersToIgnore) ); } @Test public void shouldForwardRequestInHTTPS() { int testServerHttpsPort = PortFactory.findFreePort(); EchoServer secureEchoServer = new EchoServer(testServerHttpsPort, true); try { // when mockServerClient .when( request() .withPath(calculatePath("echo")) ) .forward( forward() .withHost("127.0.0.1") .withPort(testServerHttpsPort) .withScheme(HttpForward.Scheme.HTTPS) ); // then // - in http assertEquals( response() .withStatusCode(HttpStatusCode.OK_200.code()) .withHeaders( header("x-test", "test_headers_and_body"), header(HttpHeaders.CONTENT_TYPE, TEXT_PLAIN) ) .withBody("an_example_body_http"), makeRequest( request() .withPath(calculatePath("echo")) .withMethod("POST") .withHeaders( header("x-test", "test_headers_and_body") ) .withBody("an_example_body_http"), headersToIgnore) ); // - in https assertEquals( response() .withStatusCode(HttpStatusCode.OK_200.code()) .withHeaders( header("x-test", "test_headers_and_body"), header(HttpHeaders.CONTENT_TYPE, TEXT_PLAIN) ) .withBody("an_example_body_https"), makeRequest( request() .withSecure(true) .withPath(calculatePath("echo")) .withMethod("POST") .withHeaders( header("x-test", "test_headers_and_body") ) .withBody("an_example_body_https"), headersToIgnore) ); } finally { secureEchoServer.stop(); } } @Test public void shouldAllowSimultaneousForwardAndResponseExpectations() { // when mockServerClient .when( request() .withPath(calculatePath("echo")), once() ) .forward( forward() .withHost("127.0.0.1") .withPort(getTestServerPort()) ); mockServerClient .when( request() .withPath(calculatePath("test_headers_and_body")), once() ) .respond( response() .withBody("some_body") ); // then // - forward assertEquals( response() .withStatusCode(HttpStatusCode.OK_200.code()) .withHeaders( header("x-test", "test_headers_and_body"), header(HttpHeaders.CONTENT_TYPE, TEXT_PLAIN) ) .withBody("an_example_body"), makeRequest( request() .withPath(calculatePath("echo")) .withMethod("POST") .withHeaders( header("x-test", "test_headers_and_body") ) .withBody("an_example_body"), headersToIgnore) ); // - respond assertEquals( response() .withHeader(HttpHeaders.CONTENT_TYPE, TEXT_PLAIN) .withStatusCode(HttpStatusCode.OK_200.code()) .withBody("some_body"), makeRequest( request() .withPath(calculatePath("test_headers_and_body")), headersToIgnore) ); // - no response or forward assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()), makeRequest( request() .withPath(calculatePath("test_headers_and_body")), headersToIgnore) ); } @Test public void shouldCallbackToSpecifiedClassWithPrecannedResponse() { // when mockServerClient .when( request() .withPath(calculatePath("callback")) ) .callback( callback() .withCallbackClass("org.mockserver.integration.callback.PrecannedTestExpectationCallback") ); // then // - in http assertEquals( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withHeaders( header("x-callback", "test_callback_header"), header(HttpHeaders.CONTENT_TYPE, TEXT_PLAIN) ) .withBody("a_callback_response"), makeRequest( request() .withPath(calculatePath("callback")) .withMethod("POST") .withHeaders( header("x-test", "test_headers_and_body") ) .withBody("an_example_body_http"), headersToIgnore ) ); // - in https assertEquals( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withHeaders( header("x-callback", "test_callback_header"), header(HttpHeaders.CONTENT_TYPE, TEXT_PLAIN) ) .withBody("a_callback_response"), makeRequest( request() .withSecure(true) .withPath(calculatePath("callback")) .withMethod("POST") .withHeaders( header("x-test", "test_headers_and_body") ) .withBody("an_example_body_https"), headersToIgnore ) ); } @Test public void shouldReturnResponseWithOnlyBody() { // when mockServerClient.when(request()).respond(response().withBody("some_body")); // then // - in http assertEquals( response() .withHeader(HttpHeaders.CONTENT_TYPE, TEXT_PLAIN) .withStatusCode(HttpStatusCode.OK_200.code()) .withBody("some_body"), makeRequest( request() .withPath(calculatePath("")), headersToIgnore) ); // - in https assertEquals( response() .withHeader(HttpHeaders.CONTENT_TYPE, TEXT_PLAIN) .withStatusCode(HttpStatusCode.OK_200.code()) .withBody("some_body"), makeRequest( request() .withSecure(true) .withPath(calculatePath("")), headersToIgnore) ); } @Test public void shouldReturnResponseForRequestInSsl() { // when mockServerClient.when(request().withSecure(true)).respond(response().withBody("some_body")); // then // - in http assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()), makeRequest( request() .withPath(calculatePath("")), headersToIgnore) ); // - in https assertEquals( response() .withHeader(HttpHeaders.CONTENT_TYPE, TEXT_PLAIN) .withStatusCode(HttpStatusCode.OK_200.code()) .withBody("some_body"), makeRequest( request() .withSecure(true) .withPath(calculatePath("")), headersToIgnore) ); } @Test public void shouldReturnResponseForRequestNotInSsl() { // when mockServerClient.when(request().withSecure(false)).respond(response().withBody("some_body")); // then // - in http assertEquals( response() .withHeader(HttpHeaders.CONTENT_TYPE, TEXT_PLAIN) .withStatusCode(HttpStatusCode.OK_200.code()) .withBody("some_body"), makeRequest( request() .withPath(calculatePath("")), headersToIgnore) ); // - in https assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()), makeRequest( request() .withSecure(true) .withPath(calculatePath("")), headersToIgnore) ); } @Test public void shouldReturnMatchRequestWithBodyInUTF16() { // when String body = "我说中国话"; mockServerClient.when(request().withBody(body, Charsets.UTF_16)).respond(response().withBody(body, Charsets.UTF_8)); // then // - in http assertEquals( response() .withHeader(HttpHeaders.CONTENT_TYPE, MediaType.create("text", "plain").withCharset(Charsets.UTF_8).toString()) .withStatusCode(HttpStatusCode.OK_200.code()) .withBody(body), makeRequest( request() .withPath(calculatePath("")) .withBody(body, Charsets.UTF_16), headersToIgnore) ); // - in https assertEquals( response() .withHeader(HttpHeaders.CONTENT_TYPE, MediaType.create("text", "plain").withCharset(Charsets.UTF_8).toString()) .withStatusCode(HttpStatusCode.OK_200.code()) .withBody(body), makeRequest( request() .withSecure(true) .withPath(calculatePath("")) .withBody(body, Charsets.UTF_16), headersToIgnore) ); } @Test public void shouldReturnMatchRequestWithBodyInUTF16WithContentTypeHeader() { // when String body = "我说中国话"; mockServerClient .when( request() .withHeader(HttpHeaders.CONTENT_TYPE, MediaType.create("text", "plain").withCharset(Charsets.UTF_8).toString()) .withBody(body) ) .respond( response() .withBody(body, Charsets.UTF_8) ); // then // - in http assertEquals( response() .withHeader(HttpHeaders.CONTENT_TYPE, MediaType.create("text", "plain").withCharset(Charsets.UTF_8).toString()) .withStatusCode(HttpStatusCode.OK_200.code()) .withBody(body), makeRequest( request() .withHeader(HttpHeaders.CONTENT_TYPE, MediaType.create("text", "plain").withCharset(Charsets.UTF_8).toString()) .withPath(calculatePath("")) .withBody(body), headersToIgnore) ); // - in https assertEquals( response() .withHeader(HttpHeaders.CONTENT_TYPE, MediaType.create("text", "plain").withCharset(Charsets.UTF_8).toString()) .withStatusCode(HttpStatusCode.OK_200.code()) .withBody(body), makeRequest( request() .withHeader(HttpHeaders.CONTENT_TYPE, MediaType.create("text", "plain").withCharset(Charsets.UTF_8).toString()) .withSecure(true) .withPath(calculatePath("")) .withBody(body), headersToIgnore) ); } @Test public void shouldReturnResponseWithBodyInUTF8() { // when String body = "我说中国话"; mockServerClient.when(request()).respond(response().withBody(body, Charsets.UTF_16)); // then // - in http assertEquals( response() .withHeader(HttpHeaders.CONTENT_TYPE, MediaType.create("text", "plain").withCharset(Charsets.UTF_16).toString()) .withStatusCode(HttpStatusCode.OK_200.code()) .withBody(body), makeRequest( request() .withPath(calculatePath("")), headersToIgnore) ); // - in https assertEquals( response() .withHeader(HttpHeaders.CONTENT_TYPE, MediaType.create("text", "plain").withCharset(Charsets.UTF_16).toString()) .withStatusCode(HttpStatusCode.OK_200.code()) .withBody(body), makeRequest( request() .withSecure(true) .withPath(calculatePath("")), headersToIgnore) ); } @Test public void shouldReturnResponseWithBodyInUTF16WithContentTypeHeader() { // when String body = "我说中国话"; mockServerClient .when( request() ) .respond( response() .withHeader(HttpHeaders.CONTENT_TYPE, MediaType.create("text", "plain").withCharset(Charsets.UTF_8).toString()) .withBody(body) ); // then // - in http assertEquals( response() .withHeader(HttpHeaders.CONTENT_TYPE, MediaType.create("text", "plain").withCharset(Charsets.UTF_8).toString()) .withStatusCode(HttpStatusCode.OK_200.code()) .withBody(body), makeRequest( request() .withPath(calculatePath("")), headersToIgnore) ); // - in https assertEquals( response() .withHeader(HttpHeaders.CONTENT_TYPE, MediaType.create("text", "plain").withCharset(Charsets.UTF_8).toString()) .withStatusCode(HttpStatusCode.OK_200.code()) .withBody(body), makeRequest( request() .withSecure(true) .withPath(calculatePath("")), headersToIgnore) ); } @Test public void shouldReturnResponseWithOnlyStatusCode() { // when mockServerClient .when( request() .withMethod("POST") .withPath(calculatePath("some_path")) ) .respond( response() .withStatusCode(200) ); // then // - in http assertEquals( response() .withStatusCode(HttpStatusCode.OK_200.code()), makeRequest( request() .withPath(calculatePath("some_path")) .withMethod("POST"), headersToIgnore) ); // - in https assertEquals( response() .withStatusCode(HttpStatusCode.OK_200.code()), makeRequest( request() .withSecure(true) .withPath(calculatePath("some_path")) .withMethod("POST"), headersToIgnore) ); } @Test public void shouldReturnResponseByMatchingPath() { // when mockServerClient .when( request() .withPath(calculatePath("some_path1")) ) .respond( response() .withBody("some_body1") ); mockServerClient .when( request() .withPath(calculatePath("some_path2")) ) .respond( response() .withBody("some_body2") ); // then // - in http assertEquals( response() .withHeader(HttpHeaders.CONTENT_TYPE, TEXT_PLAIN) .withStatusCode(HttpStatusCode.OK_200.code()) .withBody("some_body2"), makeRequest( request() .withPath(calculatePath("some_path2")), headersToIgnore) ); assertEquals( response() .withHeader(HttpHeaders.CONTENT_TYPE, TEXT_PLAIN) .withStatusCode(HttpStatusCode.OK_200.code()) .withBody("some_body1"), makeRequest( request() .withPath(calculatePath("some_path1")), headersToIgnore) ); // - in https assertEquals( response() .withHeader(HttpHeaders.CONTENT_TYPE, TEXT_PLAIN) .withStatusCode(HttpStatusCode.OK_200.code()) .withBody("some_body2"), makeRequest( request() .withSecure(true) .withPath(calculatePath("some_path2")), headersToIgnore) ); assertEquals( response() .withHeader(HttpHeaders.CONTENT_TYPE, TEXT_PLAIN) .withStatusCode(HttpStatusCode.OK_200.code()) .withBody("some_body1"), makeRequest( request() .withSecure(true) .withPath(calculatePath("some_path1")), headersToIgnore) ); } @Test public void shouldReturnResponseByMatchingPathExactTimes() { // when mockServerClient .when( request() .withPath(calculatePath("some_path")), exactly(2) ) .respond( response() .withBody("some_body") ); // then // - in http assertEquals( response() .withHeader(HttpHeaders.CONTENT_TYPE, TEXT_PLAIN) .withStatusCode(HttpStatusCode.OK_200.code()) .withBody("some_body"), makeRequest( request() .withPath(calculatePath("some_path")), headersToIgnore) ); // - in https assertEquals( response() .withHeader(HttpHeaders.CONTENT_TYPE, TEXT_PLAIN) .withStatusCode(HttpStatusCode.OK_200.code()) .withBody("some_body"), makeRequest( request() .withSecure(true) .withPath(calculatePath("some_path")), headersToIgnore) ); // - in http assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()), makeRequest( request() .withPath(calculatePath("some_path")), headersToIgnore) ); // - in https assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()), makeRequest( request() .withSecure(true) .withPath(calculatePath("some_path")), headersToIgnore) ); } @Test public void shouldReturnResponseWhenTimeToLiveHasNotExpired() { // when mockServerClient .when( request().withPath(calculatePath("some_path")), exactly(2), TimeToLive.exactly(TimeUnit.HOURS, 1L) ) .respond( response().withBody("some_body") ); // then // - in http assertEquals( response() .withHeader(HttpHeaders.CONTENT_TYPE, TEXT_PLAIN) .withStatusCode(HttpStatusCode.OK_200.code()) .withBody("some_body"), makeRequest( request() .withPath(calculatePath("some_path")), headersToIgnore) ); // - in https assertEquals( response() .withHeader(HttpHeaders.CONTENT_TYPE, TEXT_PLAIN) .withStatusCode(HttpStatusCode.OK_200.code()) .withBody("some_body"), makeRequest( request() .withSecure(true) .withPath(calculatePath("some_path")), headersToIgnore) ); // - in http assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()), makeRequest( request() .withPath(calculatePath("some_path")), headersToIgnore) ); // - in https assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()), makeRequest( request() .withSecure(true) .withPath(calculatePath("some_path")), headersToIgnore) ); } @Test public void shouldReturnResponseByMatchingBodyWithXPath() { // when mockServerClient.when(request().withBody(xpath("/bookstore/book[price>30]/price")), exactly(2)).respond(response().withBody("some_body")); // then // - in http assertEquals( response() .withHeader(HttpHeaders.CONTENT_TYPE, TEXT_PLAIN) .withStatusCode(HttpStatusCode.OK_200.code()) .withBody("some_body"), makeRequest( request() .withPath(calculatePath("some_path")) .withMethod("POST") .withBody(new StringBody("" + "<?xml version=\"1.0\" encoding=\"ISO-8859-1\"?>" + System.getProperty("line.separator") + "<bookstore>" + System.getProperty("line.separator") + " <book category=\"COOKING\">" + System.getProperty("line.separator") + " <title lang=\"en\">Everyday Italian</title>" + System.getProperty("line.separator") + " <author>Giada De Laurentiis</author>" + System.getProperty("line.separator") + " <year>2005</year>" + System.getProperty("line.separator") + " <price>30.00</price>" + System.getProperty("line.separator") + " </book>" + System.getProperty("line.separator") + " <book category=\"CHILDREN\">" + System.getProperty("line.separator") + " <title lang=\"en\">Harry Potter</title>" + System.getProperty("line.separator") + " <author>J K. Rowling</author>" + System.getProperty("line.separator") + " <year>2005</year>" + System.getProperty("line.separator") + " <price>29.99</price>" + System.getProperty("line.separator") + " </book>" + System.getProperty("line.separator") + " <book category=\"WEB\">" + System.getProperty("line.separator") + " <title lang=\"en\">Learning XML</title>" + System.getProperty("line.separator") + " <author>Erik T. Ray</author>" + System.getProperty("line.separator") + " <year>2003</year>" + System.getProperty("line.separator") + " <price>31.95</price>" + System.getProperty("line.separator") + " </book>" + System.getProperty("line.separator") + "</bookstore>")), headersToIgnore) ); // - in https assertEquals( response() .withHeader(HttpHeaders.CONTENT_TYPE, TEXT_PLAIN) .withStatusCode(HttpStatusCode.OK_200.code()) .withBody("some_body"), makeRequest( request() .withSecure(true) .withPath(calculatePath("some_path")) .withMethod("POST") .withBody(new StringBody("" + "<?xml version=\"1.0\" encoding=\"ISO-8859-1\"?>" + System.getProperty("line.separator") + "<bookstore>" + System.getProperty("line.separator") + " <book category=\"COOKING\">" + System.getProperty("line.separator") + " <title lang=\"en\">Everyday Italian</title>" + System.getProperty("line.separator") + " <author>Giada De Laurentiis</author>" + System.getProperty("line.separator") + " <year>2005</year>" + System.getProperty("line.separator") + " <price>30.00</price>" + System.getProperty("line.separator") + " </book>" + System.getProperty("line.separator") + " <book category=\"CHILDREN\">" + System.getProperty("line.separator") + " <title lang=\"en\">Harry Potter</title>" + System.getProperty("line.separator") + " <author>J K. Rowling</author>" + System.getProperty("line.separator") + " <year>2005</year>" + System.getProperty("line.separator") + " <price>29.99</price>" + System.getProperty("line.separator") + " </book>" + System.getProperty("line.separator") + " <book category=\"WEB\">" + System.getProperty("line.separator") + " <title lang=\"en\">Learning XML</title>" + System.getProperty("line.separator") + " <author>Erik T. Ray</author>" + System.getProperty("line.separator") + " <year>2003</year>" + System.getProperty("line.separator") + " <price>31.95</price>" + System.getProperty("line.separator") + " </book>" + System.getProperty("line.separator") + "</bookstore>")), headersToIgnore) ); } @Test public void shouldReturnResponseByMatchingBodyWithXml() { // when mockServerClient.when(request().withBody(xml("" + "<bookstore>" + System.getProperty("line.separator") + " <book nationality=\"ITALIAN\" category=\"COOKING\"><title lang=\"en\">Everyday Italian</title><author>Giada De Laurentiis</author><year>2005</year><price>30.00</price></book>" + System.getProperty("line.separator") + "</bookstore>")), exactly(2)).respond(response().withBody("some_body")); // then // - in http assertEquals( response() .withHeader(HttpHeaders.CONTENT_TYPE, TEXT_PLAIN) .withStatusCode(HttpStatusCode.OK_200.code()) .withBody("some_body"), makeRequest( request() .withPath(calculatePath("some_path")) .withMethod("POST") .withBody(new StringBody("" + "<?xml version=\"1.0\" encoding=\"ISO-8859-1\"?>" + System.getProperty("line.separator") + "<bookstore>" + System.getProperty("line.separator") + " <book category=\"COOKING\" nationality=\"ITALIAN\">" + System.getProperty("line.separator") + " <title lang=\"en\">Everyday Italian</title>" + System.getProperty("line.separator") + " <author>Giada De Laurentiis</author>" + System.getProperty("line.separator") + " <year>2005</year>" + System.getProperty("line.separator") + " <price>30.00</price>" + System.getProperty("line.separator") + " </book>" + System.getProperty("line.separator") + "</bookstore>")), headersToIgnore) ); // - in https assertEquals( response() .withHeader(HttpHeaders.CONTENT_TYPE, TEXT_PLAIN) .withStatusCode(HttpStatusCode.OK_200.code()) .withBody("some_body"), makeRequest( request() .withSecure(true) .withPath(calculatePath("some_path")) .withMethod("POST") .withBody(new StringBody("" + "<?xml version=\"1.0\" encoding=\"ISO-8859-1\"?>" + System.getProperty("line.separator") + "<bookstore>" + System.getProperty("line.separator") + " <book category=\"COOKING\" nationality=\"ITALIAN\">" + System.getProperty("line.separator") + " <title lang=\"en\">Everyday Italian</title>" + System.getProperty("line.separator") + " <author>Giada De Laurentiis</author>" + System.getProperty("line.separator") + " <year>2005</year>" + System.getProperty("line.separator") + " <price>30.00</price>" + System.getProperty("line.separator") + " </book>" + System.getProperty("line.separator") + "</bookstore>")), headersToIgnore) ); } @Test public void shouldReturnResponseByMatchingBodyWithJson() { // when mockServerClient .when( request() .withBody(json("{" + System.getProperty("line.separator") + " \"id\": 1," + System.getProperty("line.separator") + " \"name\": \"A green door\"," + System.getProperty("line.separator") + " \"price\": 12.50," + System.getProperty("line.separator") + " \"tags\": [\"home\", \"green\"]" + System.getProperty("line.separator") + "}")), exactly(2) ) .respond( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body") ); // then // - in http assertEquals( response() .withHeader(HttpHeaders.CONTENT_TYPE, TEXT_PLAIN) .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body"), makeRequest( request() .withPath(calculatePath("some_path")) .withMethod("POST") .withBody("{" + System.getProperty("line.separator") + " \"id\": 1," + System.getProperty("line.separator") + " \"extra ignored field\": \"some value\"," + System.getProperty("line.separator") + " \"name\": \"A green door\"," + System.getProperty("line.separator") + " \"price\": 12.50," + System.getProperty("line.separator") + " \"tags\": [\"home\", \"green\"]" + System.getProperty("line.separator") + "}"), headersToIgnore) ); // - in https assertEquals( response() .withHeader(HttpHeaders.CONTENT_TYPE, TEXT_PLAIN) .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body"), makeRequest( request() .withSecure(true) .withPath(calculatePath("some_path")) .withMethod("POST") .withBody("{" + System.getProperty("line.separator") + " \"id\": 1," + System.getProperty("line.separator") + " \"extra ignored array\": [\"one\", \"two\"]," + System.getProperty("line.separator") + " \"name\": \"A green door\"," + System.getProperty("line.separator") + " \"price\": 12.50," + System.getProperty("line.separator") + " \"tags\": [\"home\", \"green\"]" + System.getProperty("line.separator") + "}"), headersToIgnore) ); } @Test public void shouldReturnResponseByMatchingBodyWithJsonWithCharsetUTF8() { // when mockServerClient .when( request() .withBody(json("{" + System.getProperty("line.separator") + " \"ταυτότητα\": 1," + System.getProperty("line.separator") + " \"όνομα\": \"μια πράσινη πόρτα\"," + System.getProperty("line.separator") + " \"τιμή\": 12.50," + System.getProperty("line.separator") + " \"ετικέτες\": [\"σπίτι\", \"πράσινος\"]" + System.getProperty("line.separator") + "}", Charsets.UTF_16, MatchType.ONLY_MATCHING_FIELDS)), exactly(2) ) .respond( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body") ); // then // - in http assertEquals( response() .withHeader(HttpHeaders.CONTENT_TYPE, TEXT_PLAIN) .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body"), makeRequest( request() .withPath(calculatePath("some_path")) .withMethod("POST") .withBody(json("{" + System.getProperty("line.separator") + " \"ταυτότητα\": 1," + System.getProperty("line.separator") + " \"επιπλέον αγνοούνται τομέα\": \"κάποια αξία\"," + System.getProperty("line.separator") + " \"όνομα\": \"μια πράσινη πόρτα\"," + System.getProperty("line.separator") + " \"τιμή\": 12.50," + System.getProperty("line.separator") + " \"ετικέτες\": [\"σπίτι\", \"πράσινος\"]" + System.getProperty("line.separator") + "}", Charsets.UTF_16, MatchType.ONLY_MATCHING_FIELDS)), headersToIgnore) ); // - in https assertEquals( response() .withHeader(HttpHeaders.CONTENT_TYPE, TEXT_PLAIN) .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body"), makeRequest( request() .withSecure(true) .withPath(calculatePath("some_path")) .withMethod("POST") .withBody(json("{" + System.getProperty("line.separator") + " \"ταυτότητα\": 1," + System.getProperty("line.separator") + " \"επιπλέον αγνοούνται σειρά\": [\"ένας\", \"δυο\"]," + System.getProperty("line.separator") + " \"όνομα\": \"μια πράσινη πόρτα\"," + System.getProperty("line.separator") + " \"τιμή\": 12.50," + System.getProperty("line.separator") + " \"ετικέτες\": [\"σπίτι\", \"πράσινος\"]" + System.getProperty("line.separator") + "}", Charsets.UTF_16, MatchType.ONLY_MATCHING_FIELDS)), headersToIgnore) ); } @Test public void shouldReturnResponseByMatchingBodyWithJsonWithContentTypeHeader() { // when mockServerClient .when( request() .withBody(json("{" + System.getProperty("line.separator") + " \"ταυτότητα\": 1," + System.getProperty("line.separator") + " \"όνομα\": \"μια πράσινη πόρτα\"," + System.getProperty("line.separator") + " \"τιμή\": 12.50," + System.getProperty("line.separator") + " \"ετικέτες\": [\"σπίτι\", \"πράσινος\"]" + System.getProperty("line.separator") + "}", Charsets.UTF_16, MatchType.ONLY_MATCHING_FIELDS)), exactly(2) ) .respond( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body") ); // then // - in http assertEquals( response() .withHeader(HttpHeaders.CONTENT_TYPE, TEXT_PLAIN) .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body"), makeRequest( request() .withHeader(HttpHeaders.CONTENT_TYPE, MediaType.create("text", "plain").withCharset(Charsets.UTF_16).toString()) .withPath(calculatePath("some_path")) .withMethod("POST") .withBody(json("{" + System.getProperty("line.separator") + " \"ταυτότητα\": 1," + System.getProperty("line.separator") + " \"επιπλέον αγνοούνται τομέα\": \"κάποια αξία\"," + System.getProperty("line.separator") + " \"όνομα\": \"μια πράσινη πόρτα\"," + System.getProperty("line.separator") + " \"τιμή\": 12.50," + System.getProperty("line.separator") + " \"ετικέτες\": [\"σπίτι\", \"πράσινος\"]" + System.getProperty("line.separator") + "}")), headersToIgnore) ); // - in https assertEquals( response() .withHeader(HttpHeaders.CONTENT_TYPE, TEXT_PLAIN) .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body"), makeRequest( request() .withSecure(true) .withHeader(HttpHeaders.CONTENT_TYPE, MediaType.create("text", "plain").withCharset(Charsets.UTF_16).toString()) .withPath(calculatePath("some_path")) .withMethod("POST") .withBody(json("{" + System.getProperty("line.separator") + " \"ταυτότητα\": 1," + System.getProperty("line.separator") + " \"επιπλέον αγνοούνται σειρά\": [\"ένας\", \"δυο\"]," + System.getProperty("line.separator") + " \"όνομα\": \"μια πράσινη πόρτα\"," + System.getProperty("line.separator") + " \"τιμή\": 12.50," + System.getProperty("line.separator") + " \"ετικέτες\": [\"σπίτι\", \"πράσινος\"]" + System.getProperty("line.separator") + "}")), headersToIgnore) ); } @Test public void shouldReturnResponseByMatchingBodyWithJsonWithMatchType() { // when mockServerClient .when( request() .withBody(json("{" + System.getProperty("line.separator") + " \"id\": 1," + System.getProperty("line.separator") + " \"name\": \"A green door\"," + System.getProperty("line.separator") + " \"price\": 12.50," + System.getProperty("line.separator") + " \"tags\": [\"home\", \"green\"]" + System.getProperty("line.separator") + "}", MatchType.ONLY_MATCHING_FIELDS)), exactly(2) ) .respond( response() .withBody("some_body") ); // then // - in http assertEquals( response("some_body").withHeader(HttpHeaders.CONTENT_TYPE, TEXT_PLAIN), makeRequest( request() .withPath(calculatePath("some_path")) .withMethod("POST") .withBody("{" + System.getProperty("line.separator") + " \"id\": 1," + System.getProperty("line.separator") + " \"extra field\": \"some value\"," + System.getProperty("line.separator") + " \"name\": \"A green door\"," + System.getProperty("line.separator") + " \"price\": 12.50," + System.getProperty("line.separator") + " \"tags\": [\"home\", \"green\"]" + System.getProperty("line.separator") + "}"), headersToIgnore) ); // - in https assertEquals( response("some_body").withHeader(HttpHeaders.CONTENT_TYPE, TEXT_PLAIN), makeRequest( request() .withSecure(true) .withPath(calculatePath("some_path")) .withMethod("POST") .withBody("{" + System.getProperty("line.separator") + " \"id\": 1," + System.getProperty("line.separator") + " \"extra field\": \"some value\"," + System.getProperty("line.separator") + " \"name\": \"A green door\"," + System.getProperty("line.separator") + " \"price\": 12.50," + System.getProperty("line.separator") + " \"tags\": [\"home\", \"green\"]" + System.getProperty("line.separator") + "}"), headersToIgnore) ); } @Test public void shouldReturnResponseByMatchingBodyWithJsonSchema() { // when mockServerClient.when(request().withBody(jsonSchema("{" + System.getProperty("line.separator") + " \"$schema\": \"http://json-schema.org/draft-04/schema#\"," + System.getProperty("line.separator") + " \"title\": \"Product\"," + System.getProperty("line.separator") + " \"description\": \"A product from Acme's catalog\"," + System.getProperty("line.separator") + " \"type\": \"object\"," + System.getProperty("line.separator") + " \"properties\": {" + System.getProperty("line.separator") + " \"id\": {" + System.getProperty("line.separator") + " \"description\": \"The unique identifier for a product\"," + System.getProperty("line.separator") + " \"type\": \"integer\"" + System.getProperty("line.separator") + " }," + System.getProperty("line.separator") + " \"name\": {" + System.getProperty("line.separator") + " \"description\": \"Name of the product\"," + System.getProperty("line.separator") + " \"type\": \"string\"" + System.getProperty("line.separator") + " }," + System.getProperty("line.separator") + " \"price\": {" + System.getProperty("line.separator") + " \"type\": \"number\"," + System.getProperty("line.separator") + " \"minimum\": 0," + System.getProperty("line.separator") + " \"exclusiveMinimum\": true" + System.getProperty("line.separator") + " }," + System.getProperty("line.separator") + " \"tags\": {" + System.getProperty("line.separator") + " \"type\": \"array\"," + System.getProperty("line.separator") + " \"items\": {" + System.getProperty("line.separator") + " \"type\": \"string\"" + System.getProperty("line.separator") + " }," + System.getProperty("line.separator") + " \"minItems\": 1," + System.getProperty("line.separator") + " \"uniqueItems\": true" + System.getProperty("line.separator") + " }" + System.getProperty("line.separator") + " }," + System.getProperty("line.separator") + " \"required\": [\"id\", \"name\", \"price\"]" + System.getProperty("line.separator") + "}")), exactly(2)).respond(response().withBody("some_body")); // then // - in http assertEquals( response() .withHeader(HttpHeaders.CONTENT_TYPE, TEXT_PLAIN) .withStatusCode(HttpStatusCode.OK_200.code()) .withBody("some_body"), makeRequest( request() .withPath(calculatePath("some_path")) .withMethod("POST") .withBody("{" + System.getProperty("line.separator") + " \"id\": 1," + System.getProperty("line.separator") + " \"name\": \"A green door\"," + System.getProperty("line.separator") + " \"price\": 12.50," + System.getProperty("line.separator") + " \"tags\": [\"home\", \"green\"]" + System.getProperty("line.separator") + "}"), headersToIgnore) ); // - in https assertEquals( response() .withHeader(HttpHeaders.CONTENT_TYPE, TEXT_PLAIN) .withStatusCode(HttpStatusCode.OK_200.code()) .withBody("some_body"), makeRequest( request() .withSecure(true) .withPath(calculatePath("some_path")) .withMethod("POST") .withBody("{" + System.getProperty("line.separator") + " \"id\": 1," + System.getProperty("line.separator") + " \"name\": \"A green door\"," + System.getProperty("line.separator") + " \"price\": 12.50," + System.getProperty("line.separator") + " \"tags\": [\"home\", \"green\"]" + System.getProperty("line.separator") + "}"), headersToIgnore) ); } @Test public void shouldReturnPDFResponseByMatchingPath() throws IOException { // when byte[] pdfBytes = IOUtils.toByteArray(getClass().getClassLoader().getResourceAsStream("test.pdf")); mockServerClient .when( request() .withPath(calculatePath("ws/rest/user/[0-9]+/document/[0-9]+\\.pdf")) ) .respond( response() .withStatusCode(HttpStatusCode.OK_200.code()) .withHeaders( header(HttpHeaders.CONTENT_TYPE, MediaType.PDF.toString()), header(HttpHeaders.CONTENT_DISPOSITION, "form-data; name=\"test.pdf\"; filename=\"test.pdf\""), header(HttpHeaders.CACHE_CONTROL, "must-revalidate, post-check=0, pre-check=0") ) .withBody(binary(pdfBytes)) ); // then // - in http assertEquals( response() .withStatusCode(HttpStatusCode.OK_200.code()) .withHeaders( header(HttpHeaders.CONTENT_DISPOSITION, "form-data; name=\"test.pdf\"; filename=\"test.pdf\""), header(HttpHeaders.CACHE_CONTROL, "must-revalidate, post-check=0, pre-check=0"), header(HttpHeaders.CONTENT_TYPE, MediaType.PDF.toString()) ) .withBody(binary(pdfBytes)), makeRequest( request() .withPath(calculatePath("ws/rest/user/1/document/2.pdf")) .withMethod("GET"), headersToIgnore) ); // - in https assertEquals( response() .withStatusCode(HttpStatusCode.OK_200.code()) .withHeaders( header(HttpHeaders.CONTENT_DISPOSITION, "form-data; name=\"test.pdf\"; filename=\"test.pdf\""), header(HttpHeaders.CACHE_CONTROL, "must-revalidate, post-check=0, pre-check=0"), header(HttpHeaders.CONTENT_TYPE, MediaType.PDF.toString()) ) .withBody(binary(pdfBytes)), makeRequest( request() .withSecure(true) .withPath(calculatePath("ws/rest/user/1/document/2.pdf")) .withMethod("GET"), headersToIgnore) ); } @Test public void shouldReturnPNGResponseByMatchingPath() throws IOException { // when byte[] pngBytes = IOUtils.toByteArray(getClass().getClassLoader().getResourceAsStream("test.png")); mockServerClient .when( request() .withPath(calculatePath("ws/rest/user/[0-9]+/icon/[0-9]+\\.png")) ) .respond( response() .withStatusCode(HttpStatusCode.OK_200.code()) .withHeaders( header(HttpHeaders.CONTENT_TYPE, MediaType.PNG.toString()), header(HttpHeaders.CONTENT_DISPOSITION, "form-data; name=\"test.png\"; filename=\"test.png\"") ) .withBody(binary(pngBytes)) ); // then // - in http assertEquals( response() .withStatusCode(HttpStatusCode.OK_200.code()) .withHeaders( header(HttpHeaders.CONTENT_DISPOSITION, "form-data; name=\"test.png\"; filename=\"test.png\""), header(HttpHeaders.CONTENT_TYPE, MediaType.PNG.toString()) ) .withBody(binary(pngBytes)), makeRequest( request() .withPath(calculatePath("ws/rest/user/1/icon/1.png")) .withMethod("GET"), headersToIgnore) ); // - in https assertEquals( response() .withStatusCode(HttpStatusCode.OK_200.code()) .withHeaders( header(HttpHeaders.CONTENT_DISPOSITION, "form-data; name=\"test.png\"; filename=\"test.png\""), header(HttpHeaders.CONTENT_TYPE, MediaType.PNG.toString()) ) .withBody(binary(pngBytes)), makeRequest( request() .withSecure(true) .withPath(calculatePath("ws/rest/user/1/icon/1.png")) .withMethod("GET"), headersToIgnore) ); } @Test public void shouldReturnPDFResponseByMatchingBinaryPDFBody() throws IOException { // when byte[] pdfBytes = IOUtils.toByteArray(getClass().getClassLoader().getResourceAsStream("test.pdf")); mockServerClient .when( request().withBody(binary(pdfBytes)) ) .respond( response() .withStatusCode(HttpStatusCode.OK_200.code()) .withHeaders( header(HttpHeaders.CONTENT_TYPE, MediaType.PDF.toString()), header(HttpHeaders.CONTENT_DISPOSITION, "form-data; name=\"test.pdf\"; filename=\"test.pdf\""), header(HttpHeaders.CACHE_CONTROL, "must-revalidate, post-check=0, pre-check=0") ) .withBody(binary(pdfBytes)) ); // then // - in http assertEquals( response() .withStatusCode(HttpStatusCode.OK_200.code()) .withHeaders( header(HttpHeaders.CONTENT_DISPOSITION, "form-data; name=\"test.pdf\"; filename=\"test.pdf\""), header(HttpHeaders.CACHE_CONTROL, "must-revalidate, post-check=0, pre-check=0"), header(HttpHeaders.CONTENT_TYPE, MediaType.PDF.toString()) ) .withBody(binary(pdfBytes)), makeRequest( request() .withPath(calculatePath("ws/rest/user/1/document/2.pdf")) .withBody(binary(pdfBytes)) .withMethod("POST"), headersToIgnore) ); // - in https assertEquals( response() .withStatusCode(HttpStatusCode.OK_200.code()) .withHeaders( header(HttpHeaders.CONTENT_DISPOSITION, "form-data; name=\"test.pdf\"; filename=\"test.pdf\""), header(HttpHeaders.CACHE_CONTROL, "must-revalidate, post-check=0, pre-check=0"), header(HttpHeaders.CONTENT_TYPE, MediaType.PDF.toString()) ) .withBody(binary(pdfBytes)), makeRequest( request() .withSecure(true) .withPath(calculatePath("ws/rest/user/1/document/2.pdf")) .withBody(binary(pdfBytes)) .withMethod("POST"), headersToIgnore) ); } @Test public void shouldReturnPNGResponseByMatchingBinaryPNGBody() throws IOException { // when byte[] pngBytes = IOUtils.toByteArray(getClass().getClassLoader().getResourceAsStream("test.png")); mockServerClient .when( request().withBody(binary(pngBytes)) ) .respond( response() .withStatusCode(HttpStatusCode.OK_200.code()) .withHeaders( header(HttpHeaders.CONTENT_TYPE, MediaType.PNG.toString()), header(HttpHeaders.CONTENT_DISPOSITION, "form-data; name=\"test.png\"; filename=\"test.png\"") ) .withBody(binary(pngBytes)) ); // then // - in http assertEquals( response() .withStatusCode(HttpStatusCode.OK_200.code()) .withHeaders( header(HttpHeaders.CONTENT_DISPOSITION, "form-data; name=\"test.png\"; filename=\"test.png\""), header(HttpHeaders.CONTENT_TYPE, MediaType.PNG.toString()) ) .withBody(binary(pngBytes)), makeRequest( request() .withPath(calculatePath("ws/rest/user/1/icon/1.png")) .withBody(binary(pngBytes)) .withMethod("POST"), headersToIgnore) ); // - in https assertEquals( response() .withStatusCode(HttpStatusCode.OK_200.code()) .withHeaders( header(HttpHeaders.CONTENT_DISPOSITION, "form-data; name=\"test.png\"; filename=\"test.png\""), header(HttpHeaders.CONTENT_TYPE, MediaType.PNG.toString()) ) .withBody(binary(pngBytes)), makeRequest( request() .withSecure(true) .withPath(calculatePath("ws/rest/user/1/icon/1.png")) .withBody(binary(pngBytes)) .withMethod("POST"), headersToIgnore) ); } @Test public void shouldReturnResponseForExpectationWithDelay() { // when mockServerClient .when( request() .withPath(calculatePath("some_path1")) ) .respond( response() .withBody("some_body1") .withDelay(new Delay(TimeUnit.MILLISECONDS, 10)) ); mockServerClient .when( request() .withPath(calculatePath("some_path2")) ) .respond( response() .withBody("some_body2") .withDelay(new Delay(TimeUnit.MILLISECONDS, 20)) ); // then // - in http assertEquals( response() .withHeader(HttpHeaders.CONTENT_TYPE, TEXT_PLAIN) .withStatusCode(HttpStatusCode.OK_200.code()) .withBody("some_body2"), makeRequest( request() .withPath(calculatePath("some_path2")), headersToIgnore) ); assertEquals( response() .withHeader(HttpHeaders.CONTENT_TYPE, TEXT_PLAIN) .withStatusCode(HttpStatusCode.OK_200.code()) .withBody("some_body1"), makeRequest( request() .withPath(calculatePath("some_path1")), headersToIgnore) ); // - in https assertEquals( response() .withHeader(HttpHeaders.CONTENT_TYPE, TEXT_PLAIN) .withStatusCode(HttpStatusCode.OK_200.code()) .withBody("some_body2"), makeRequest( request() .withSecure(true) .withPath(calculatePath("some_path2")), headersToIgnore) ); assertEquals( response() .withHeader(HttpHeaders.CONTENT_TYPE, TEXT_PLAIN) .withStatusCode(HttpStatusCode.OK_200.code()) .withBody("some_body1"), makeRequest( request() .withSecure(true) .withPath(calculatePath("some_path1")), headersToIgnore) ); } @Test public void shouldReturnResponseByMatchingPathAndMethod() { // when mockServerClient .when( request() .withMethod("GET") .withPath(calculatePath("some_pathRequest")) ) .respond( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body_response") ); // then // - in http assertEquals( response() .withHeader(HttpHeaders.CONTENT_TYPE, TEXT_PLAIN) .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body_response"), makeRequest( request() .withMethod("GET") .withPath(calculatePath("some_pathRequest")) .withQueryStringParameters( param("queryStringParameterOneName", "queryStringParameterOneValue"), param("queryStringParameterTwoName", "queryStringParameterTwoValue") ) .withHeaders(header("headerNameRequest", "headerValueRequest")) .withCookies(cookie("cookieNameRequest", "cookieValueRequest")), headersToIgnore) ); // - in https assertEquals( response() .withHeader(HttpHeaders.CONTENT_TYPE, TEXT_PLAIN) .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body_response"), makeRequest( request() .withMethod("GET") .withSecure(true) .withPath(calculatePath("some_pathRequest")) .withQueryStringParameters( param("queryStringParameterOneName", "queryStringParameterOneValue"), param("queryStringParameterTwoName", "queryStringParameterTwoValue") ) .withHeaders(header("headerNameRequest", "headerValueRequest")) .withCookies(cookie("cookieNameRequest", "cookieValueRequest")), headersToIgnore) ); } @Test public void shouldReturnResponseByNotMatchingPathWithNotOperator() { // when mockServerClient .when( request() .withPath(not(calculatePath("some_path"))) ) .respond( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body_response") ); // then // - in http assertEquals( response() .withHeader(HttpHeaders.CONTENT_TYPE, TEXT_PLAIN) .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body_response"), makeRequest( request() .withPath(calculatePath("some_other_path")), headersToIgnore) ); // - in https assertEquals( response() .withHeader(HttpHeaders.CONTENT_TYPE, TEXT_PLAIN) .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body_response"), makeRequest( request() .withPath(calculatePath("some_other_path")), headersToIgnore) ); } @Test public void shouldReturnResponseByNotMatchingMethodWithNotOperator() { // when mockServerClient .when( request() .withMethod(not("GET")) ) .respond( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body_response") ); // then // - in http assertEquals( response() .withHeader(HttpHeaders.CONTENT_TYPE, TEXT_PLAIN) .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body_response"), makeRequest( request() .withMethod("POST"), headersToIgnore) ); // - in https assertEquals( response() .withHeader(HttpHeaders.CONTENT_TYPE, TEXT_PLAIN) .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body_response"), makeRequest( request() .withMethod("POST"), headersToIgnore) ); } @Test public void shouldReturnResponseByMatchingPathAndMethodAndBody() { // when mockServerClient .when( request() .withMethod("POST") .withPath(calculatePath("some_pathRequest")) .withBody("some_bodyRequest") ) .respond( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body_response") .withHeaders(header("headerNameResponse", "headerValueResponse")) ); // then // - in http assertEquals( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body_response") .withHeaders( header("headerNameResponse", "headerValueResponse"), header(HttpHeaders.CONTENT_TYPE, TEXT_PLAIN) ), makeRequest( request() .withMethod("POST") .withPath(calculatePath("some_pathRequest")) .withQueryStringParameters( param("queryStringParameterOneName", "queryStringParameterOneValue"), param("queryStringParameterTwoName", "queryStringParameterTwoValue") ) .withBody("some_bodyRequest") .withHeaders(header("headerNameRequest", "headerValueRequest")) .withCookies(cookie("cookieNameRequest", "cookieValueRequest")), headersToIgnore) ); // - in https assertEquals( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body_response") .withHeaders( header("headerNameResponse", "headerValueResponse"), header(HttpHeaders.CONTENT_TYPE, TEXT_PLAIN) ), makeRequest( request() .withMethod("POST") .withSecure(true) .withPath(calculatePath("some_pathRequest")) .withQueryStringParameters( param("queryStringParameterOneName", "queryStringParameterOneValue"), param("queryStringParameterTwoName", "queryStringParameterTwoValue") ) .withBody("some_bodyRequest") .withHeaders(header("headerNameRequest", "headerValueRequest")) .withCookies(cookie("cookieNameRequest", "cookieValueRequest")), headersToIgnore) ); } @Test public void shouldReturnResponseByMatchingPathAndMethodAndQueryStringParameters() { // when mockServerClient .when( request() .withMethod("GET") .withPath(calculatePath("some_pathRequest")) .withQueryStringParameters( param("queryStringParameterOneName", "queryStringParameterOneValue"), param("queryStringParameterTwoName", "queryStringParameterTwoValue") ) ) .respond( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body_response") .withCookies(cookie("cookieNameResponse", "cookieValueResponse")) ); // then // - in http assertEquals( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body_response") .withCookies(cookie("cookieNameResponse", "cookieValueResponse")) .withHeaders( header("Set-Cookie", "cookieNameResponse=cookieValueResponse"), header(HttpHeaders.CONTENT_TYPE, TEXT_PLAIN) ), makeRequest( request() .withMethod("GET") .withPath(calculatePath("some_pathRequest")) .withQueryStringParameters( param("queryStringParameterOneName", "queryStringParameterOneValue"), param("queryStringParameterTwoName", "queryStringParameterTwoValue") ) .withHeaders(header("headerNameRequest", "headerValueRequest")) .withCookies(cookie("cookieNameRequest", "cookieValueRequest")), headersToIgnore) ); // - in https assertEquals( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body_response") .withCookies(cookie("cookieNameResponse", "cookieValueResponse")) .withHeaders( header("Set-Cookie", "cookieNameResponse=cookieValueResponse"), header(HttpHeaders.CONTENT_TYPE, TEXT_PLAIN) ), makeRequest( request() .withMethod("GET") .withSecure(true) .withPath(calculatePath("some_pathRequest")) .withQueryStringParameters( param("queryStringParameterOneName", "queryStringParameterOneValue"), param("queryStringParameterTwoName", "queryStringParameterTwoValue") ) .withHeaders(header("headerNameRequest", "headerValueRequest")) .withCookies(cookie("cookieNameRequest", "cookieValueRequest")), headersToIgnore) ); } @Test public void shouldReturnResponseByMatchingPathAndMethodAndHeaders() { // when mockServerClient .when( request() .withMethod("GET") .withPath(calculatePath("some_pathRequest")) .withHeaders( header("requestHeaderNameOne", "requestHeaderValueOne_One", "requestHeaderValueOne_Two"), header("requestHeaderNameTwo", "requestHeaderValueTwo") ) ) .respond( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body_response") .withCookies(cookie("cookieNameResponse", "cookieValueResponse")) ); // then // - in http assertEquals( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body_response") .withCookies(cookie("cookieNameResponse", "cookieValueResponse")) .withHeaders( header("Set-Cookie", "cookieNameResponse=cookieValueResponse"), header(HttpHeaders.CONTENT_TYPE, TEXT_PLAIN) ), makeRequest( request() .withMethod("GET") .withPath(calculatePath("some_pathRequest")) .withHeaders( header("requestHeaderNameOne", "requestHeaderValueOne_One", "requestHeaderValueOne_Two"), header("requestHeaderNameTwo", "requestHeaderValueTwo") ) .withCookies(cookie("cookieNameRequest", "cookieValueRequest")), headersToIgnore) ); // - in https assertEquals( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body_response") .withCookies(cookie("cookieNameResponse", "cookieValueResponse")) .withHeaders( header("Set-Cookie", "cookieNameResponse=cookieValueResponse"), header(HttpHeaders.CONTENT_TYPE, TEXT_PLAIN) ), makeRequest( request() .withMethod("GET") .withSecure(true) .withPath(calculatePath("some_pathRequest")) .withHeaders( header("requestHeaderNameOne", "requestHeaderValueOne_One", "requestHeaderValueOne_Two"), header("requestHeaderNameTwo", "requestHeaderValueTwo") ) .withCookies(cookie("cookieNameRequest", "cookieValueRequest")), headersToIgnore) ); } @Test public void shouldReturnResponseByMatchingPathAndMethodAndCookies() { // when mockServerClient .when( request() .withMethod("GET") .withPath(calculatePath("some_pathRequest")) .withCookies( cookie("requestCookieNameOne", "requestCookieValueOne"), cookie("requestCookieNameTwo", "requestCookieValueTwo") ) ) .respond( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body_response") .withCookies( cookie("responseCookieNameOne", "responseCookieValueOne"), cookie("responseCookieNameTwo", "responseCookieValueTwo") ) ); // then // - in http - cookie objects assertEquals( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body_response") .withCookies( cookie("responseCookieNameOne", "responseCookieValueOne"), cookie("responseCookieNameTwo", "responseCookieValueTwo") ) .withHeaders( header("Set-Cookie", "responseCookieNameOne=responseCookieValueOne", "responseCookieNameTwo=responseCookieValueTwo"), header(HttpHeaders.CONTENT_TYPE, TEXT_PLAIN) ), makeRequest( request() .withMethod("GET") .withPath(calculatePath("some_pathRequest")) .withHeaders( header("headerNameRequest", "headerValueRequest"), header(HttpHeaders.CONTENT_TYPE, TEXT_PLAIN) ) .withCookies( cookie("requestCookieNameOne", "requestCookieValueOne"), cookie("requestCookieNameTwo", "requestCookieValueTwo") ), headersToIgnore) ); // - in http - cookie header assertEquals( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body_response") .withCookies( cookie("responseCookieNameOne", "responseCookieValueOne"), cookie("responseCookieNameTwo", "responseCookieValueTwo") ) .withHeaders( header("Set-Cookie", "responseCookieNameOne=responseCookieValueOne", "responseCookieNameTwo=responseCookieValueTwo"), header(HttpHeaders.CONTENT_TYPE, TEXT_PLAIN) ), makeRequest( request() .withMethod("GET") .withPath(calculatePath("some_pathRequest")) .withHeaders( header("headerNameRequest", "headerValueRequest"), header("Cookie", "requestCookieNameOne=requestCookieValueOne; requestCookieNameTwo=requestCookieValueTwo") ), headersToIgnore) ); // - in https - cookie objects assertEquals( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body_response") .withCookies( cookie("responseCookieNameOne", "responseCookieValueOne"), cookie("responseCookieNameTwo", "responseCookieValueTwo") ) .withHeaders( header("Set-Cookie", "responseCookieNameOne=responseCookieValueOne", "responseCookieNameTwo=responseCookieValueTwo"), header(HttpHeaders.CONTENT_TYPE, TEXT_PLAIN) ), makeRequest( request() .withMethod("GET") .withSecure(true) .withPath(calculatePath("some_pathRequest")) .withHeaders( header("headerNameRequest", "headerValueRequest") ) .withCookies( cookie("requestCookieNameOne", "requestCookieValueOne"), cookie("requestCookieNameTwo", "requestCookieValueTwo") ), headersToIgnore) ); // - in https - cookie header assertEquals( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body_response") .withCookies( cookie("responseCookieNameOne", "responseCookieValueOne"), cookie("responseCookieNameTwo", "responseCookieValueTwo") ) .withHeaders( header("Set-Cookie", "responseCookieNameOne=responseCookieValueOne", "responseCookieNameTwo=responseCookieValueTwo"), header(HttpHeaders.CONTENT_TYPE, TEXT_PLAIN) ), makeRequest( request() .withMethod("GET") .withSecure(true) .withPath(calculatePath("some_pathRequest")) .withHeaders( header("headerNameRequest", "headerValueRequest"), header("Cookie", "requestCookieNameOne=requestCookieValueOne; requestCookieNameTwo=requestCookieValueTwo") ), headersToIgnore) ); } @Test public void shouldReturnResponseByMatchingPathAndMethodAndQueryStringParametersAndBodyParameters() { // when mockServerClient .when( request() .withMethod("POST") .withPath(calculatePath("some_pathRequest")) .withQueryStringParameters( param("queryStringParameterOneName", "queryStringParameterOneValueOne", "queryStringParameterOneValueTwo"), param("queryStringParameterTwoName", "queryStringParameterTwoValue") ) .withBody(params(param("bodyParameterName", "bodyParameterValue"))) ) .respond( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body") ); // then // - in http - url query string assertEquals( response() .withHeader(HttpHeaders.CONTENT_TYPE, TEXT_PLAIN) .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body"), makeRequest( request() .withMethod("POST") .withPath(calculatePath("some_pathRequest")) .withQueryStringParameters( param("queryStringParameterOneName", "queryStringParameterOneValueOne", "queryStringParameterOneValueTwo"), param("queryStringParameterTwoName", "queryStringParameterTwoValue") ) .withBody(params(param("bodyParameterName", "bodyParameterValue"))), headersToIgnore) ); // - in https - query string parameter objects assertEquals( response() .withHeader(HttpHeaders.CONTENT_TYPE, TEXT_PLAIN) .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body"), makeRequest( request() .withSecure(true) .withMethod("POST") .withPath(calculatePath("some_pathRequest")) .withQueryStringParameters( param("queryStringParameterOneName", "queryStringParameterOneValueOne", "queryStringParameterOneValueTwo"), param("queryStringParameterTwoName", "queryStringParameterTwoValue") ) .withBody(params(param("bodyParameterName", "bodyParameterValue"))), headersToIgnore) ); } @Test public void shouldReturnResponseByMatchingPathAndMethodAndQueryStringParametersAndBody() { // when mockServerClient .when( request() .withMethod("POST") .withPath(calculatePath("some_pathRequest")) .withQueryStringParameters( param("queryStringParameterOneName", "queryStringParameterOneValueOne", "queryStringParameterOneValueTwo"), param("queryStringParameterTwoName", "queryStringParameterTwoValue") ) .withBody("some_bodyRequest") ) .respond( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body_response") .withHeaders(header("headerNameResponse", "headerValueResponse")) .withCookies(cookie("cookieNameResponse", "cookieValueResponse")) ); // then // - in http - url query string assertEquals( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body_response") .withCookies(cookie("cookieNameResponse", "cookieValueResponse")) .withHeaders( header("headerNameResponse", "headerValueResponse"), header("Set-Cookie", "cookieNameResponse=cookieValueResponse"), header(HttpHeaders.CONTENT_TYPE, TEXT_PLAIN) ), makeRequest( request() .withMethod("POST") .withPath(calculatePath("some_pathRequest")) .withQueryStringParameters( param("queryStringParameterOneName", "queryStringParameterOneValueOne", "queryStringParameterOneValueTwo"), param("queryStringParameterTwoName", "queryStringParameterTwoValue") ) .withBody("some_bodyRequest") .withHeaders(header("headerNameRequest", "headerValueRequest")) .withCookies(cookie("cookieNameRequest", "cookieValueRequest")), headersToIgnore) ); // - in http - query string parameter objects assertEquals( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body_response") .withCookies(cookie("cookieNameResponse", "cookieValueResponse")) .withHeaders( header("headerNameResponse", "headerValueResponse"), header("Set-Cookie", "cookieNameResponse=cookieValueResponse"), header(HttpHeaders.CONTENT_TYPE, TEXT_PLAIN) ), makeRequest( request() .withMethod("POST") .withPath(calculatePath("some_pathRequest")) .withQueryStringParameters( param("queryStringParameterOneName", "queryStringParameterOneValueOne", "queryStringParameterOneValueTwo"), param("queryStringParameterTwoName", "queryStringParameterTwoValue") ) .withBody("some_bodyRequest") .withHeaders(header("headerNameRequest", "headerValueRequest")) .withCookies(cookie("cookieNameRequest", "cookieValueRequest")), headersToIgnore) ); // - in https - url string and query string parameter objects assertEquals( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body_response") .withCookies(cookie("cookieNameResponse", "cookieValueResponse")) .withHeaders( header("headerNameResponse", "headerValueResponse"), header("Set-Cookie", "cookieNameResponse=cookieValueResponse"), header(HttpHeaders.CONTENT_TYPE, TEXT_PLAIN) ), makeRequest( request() .withMethod("POST") .withPath(calculatePath("some_pathRequest")) .withQueryStringParameters( param("queryStringParameterOneName", "queryStringParameterOneValueOne", "queryStringParameterOneValueTwo"), param("queryStringParameterTwoName", "queryStringParameterTwoValue") ) .withBody("some_bodyRequest") .withHeaders(header("headerNameRequest", "headerValueRequest")) .withCookies(cookie("cookieNameRequest", "cookieValueRequest")), headersToIgnore) ); } @Test public void shouldReturnResponseByMatchingPathAndMethodAndBodyParameters() { // when mockServerClient .when( request() .withMethod("POST") .withPath(calculatePath("some_pathRequest")) .withBody(params( param("bodyParameterOneName", "Parameter One Value One", "Parameter One Value Two"), param("bodyParameterTwoName", "Parameter Two") )) ) .respond( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body_response") .withHeaders(header("headerNameResponse", "headerValueResponse")) .withCookies(cookie("cookieNameResponse", "cookieValueResponse")) ); // then // - in http - body string assertEquals( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body_response") .withCookies(cookie("cookieNameResponse", "cookieValueResponse")) .withHeaders( header("headerNameResponse", "headerValueResponse"), header("Set-Cookie", "cookieNameResponse=cookieValueResponse"), header(HttpHeaders.CONTENT_TYPE, TEXT_PLAIN) ), makeRequest( request() .withMethod("POST") .withPath(calculatePath("some_pathRequest")) .withBody(new StringBody("bodyParameterOneName=Parameter+One+Value+One" + "&bodyParameterOneName=Parameter+One+Value+Two" + "&bodyParameterTwoName=Parameter+Two")) .withHeaders(header("headerNameRequest", "headerValueRequest")) .withCookies(cookie("cookieNameRequest", "cookieValueRequest")), headersToIgnore) ); // - in http - body parameter objects assertEquals( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body_response") .withCookies(cookie("cookieNameResponse", "cookieValueResponse")) .withHeaders( header("headerNameResponse", "headerValueResponse"), header("Set-Cookie", "cookieNameResponse=cookieValueResponse"), header(HttpHeaders.CONTENT_TYPE, TEXT_PLAIN) ), makeRequest( request() .withMethod("POST") .withPath(calculatePath("some_pathRequest")) .withBody(params( param("bodyParameterOneName", "Parameter One Value One", "Parameter One Value Two"), param("bodyParameterTwoName", "Parameter Two") )) .withHeaders(header("headerNameRequest", "headerValueRequest")) .withCookies(cookie("cookieNameRequest", "cookieValueRequest")), headersToIgnore) ); // - in https - url string and query string parameter objects assertEquals( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body_response") .withCookies(cookie("cookieNameResponse", "cookieValueResponse")) .withHeaders( header("headerNameResponse", "headerValueResponse"), header("Set-Cookie", "cookieNameResponse=cookieValueResponse"), header(HttpHeaders.CONTENT_TYPE, TEXT_PLAIN) ), makeRequest( request() .withMethod("POST") .withPath(calculatePath("some_pathRequest")) .withBody(params( param("bodyParameterOneName", "Parameter One Value One", "Parameter One Value Two"), param("bodyParameterTwoName", "Parameter Two") )) .withHeaders(header("headerNameRequest", "headerValueRequest")) .withCookies(cookie("cookieNameRequest", "cookieValueRequest")), headersToIgnore) ); } @Test public void shouldReturnResponseByMatchingPathAndMethodAndParametersAndHeadersAndCookies() { // when mockServerClient .when( request() .withMethod("PUT") .withPath(calculatePath("some_pathRequest")) .withBody(new StringBody("bodyParameterOneName=Parameter+One+Value+One" + "&bodyParameterOneName=Parameter+One+Value+Two" + "&bodyParameterTwoName=Parameter+Two")) .withHeaders(header("headerNameRequest", "headerValueRequest")) .withCookies(cookie("cookieNameRequest", "cookieValueRequest")) ) .respond( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body_response") .withHeaders(header("headerNameResponse", "headerValueResponse")) .withCookies(cookie("cookieNameResponse", "cookieValueResponse")) ); // then // - in http - body string assertEquals( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body_response") .withCookies(cookie("cookieNameResponse", "cookieValueResponse")) .withHeaders( header("headerNameResponse", "headerValueResponse"), header("Set-Cookie", "cookieNameResponse=cookieValueResponse"), header(HttpHeaders.CONTENT_TYPE, TEXT_PLAIN) ), makeRequest( request() .withMethod("PUT") .withPath(calculatePath("some_pathRequest")) .withBody(new StringBody("bodyParameterOneName=Parameter+One+Value+One" + "&bodyParameterOneName=Parameter+One+Value+Two" + "&bodyParameterTwoName=Parameter+Two")) .withHeaders( header("headerNameRequest", "headerValueRequest"), header("Cookie", "cookieNameRequest=cookieValueRequest") ), headersToIgnore) ); // - in http - body parameter objects assertEquals( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body_response") .withCookies(cookie("cookieNameResponse", "cookieValueResponse")) .withHeaders( header("headerNameResponse", "headerValueResponse"), header("Set-Cookie", "cookieNameResponse=cookieValueResponse"), header(HttpHeaders.CONTENT_TYPE, TEXT_PLAIN) ), makeRequest( request() .withMethod("PUT") .withPath(calculatePath("some_pathRequest")) .withBody(params( param("bodyParameterOneName", "Parameter One Value One", "Parameter One Value Two"), param("bodyParameterTwoName", "Parameter Two") )) .withHeaders(header("headerNameRequest", "headerValueRequest")) .withCookies(cookie("cookieNameRequest", "cookieValueRequest")), headersToIgnore) ); } @Test public void shouldReturnResponseByNotMatchingBodyParameterWithNotOperatorForNameAndValue() { // when mockServerClient .when( request() .withMethod("POST") .withPath(calculatePath("some_pathRequest")) .withBody(params( param(not("bodyParameterOneName"), not("Parameter One Value One"), not("Parameter One Value Two")), param("bodyParameterTwoName", "Parameter Two") )) ) .respond( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body_response") ); // then // wrong query string parameter name assertEquals( response() .withHeader(HttpHeaders.CONTENT_TYPE, TEXT_PLAIN) .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body_response"), makeRequest( request() .withMethod("POST") .withPath(calculatePath("some_pathRequest")) .withBody(params( param("OTHERBodyParameterOneName", "Parameter One Value One", "Parameter One Value Two"), param("bodyParameterTwoName", "Parameter Two") )) .withHeaders(header("headerNameRequest", "headerValueRequest")) .withCookies(cookie("cookieNameRequest", "cookieValueRequest")), headersToIgnore) ); // wrong query string parameter name assertEquals( response() .withHeader(HttpHeaders.CONTENT_TYPE, TEXT_PLAIN) .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body_response"), makeRequest( request() .withMethod("POST") .withPath(calculatePath("some_pathRequest")) .withBody(new StringBody("OTHERBodyParameterOneName=Parameter+One+Value+One" + "&OTHERBodyParameterOneName=Parameter+One+Value+Two" + "&bodyParameterTwoName=Parameter+Two")) .withHeaders(header("headerNameRequest", "headerValueRequest")) .withCookies(cookie("cookieNameRequest", "cookieValueRequest")), headersToIgnore) ); // wrong query string parameter value assertEquals( response() .withHeader(HttpHeaders.CONTENT_TYPE, TEXT_PLAIN) .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body_response"), makeRequest( request() .withMethod("POST") .withPath(calculatePath("some_pathRequest")) .withBody(params( param("bodyParameterOneName", "OTHER Parameter One Value One", "OTHER Parameter One Value Two"), param("bodyParameterTwoName", "Parameter Two") )) .withHeaders(header("headerNameRequest", "headerValueRequest")) .withCookies(cookie("cookieNameRequest", "cookieValueRequest")), headersToIgnore) ); // wrong query string parameter value assertEquals( response() .withHeader(HttpHeaders.CONTENT_TYPE, TEXT_PLAIN) .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body_response"), makeRequest( request() .withMethod("POST") .withPath(calculatePath("some_pathRequest")) .withBody(new StringBody("bodyParameterOneName=OTHER Parameter+One+Value+One" + "&bodyParameterOneName=OTHER Parameter+One+Value+Two" + "&bodyParameterTwoName=Parameter+Two")) .withHeaders(header("headerNameRequest", "headerValueRequest")) .withCookies(cookie("cookieNameRequest", "cookieValueRequest")), headersToIgnore) ); } @Test public void shouldReturnResponseByNotMatchingBodyParameterWithNotOperatorForName() { // when mockServerClient .when( request() .withMethod("POST") .withPath(calculatePath("some_pathRequest")) .withBody(params( param(not("bodyParameterOneName"), string("Parameter One Value One"), string("Parameter One Value Two")), param("bodyParameterTwoName", "Parameter Two") )) ) .respond( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body_response") ); // then // wrong query string parameter name assertEquals( response() .withHeader(HttpHeaders.CONTENT_TYPE, TEXT_PLAIN) .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body_response"), makeRequest( request() .withMethod("POST") .withPath(calculatePath("some_pathRequest")) .withBody(params( param("OTHERBodyParameterOneName", "Parameter One Value One", "Parameter One Value Two"), param("bodyParameterTwoName", "Parameter Two") )) .withHeaders(header("headerNameRequest", "headerValueRequest")) .withCookies(cookie("cookieNameRequest", "cookieValueRequest")), headersToIgnore) ); // wrong query string parameter name assertEquals( response() .withHeader(HttpHeaders.CONTENT_TYPE, TEXT_PLAIN) .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body_response"), makeRequest( request() .withMethod("POST") .withPath(calculatePath("some_pathRequest")) .withBody(new StringBody("OTHERBodyParameterOneName=Parameter+One+Value+One" + "&OTHERBodyParameterOneName=Parameter+One+Value+Two" + "&bodyParameterTwoName=Parameter+Two")) .withHeaders(header("headerNameRequest", "headerValueRequest")) .withCookies(cookie("cookieNameRequest", "cookieValueRequest")), headersToIgnore) ); } @Test public void shouldReturnResponseByNotMatchingBodyParameterWithNotOperatorForValue() { // when mockServerClient .when( request() .withMethod("POST") .withPath(calculatePath("some_pathRequest")) .withBody(params( param(string("bodyParameterOneName"), not("Parameter One Value One"), not("Parameter One Value Two")), param("bodyParameterTwoName", "Parameter Two") )) ) .respond( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body_response") ); // then // wrong query string parameter value assertEquals( response() .withHeader(HttpHeaders.CONTENT_TYPE, TEXT_PLAIN) .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body_response"), makeRequest( request() .withMethod("POST") .withPath(calculatePath("some_pathRequest")) .withBody(params( param("bodyParameterOneName", "OTHER Parameter One Value One", "OTHER Parameter One Value Two"), param("bodyParameterTwoName", "Parameter Two") )) .withHeaders(header("headerNameRequest", "headerValueRequest")) .withCookies(cookie("cookieNameRequest", "cookieValueRequest")), headersToIgnore) ); // wrong query string parameter value assertEquals( response() .withHeader(HttpHeaders.CONTENT_TYPE, TEXT_PLAIN) .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body_response"), makeRequest( request() .withMethod("POST") .withPath(calculatePath("some_pathRequest")) .withBody(new StringBody("bodyParameterOneName=OTHER Parameter+One+Value+One" + "&bodyParameterOneName=OTHER Parameter+One+Value+Two" + "&bodyParameterTwoName=Parameter+Two")) .withHeaders(header("headerNameRequest", "headerValueRequest")) .withCookies(cookie("cookieNameRequest", "cookieValueRequest")), headersToIgnore) ); } @Test public void shouldReturnResponseByNotMatchingQueryStringParameterWithNotOperatorForNameAndValue() { // when mockServerClient .when( request() .withMethod("POST") .withPath(calculatePath("some_pathRequest")) .withQueryStringParameters( param(not("queryStringParameterOneName"), not("Parameter One Value One"), not("Parameter One Value Two")), param("queryStringParameterTwoName", "Parameter Two") ) ) .respond( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body_response") ); // then // wrong query string parameter name assertEquals( response() .withHeader(HttpHeaders.CONTENT_TYPE, TEXT_PLAIN) .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body_response"), makeRequest( request() .withMethod("POST") .withPath(calculatePath("some_pathRequest")) .withQueryStringParameters( param("OTHERQueryStringParameterOneName", "Parameter One Value One", "Parameter One Value Two"), param("queryStringParameterTwoName", "Parameter Two") ), headersToIgnore) ); // wrong query string parameter value assertEquals( response() .withHeader(HttpHeaders.CONTENT_TYPE, TEXT_PLAIN) .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body_response"), makeRequest( request() .withMethod("POST") .withPath(calculatePath("some_pathRequest")) .withQueryStringParameters( param("queryStringParameterOneName", "OTHER Parameter One Value One", "OTHER Parameter One Value Two"), param("queryStringParameterTwoName", "Parameter Two") ), headersToIgnore) ); } @Test public void shouldReturnResponseByNotMatchingQueryStringParameterWithNotOperatorForName() { // when mockServerClient .when( request() .withMethod("POST") .withPath(calculatePath("some_pathRequest")) .withQueryStringParameters( param(not("queryStringParameterOneName"), string("Parameter One Value One"), string("Parameter One Value Two")), param("queryStringParameterTwoName", "Parameter Two") ) ) .respond( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body_response") ); // then // wrong query string parameter name assertEquals( response() .withHeader(HttpHeaders.CONTENT_TYPE, TEXT_PLAIN) .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body_response"), makeRequest( request() .withMethod("POST") .withPath(calculatePath("some_pathRequest")) .withQueryStringParameters( param("OTHERQueryStringParameterOneName", "Parameter One Value One", "Parameter One Value Two"), param("queryStringParameterTwoName", "Parameter Two") ), headersToIgnore) ); } @Test public void shouldReturnResponseByNotMatchingQueryStringParameterWithNotOperatorForValue() { // when mockServerClient .when( request() .withMethod("POST") .withPath(calculatePath("some_pathRequest")) .withQueryStringParameters( param(string("queryStringParameterOneName"), not("Parameter One Value One"), not("Parameter One Value Two")), param("queryStringParameterTwoName", "Parameter Two") ) ) .respond( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body_response") ); // then // wrong query string parameter value assertEquals( response() .withHeader(HttpHeaders.CONTENT_TYPE, TEXT_PLAIN) .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body_response"), makeRequest( request() .withMethod("POST") .withPath(calculatePath("some_pathRequest")) .withQueryStringParameters( param("queryStringParameterOneName", "OTHER Parameter One Value One", "OTHER Parameter One Value Two"), param("queryStringParameterTwoName", "Parameter Two") ), headersToIgnore) ); } @Test public void shouldReturnResponseByNotMatchingCookieWithNotOperatorForNameAndValue() { // when mockServerClient .when( request() .withMethod("GET") .withPath(calculatePath("some_pathRequest")) .withCookies( cookie(not("requestCookieNameOne"), not("requestCookieValueOne")), cookie("requestCookieNameTwo", "requestCookieValueTwo") ) ) .respond( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body_response") ); // then // wrong query string cookie name assertEquals( response() .withHeader(HttpHeaders.CONTENT_TYPE, TEXT_PLAIN) .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body_response"), makeRequest( request() .withMethod("GET") .withPath(calculatePath("some_pathRequest")) .withCookies( cookie("OTHERrequestCookieNameOne", "requestCookieValueOne"), cookie("requestCookieNameTwo", "requestCookieValueTwo") ), headersToIgnore) ); // wrong query string cookie value assertEquals( response() .withHeader(HttpHeaders.CONTENT_TYPE, TEXT_PLAIN) .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body_response"), makeRequest( request() .withMethod("GET") .withPath(calculatePath("some_pathRequest")) .withCookies( cookie("requestCookieNameOne", "OTHERrequestCookieValueOne"), cookie("requestCookieNameTwo", "requestCookieValueTwo") ), headersToIgnore) ); } @Test public void shouldReturnResponseByNotMatchingCookieWithNotOperatorForName() { // when mockServerClient .when( request() .withMethod("GET") .withPath(calculatePath("some_pathRequest")) .withCookies( cookie(not("requestCookieNameOne"), string("requestCookieValueOne")), cookie("requestCookieNameTwo", "requestCookieValueTwo") ) ) .respond( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body_response") ); // then // wrong query string cookie name assertEquals( response() .withHeader(HttpHeaders.CONTENT_TYPE, TEXT_PLAIN) .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body_response"), makeRequest( request() .withMethod("GET") .withPath(calculatePath("some_pathRequest")) .withCookies( cookie("OTHERrequestCookieNameOne", "requestCookieValueOne"), cookie("requestCookieNameTwo", "requestCookieValueTwo") ), headersToIgnore) ); } @Test public void shouldReturnResponseByNotMatchingCookieWithNotOperatorForValue() { // when mockServerClient .when( request() .withMethod("GET") .withPath(calculatePath("some_pathRequest")) .withCookies( cookie(string("requestCookieNameOne"), not("requestCookieValueOne")), cookie("requestCookieNameTwo", "requestCookieValueTwo") ) ) .respond( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body_response") ); // then // wrong query string cookie value assertEquals( response() .withHeader(HttpHeaders.CONTENT_TYPE, TEXT_PLAIN) .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body_response"), makeRequest( request() .withMethod("GET") .withPath(calculatePath("some_pathRequest")) .withCookies( cookie("requestCookieNameOne", "OTHERrequestCookieValueOne"), cookie("requestCookieNameTwo", "requestCookieValueTwo") ), headersToIgnore) ); } @Test public void shouldReturnResponseByNotMatchingHeaderWithNotOperatorForNameAndValue() { // when mockServerClient .when( request() .withMethod("GET") .withPath(calculatePath("some_pathRequest")) .withHeaders( header(not("requestHeaderNameOne"), not("requestHeaderValueOne")), header("requestHeaderNameTwo", "requestHeaderValueTwo") ) ) .respond( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body_response") ); // then // wrong query string header name assertEquals( response() .withHeader(HttpHeaders.CONTENT_TYPE, TEXT_PLAIN) .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body_response"), makeRequest( request() .withMethod("GET") .withPath(calculatePath("some_pathRequest")) .withHeaders( header("OTHERrequestHeaderNameOne", "requestHeaderValueOne"), header("requestHeaderNameTwo", "requestHeaderValueTwo") ), headersToIgnore) ); // wrong query string header value assertEquals( response() .withHeader(HttpHeaders.CONTENT_TYPE, TEXT_PLAIN) .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body_response"), makeRequest( request() .withMethod("GET") .withPath(calculatePath("some_pathRequest")) .withHeaders( header("requestHeaderNameOne", "OTHERrequestHeaderValueOne"), header("requestHeaderNameTwo", "requestHeaderValueTwo") ), headersToIgnore) ); } @Test public void shouldReturnResponseByNotMatchingHeaderWithNotOperatorForName() { // when mockServerClient .when( request() .withMethod("GET") .withPath(calculatePath("some_pathRequest")) .withHeaders( header(not("requestHeaderNameOne"), string("requestHeaderValueOne")), header("requestHeaderNameTwo", "requestHeaderValueTwo") ) ) .respond( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body_response") ); // then // wrong query string header name assertEquals( response() .withHeader(HttpHeaders.CONTENT_TYPE, TEXT_PLAIN) .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body_response"), makeRequest( request() .withMethod("GET") .withPath(calculatePath("some_pathRequest")) .withHeaders( header("OTHERrequestHeaderNameOne", "requestHeaderValueOne"), header("requestHeaderNameTwo", "requestHeaderValueTwo") ), headersToIgnore) ); } @Test public void shouldReturnResponseByNotMatchingHeaderWithNotOperatorForValue() { // when mockServerClient .when( request() .withMethod("GET") .withPath(calculatePath("some_pathRequest")) .withHeaders( header(string("requestHeaderNameOne"), not("requestHeaderValueOne")), header("requestHeaderNameTwo", "requestHeaderValueTwo") ) ) .respond( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body_response") ); // then // wrong query string header value assertEquals( response() .withHeader(HttpHeaders.CONTENT_TYPE, TEXT_PLAIN) .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body_response"), makeRequest( request() .withMethod("GET") .withPath(calculatePath("some_pathRequest")) .withHeaders( header("requestHeaderNameOne", "OTHERrequestHeaderValueOne"), header("requestHeaderNameTwo", "requestHeaderValueTwo") ), headersToIgnore) ); } @Test public void shouldNotReturnResponseForWhenTimeToLiveExpired() { // when mockServerClient .when( request().withPath(calculatePath("some_path")), exactly(2), TimeToLive.exactly(TimeUnit.SECONDS, 5L) ) .respond( response().withBody("some_body").withDelay(TimeUnit.SECONDS, 5L) ); // then assertEquals( response() .withHeader(HttpHeaders.CONTENT_TYPE, TEXT_PLAIN) .withStatusCode(HttpStatusCode.OK_200.code()) .withBody("some_body"), makeRequest( request() .withPath(calculatePath("some_path")), headersToIgnore) ); // - in http assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()), makeRequest( request() .withPath(calculatePath("some_path")), headersToIgnore) ); // - in https assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()), makeRequest( request() .withSecure(true) .withPath(calculatePath("some_path")), headersToIgnore) ); } @Test public void shouldNotReturnResponseForNonMatchingBody() { // when mockServerClient .when( request() .withMethod("GET") .withPath(calculatePath("some_path")) .withQueryStringParameters( param("queryStringParameterOneName", "queryStringParameterOneValue"), param("queryStringParameterTwoName", "queryStringParameterTwoValue") ) .withBody(exact("some_body")) .withHeaders(header("headerName", "headerValue")) .withCookies(cookie("cookieName", "cookieValue")) ) .respond( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body") .withHeaders(header("headerName", "headerValue")) .withCookies(cookie("cookieName", "cookieValue")) ); // then // - in http assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()), makeRequest( request() .withMethod("GET") .withPath(calculatePath("some_path")) .withQueryStringParameters( param("queryStringParameterOneName", "queryStringParameterOneValue"), param("queryStringParameterTwoName", "queryStringParameterTwoValue") ) .withBody(exact("some_other_body")) .withHeaders(header("headerName", "headerValue")) .withCookies(cookie("cookieName", "cookieValue")), headersToIgnore) ); // - in https assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()), makeRequest( request() .withMethod("GET") .withSecure(true) .withPath(calculatePath("some_path")) .withQueryStringParameters( param("queryStringParameterOneName", "queryStringParameterOneValue"), param("queryStringParameterTwoName", "queryStringParameterTwoValue") ) .withBody(exact("some_other_body")) .withHeaders(header("headerName", "headerValue")) .withCookies(cookie("cookieName", "cookieValue")), headersToIgnore) ); } @Test public void shouldNotReturnResponseForMatchingBodyWithNotOperator() { // when mockServerClient .when( request() .withBody(Not.not(json("{" + System.getProperty("line.separator") + " \"id\": 1," + System.getProperty("line.separator") + " \"name\": \"A green door\"," + System.getProperty("line.separator") + " \"price\": 12.50," + System.getProperty("line.separator") + " \"tags\": [\"home\", \"green\"]" + System.getProperty("line.separator") + "}"))), exactly(2) ) .respond( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body") ); // then // - in http assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()), makeRequest( request() .withPath(calculatePath("some_path")) .withMethod("POST") .withBody("{" + System.getProperty("line.separator") + " \"id\": 1," + System.getProperty("line.separator") + " \"extra_ignored_field\": \"some value\"," + System.getProperty("line.separator") + " \"name\": \"A green door\"," + System.getProperty("line.separator") + " \"price\": 12.50," + System.getProperty("line.separator") + " \"tags\": [\"home\", \"green\"]" + System.getProperty("line.separator") + "}"), headersToIgnore) ); // - in https assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()), makeRequest( request() .withSecure(true) .withPath(calculatePath("some_path")) .withMethod("POST") .withBody("{" + System.getProperty("line.separator") + " \"id\": 1," + System.getProperty("line.separator") + " \"extra_ignored_array\": [\"one\", \"two\"]," + System.getProperty("line.separator") + " \"name\": \"A green door\"," + System.getProperty("line.separator") + " \"price\": 12.50," + System.getProperty("line.separator") + " \"tags\": [\"home\", \"green\"]" + System.getProperty("line.separator") + "}"), headersToIgnore) ); } @Test public void shouldNotReturnResponseForNonMatchingXPathBody() { // when mockServerClient.when(request().withBody(new XPathBody("/bookstore/book[price>35]/price")), exactly(2)).respond(response().withBody("some_body")); // then // - in http assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()), makeRequest( request() .withSecure(true) .withPath(calculatePath("some_path")) .withMethod("POST") .withBody(new StringBody("" + "<?xml version=\"1.0\" encoding=\"ISO-8859-1\"?>" + System.getProperty("line.separator") + "<bookstore>" + System.getProperty("line.separator") + " <book category=\"COOKING\">" + System.getProperty("line.separator") + " <title lang=\"en\">Everyday Italian</title>" + System.getProperty("line.separator") + " <author>Giada De Laurentiis</author>" + System.getProperty("line.separator") + " <year>2005</year>" + System.getProperty("line.separator") + " <price>30.00</price>" + System.getProperty("line.separator") + " </book>" + System.getProperty("line.separator") + " <book category=\"CHILDREN\">" + System.getProperty("line.separator") + " <title lang=\"en\">Harry Potter</title>" + System.getProperty("line.separator") + " <author>J K. Rowling</author>" + System.getProperty("line.separator") + " <year>2005</year>" + System.getProperty("line.separator") + " <price>29.99</price>" + System.getProperty("line.separator") + " </book>" + System.getProperty("line.separator") + " <book category=\"WEB\">" + System.getProperty("line.separator") + " <title lang=\"en\">Learning XML</title>" + System.getProperty("line.separator") + " <author>Erik T. Ray</author>" + System.getProperty("line.separator") + " <year>2003</year>" + System.getProperty("line.separator") + " <price>31.95</price>" + System.getProperty("line.separator") + " </book>" + System.getProperty("line.separator") + "</bookstore>")), headersToIgnore) ); // - in https assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()), makeRequest( request() .withSecure(true) .withPath(calculatePath("some_path")) .withMethod("POST") .withBody(new StringBody("" + "<?xml version=\"1.0\" encoding=\"ISO-8859-1\"?>" + System.getProperty("line.separator") + "<bookstore>" + System.getProperty("line.separator") + " <book category=\"COOKING\">" + System.getProperty("line.separator") + " <title lang=\"en\">Everyday Italian</title>" + System.getProperty("line.separator") + " <author>Giada De Laurentiis</author>" + System.getProperty("line.separator") + " <year>2005</year>" + System.getProperty("line.separator") + " <price>30.00</price>" + System.getProperty("line.separator") + " </book>" + System.getProperty("line.separator") + " <book category=\"CHILDREN\">" + System.getProperty("line.separator") + " <title lang=\"en\">Harry Potter</title>" + System.getProperty("line.separator") + " <author>J K. Rowling</author>" + System.getProperty("line.separator") + " <year>2005</year>" + System.getProperty("line.separator") + " <price>29.99</price>" + System.getProperty("line.separator") + " </book>" + System.getProperty("line.separator") + " <book category=\"WEB\">" + System.getProperty("line.separator") + " <title lang=\"en\">Learning XML</title>" + System.getProperty("line.separator") + " <author>Erik T. Ray</author>" + System.getProperty("line.separator") + " <year>2003</year>" + System.getProperty("line.separator") + " <price>31.95</price>" + System.getProperty("line.separator") + " </book>" + System.getProperty("line.separator") + "</bookstore>")), headersToIgnore) ); } @Test public void shouldNotReturnResponseForNonMatchingXmlBody() { // when mockServerClient.when(request().withBody(xml("" + "<?xml version=\"1.0\" encoding=\"ISO-8859-1\"?>" + System.getProperty("line.separator") + "<bookstore>" + System.getProperty("line.separator") + " <book category=\"COOKING\" nationality=\"ITALIAN\">" + System.getProperty("line.separator") + " <title lang=\"en\">Everyday Italian</title>" + System.getProperty("line.separator") + " <author>Giada De Laurentiis</author>" + System.getProperty("line.separator") + " <year>2005</year>" + System.getProperty("line.separator") + " <price>30.00</price>" + System.getProperty("line.separator") + " </book>" + System.getProperty("line.separator") + "</bookstore>")), exactly(2)).respond(response().withBody("some_body")); // then // - in http assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()), makeRequest( request() .withSecure(true) .withPath(calculatePath("some_path")) .withMethod("POST") .withBody(new StringBody("" + "<?xml version=\"1.0\" encoding=\"ISO-8859-1\"?>" + System.getProperty("line.separator") + "<bookstore>" + System.getProperty("line.separator") + " <book category=\"COOKING\">" + System.getProperty("line.separator") + " <title lang=\"en\">Everyday Italian</title>" + System.getProperty("line.separator") + " <author>Giada De Laurentiis</author>" + System.getProperty("line.separator") + " <year>2005</year>" + System.getProperty("line.separator") + " <price>30.00</price>" + System.getProperty("line.separator") + " </book>" + System.getProperty("line.separator") + "</bookstore>")), headersToIgnore) ); // - in https assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()), makeRequest( request() .withSecure(true) .withPath(calculatePath("some_path")) .withMethod("POST") .withBody(new StringBody("" + "<?xml version=\"1.0\" encoding=\"ISO-8859-1\"?>" + System.getProperty("line.separator") + "<bookstore>" + System.getProperty("line.separator") + " <book category=\"COOKING\">" + System.getProperty("line.separator") + " <title lang=\"en\">Everyday Italian</title>" + System.getProperty("line.separator") + " <author>Giada De Laurentiis</author>" + System.getProperty("line.separator") + " <year>2005</year>" + System.getProperty("line.separator") + " <price>30.00</price>" + System.getProperty("line.separator") + " </book>" + System.getProperty("line.separator") + "</bookstore>")), headersToIgnore) ); } @Test public void shouldNotReturnResponseForNonMatchingJsonBody() { // when mockServerClient.when(request().withBody(json("{" + System.getProperty("line.separator") + " \"id\": 1," + System.getProperty("line.separator") + " \"name\": \"A green door\"," + System.getProperty("line.separator") + " \"price\": 12.50," + System.getProperty("line.separator") + " \"tags\": [\"home\", \"green\"]" + System.getProperty("line.separator") + "}")), exactly(2)).respond(response().withBody("some_body")); // then // - in http assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()), makeRequest( request() .withPath(calculatePath("some_path")) .withMethod("POST") .withBody("{" + System.getProperty("line.separator") + " \"id\": 1," + System.getProperty("line.separator") + " \"name\": \"---- XXXX WRONG VALUE XXXX ----\"," + System.getProperty("line.separator") + " \"price\": 12.50," + System.getProperty("line.separator") + " \"tags\": [\"home\", \"green\"]" + System.getProperty("line.separator") + "}"), headersToIgnore) ); // - in https assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()), makeRequest( request() .withSecure(true) .withPath(calculatePath("some_path")) .withMethod("POST") .withBody("{" + System.getProperty("line.separator") + " \"id\": 1," + System.getProperty("line.separator") + " \"name\": \"---- XXXX WRONG VALUE XXXX ----\"," + System.getProperty("line.separator") + " \"price\": 12.50," + System.getProperty("line.separator") + " \"tags\": [\"home\", \"green\"]" + System.getProperty("line.separator") + "}"), headersToIgnore) ); } @Test public void shouldNotReturnResponseForNonMatchingJsonBodyWithMatchType() { // when mockServerClient .when( request() .withBody(json("{" + System.getProperty("line.separator") + " \"id\": 1," + System.getProperty("line.separator") + " \"name\": \"A green door\"," + System.getProperty("line.separator") + " \"price\": 12.50," + System.getProperty("line.separator") + " \"tags\": [\"home\", \"green\"]" + System.getProperty("line.separator") + "}", MatchType.STRICT)), exactly(2)) .respond( response() .withBody("some_body") ); // then // - in http assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()), makeRequest( request() .withPath(calculatePath("some_path")) .withMethod("POST") .withBody("{" + System.getProperty("line.separator") + " \"id\": 1," + System.getProperty("line.separator") + " \"extra field\": \"some value\"," + System.getProperty("line.separator") + " \"name\": \"A green door\"," + System.getProperty("line.separator") + " \"price\": 12.50," + System.getProperty("line.separator") + " \"tags\": [\"home\", \"green\"]" + System.getProperty("line.separator") + "}"), headersToIgnore) ); // - in https assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()), makeRequest( request() .withSecure(true) .withPath(calculatePath("some_path")) .withMethod("POST") .withBody("{" + System.getProperty("line.separator") + " \"id\": 1," + System.getProperty("line.separator") + " \"extra field\": \"some value\"," + System.getProperty("line.separator") + " \"name\": \"A green door\"," + System.getProperty("line.separator") + " \"price\": 12.50," + System.getProperty("line.separator") + " \"tags\": [\"home\", \"green\"]" + System.getProperty("line.separator") + "}"), headersToIgnore) ); } @Test public void shouldNotReturnResponseForNonMatchingJsonSchema() { // when mockServerClient.when(request().withBody(jsonSchema("{" + System.getProperty("line.separator") + " \"$schema\": \"http://json-schema.org/draft-04/schema#\"," + System.getProperty("line.separator") + " \"title\": \"Product\"," + System.getProperty("line.separator") + " \"description\": \"A product from Acme's catalog\"," + System.getProperty("line.separator") + " \"type\": \"object\"," + System.getProperty("line.separator") + " \"properties\": {" + System.getProperty("line.separator") + " \"id\": {" + System.getProperty("line.separator") + " \"description\": \"The unique identifier for a product\"," + System.getProperty("line.separator") + " \"type\": \"integer\"" + System.getProperty("line.separator") + " }," + System.getProperty("line.separator") + " \"name\": {" + System.getProperty("line.separator") + " \"description\": \"Name of the product\"," + System.getProperty("line.separator") + " \"type\": \"string\"" + System.getProperty("line.separator") + " }," + System.getProperty("line.separator") + " \"price\": {" + System.getProperty("line.separator") + " \"type\": \"number\"," + System.getProperty("line.separator") + " \"minimum\": 0," + System.getProperty("line.separator") + " \"exclusiveMinimum\": true" + System.getProperty("line.separator") + " }," + System.getProperty("line.separator") + " \"tags\": {" + System.getProperty("line.separator") + " \"type\": \"array\"," + System.getProperty("line.separator") + " \"items\": {" + System.getProperty("line.separator") + " \"type\": \"string\"" + System.getProperty("line.separator") + " }," + System.getProperty("line.separator") + " \"minItems\": 1," + System.getProperty("line.separator") + " \"uniqueItems\": true" + System.getProperty("line.separator") + " }" + System.getProperty("line.separator") + " }," + System.getProperty("line.separator") + " \"required\": [\"id\", \"name\", \"price\"]" + System.getProperty("line.separator") + "}")), exactly(2)).respond(response().withBody("some_body")); // then // - in http assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()), makeRequest( request() .withPath(calculatePath("some_path")) .withMethod("POST") .withBody("{" + System.getProperty("line.separator") + " \"id\": 1," + System.getProperty("line.separator") + " \"wrong field name\": \"A green door\"," + System.getProperty("line.separator") + " \"price\": 12.50," + System.getProperty("line.separator") + " \"tags\": [\"home\", \"green\"]" + System.getProperty("line.separator") + "}"), headersToIgnore) ); // - in https assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()), makeRequest( request() .withSecure(true) .withPath(calculatePath("some_path")) .withMethod("POST") .withBody("{" + System.getProperty("line.separator") + " \"id\": 1," + System.getProperty("line.separator") + " \"name\": \"A green door\"," + System.getProperty("line.separator") + " \"wrong field name\": 12.50," + System.getProperty("line.separator") + " \"tags\": [\"home\", \"green\"]" + System.getProperty("line.separator") + "}"), headersToIgnore) ); } @Test public void shouldNotReturnResponseForNonMatchingPath() { // when mockServerClient .when( request() .withMethod("GET") .withPath(calculatePath("some_path")) .withQueryStringParameters( param("queryStringParameterOneName", "queryStringParameterOneValue"), param("queryStringParameterTwoName", "queryStringParameterTwoValue") ) .withBody(exact("some_body")) .withHeaders(header("headerName", "headerValue")) .withCookies(cookie("cookieName", "cookieValue")) ) .respond( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body") .withHeaders(header("headerName", "headerValue")) .withCookies(cookie("cookieName", "cookieValue")) ); // then // - in http assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()), makeRequest( request() .withMethod("GET") .withPath(calculatePath("some_other_path")) .withQueryStringParameters( param("queryStringParameterOneName", "queryStringParameterOneValue"), param("queryStringParameterTwoName", "queryStringParameterTwoValue") ) .withBody(exact("some_body")) .withHeaders(header("headerName", "headerValue")) .withCookies(cookie("cookieName", "cookieValue")), headersToIgnore) ); // - in https assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()), makeRequest( request() .withMethod("GET") .withSecure(true) .withPath(calculatePath("some_other_path")) .withQueryStringParameters( param("queryStringParameterOneName", "queryStringParameterOneValue"), param("queryStringParameterTwoName", "queryStringParameterTwoValue") ) .withBody(exact("some_body")) .withHeaders(header("headerName", "headerValue")) .withCookies(cookie("cookieName", "cookieValue")), headersToIgnore) ); } @Test public void shouldNotReturnResponseForMatchingPathWithNotOperator() { // when mockServerClient .when( request() .withPath(not(calculatePath("some_path"))) ) .respond( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body_response") ); // then // - in http assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()), makeRequest( request() .withPath(calculatePath("some_path")), headersToIgnore) ); // - in https assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()), makeRequest( request() .withPath(calculatePath("some_path")), headersToIgnore) ); } @Test public void shouldNotReturnResponseForMatchingMethodWithNotOperator() { // when mockServerClient .when( request() .withMethod(not("GET")) ) .respond( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body_response") ); // then // - in http assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()), makeRequest( request() .withMethod("GET"), headersToIgnore) ); // - in https assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()), makeRequest( request() .withMethod("GET"), headersToIgnore) ); } @Test public void shouldNotReturnResponseForNonMatchingBodyParameterName() { // when mockServerClient .when( request() .withMethod("POST") .withPath(calculatePath("some_pathRequest")) .withBody(params( param("bodyParameterOneName", "Parameter One Value One", "Parameter One Value Two"), param("bodyParameterTwoName", "Parameter Two") )) ) .respond( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body_response") .withHeaders(header("headerNameResponse", "headerValueResponse")) .withCookies(cookie("cookieNameResponse", "cookieValueResponse")) ); // then // wrong query string parameter name assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()), makeRequest( request() .withMethod("POST") .withPath(calculatePath("some_pathRequest")) .withBody(params( param("OTHERBodyParameterOneName", "Parameter One Value One", "Parameter One Value Two"), param("bodyParameterTwoName", "Parameter Two") )) .withHeaders(header("headerNameRequest", "headerValueRequest")) .withCookies(cookie("cookieNameRequest", "cookieValueRequest")), headersToIgnore) ); // wrong query string parameter name assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()), makeRequest( request() .withMethod("POST") .withPath(calculatePath("some_pathRequest")) .withBody(new StringBody("OTHERBodyParameterOneName=Parameter+One+Value+One" + "&bodyParameterOneName=Parameter+One+Value+Two" + "&bodyParameterTwoName=Parameter+Two")) .withHeaders(header("headerNameRequest", "headerValueRequest")) .withCookies(cookie("cookieNameRequest", "cookieValueRequest")), headersToIgnore) ); } @Test public void shouldNotReturnResponseForMatchingBodyParameterWithNotOperator() { // when mockServerClient .when( request() .withMethod("POST") .withPath(calculatePath("some_pathRequest")) .withBody(params( param(not("bodyParameterOneName"), not("Parameter One Value One"), not("Parameter One Value Two")), param("bodyParameterTwoName", "Parameter Two") )) ) .respond( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body_response") ); // then // wrong query string parameter name assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()), makeRequest( request() .withMethod("POST") .withPath(calculatePath("some_pathRequest")) .withBody(params( param("bodyParameterOneName", "Parameter One Value One", "Parameter One Value Two"), param("bodyParameterTwoName", "Parameter Two") )) .withHeaders(header("headerNameRequest", "headerValueRequest")) .withCookies(cookie("cookieNameRequest", "cookieValueRequest")), headersToIgnore) ); // wrong query string parameter name assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()), makeRequest( request() .withMethod("POST") .withPath(calculatePath("some_pathRequest")) .withBody(new StringBody("bodyParameterOneName=Other Parameter+One+Value+One" + "&bodyParameterOneName=Parameter+One+Value+Two" + "&bodyParameterTwoName=Parameter+Two")) .withHeaders(header("headerNameRequest", "headerValueRequest")) .withCookies(cookie("cookieNameRequest", "cookieValueRequest")), headersToIgnore) ); } @Test public void shouldNotReturnResponseForNonMatchingBodyParameterValue() { // when mockServerClient .when( request() .withMethod("POST") .withPath(calculatePath("some_pathRequest")) .withBody(params( param("bodyParameterOneName", "Parameter One Value One", "Parameter One Value Two"), param("bodyParameterTwoName", "Parameter Two") )) ) .respond( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body_response") .withHeaders(header("headerNameResponse", "headerValueResponse")) .withCookies(cookie("cookieNameResponse", "cookieValueResponse")) ); // then // wrong body parameter value assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()), makeRequest( request() .withMethod("POST") .withPath(calculatePath("some_pathRequest")) .withBody(params( param("bodyParameterOneName", "Other Parameter One Value One", "Parameter One Value Two"), param("bodyParameterTwoName", "Parameter Two") )) .withHeaders(header("headerNameRequest", "headerValueRequest")) .withCookies(cookie("cookieNameRequest", "cookieValueRequest")), headersToIgnore) ); // wrong body parameter value assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()), makeRequest( request() .withMethod("POST") .withPath(calculatePath("some_pathRequest")) .withBody(new StringBody("bodyParameterOneName=Other Parameter+One+Value+One" + "&bodyParameterOneName=Parameter+One+Value+Two" + "&bodyParameterTwoName=Parameter+Two")) .withHeaders(header("headerNameRequest", "headerValueRequest")) .withCookies(cookie("cookieNameRequest", "cookieValueRequest")), headersToIgnore) ); } @Test public void shouldNotReturnResponseForNonMatchingQueryStringParameterName() { // when mockServerClient .when( request() .withMethod("POST") .withPath(calculatePath("some_pathRequest")) .withQueryStringParameters( param("queryStringParameterOneName", "queryStringParameterOneValueOne", "queryStringParameterOneValueTwo"), param("queryStringParameterTwoName", "queryStringParameterTwoValue") ) .withBody("some_bodyRequest") ) .respond( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body_response") .withHeaders(header("headerNameResponse", "headerValueResponse")) .withCookies(cookie("cookieNameResponse", "cookieValueResponse")) ); // then // wrong query string parameter name assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()), makeRequest( request() .withMethod("POST") .withPath(calculatePath("some_pathRequest")) .withQueryStringParameters( param("OTHERQueryStringParameterOneName", "queryStringParameterOneValueOne", "queryStringParameterOneValueTwo"), param("queryStringParameterTwoName", "queryStringParameterTwoValue") ) .withBody("some_bodyRequest") .withHeaders( header("headerNameRequest", "headerValueRequest") ) .withCookies(cookie("cookieNameRequest", "cookieValueRequest")), headersToIgnore) ); } @Test public void shouldNotReturnResponseForNonMatchingQueryStringParameterValue() { // when mockServerClient .when( request() .withMethod("POST") .withPath(calculatePath("some_pathRequest")) .withQueryStringParameters( param("queryStringParameterOneName", "queryStringParameterOneValueOne", "queryStringParameterOneValueTwo"), param("queryStringParameterTwoName", "queryStringParameterTwoValue") ) .withBody("some_bodyRequest") ) .respond( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body_response") .withHeaders(header("headerNameResponse", "headerValueResponse")) .withCookies(cookie("cookieNameResponse", "cookieValueResponse")) ); // then // wrong query string parameter value assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()), makeRequest( request() .withMethod("POST") .withPath(calculatePath("some_pathRequest")) .withQueryStringParameters( param("queryStringParameterOneName", "OTHERqueryStringParameterOneValueOne", "queryStringParameterOneValueTwo"), param("queryStringParameterTwoName", "queryStringParameterTwoValue") ) .withBody("some_bodyRequest") .withHeaders(header("headerNameRequest", "headerValueRequest")) .withCookies(cookie("cookieNameRequest", "cookieValueRequest")), headersToIgnore) ); } @Test public void shouldNotReturnResponseForMatchingQueryStringParameterWithNotOperator() { // when mockServerClient .when( request() .withMethod("POST") .withPath(calculatePath("some_pathRequest")) .withQueryStringParameters( param(not("queryStringParameterOneName"), not("Parameter One Value One"), not("Parameter One Value Two")), param("queryStringParameterTwoName", "Parameter Two") ) ) .respond( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body_response") ); // then // wrong query string parameter name assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()), makeRequest( request() .withMethod("POST") .withPath(calculatePath("some_pathRequest")) .withQueryStringParameters( param("queryStringParameterOneName", "Parameter One Value One", "Parameter One Value Two"), param("queryStringParameterTwoName", "Parameter Two") ), headersToIgnore) ); // wrong query string parameter name assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()), makeRequest( request() .withMethod("POST") .withPath(calculatePath("some_pathRequest")) .withQueryStringParameters( param("queryStringParameterOneName", "Parameter One Value One", "Parameter One Value Two"), param("queryStringParameterTwoName", "Parameter Two") ), headersToIgnore) ); } @Test public void shouldNotReturnResponseForNonMatchingCookieName() { // when mockServerClient .when( request() .withMethod("GET") .withPath(calculatePath("some_path")) .withQueryStringParameters( param("queryStringParameterOneName", "queryStringParameterOneValue"), param("queryStringParameterTwoName", "queryStringParameterTwoValue") ) .withBody(exact("some_body")) .withHeaders(header("headerName", "headerValue")) .withCookies(cookie("cookieName", "cookieValue")) ) .respond( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body") .withHeaders(header("headerName", "headerValue")) .withCookies(cookie("cookieName", "cookieValue")) ); // then // - in http assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()), makeRequest( request() .withMethod("GET") .withPath(calculatePath("some_path")) .withQueryStringParameters( param("queryStringParameterOneName", "queryStringParameterOneValue"), param("queryStringParameterTwoName", "queryStringParameterTwoValue") ) .withBody(exact("some_body")) .withHeaders(header("headerName", "headerValue")) .withCookies(cookie("cookieOtherName", "cookieValue")), headersToIgnore) ); // - in https assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()), makeRequest( request() .withMethod("GET") .withSecure(true) .withPath(calculatePath("some_path")) .withQueryStringParameters( param("queryStringParameterOneName", "queryStringParameterOneValue"), param("queryStringParameterTwoName", "queryStringParameterTwoValue") ) .withBody(exact("some_body")) .withHeaders(header("headerName", "headerValue")) .withCookies(cookie("cookieOtherName", "cookieValue")), headersToIgnore) ); } @Test public void shouldNotReturnResponseForNonMatchingCookieValue() { // when mockServerClient .when( request() .withMethod("GET") .withPath(calculatePath("some_path")) .withQueryStringParameters( param("queryStringParameterOneName", "queryStringParameterOneValue"), param("queryStringParameterTwoName", "queryStringParameterTwoValue") ) .withBody(exact("some_body")) .withHeaders(header("headerName", "headerValue")) .withCookies(cookie("cookieName", "cookieValue")) ) .respond( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body") .withHeaders(header("headerName", "headerValue")) .withCookies(cookie("cookieName", "cookieValue")) ); // then // - in http assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()), makeRequest( request() .withMethod("GET") .withPath(calculatePath("some_path")) .withQueryStringParameters( param("queryStringParameterOneName", "queryStringParameterOneValue"), param("queryStringParameterTwoName", "queryStringParameterTwoValue") ) .withBody(exact("some_body")) .withHeaders(header("headerName", "headerValue")) .withCookies(cookie("cookieName", "cookieOtherValue")), headersToIgnore) ); // - in https assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()), makeRequest( request() .withMethod("GET") .withSecure(true) .withPath(calculatePath("some_path")) .withQueryStringParameters( param("queryStringParameterOneName", "queryStringParameterOneValue"), param("queryStringParameterTwoName", "queryStringParameterTwoValue") ) .withBody(exact("some_body")) .withHeaders(header("headerName", "headerValue")) .withCookies(cookie("cookieName", "cookieOtherValue")), headersToIgnore) ); } @Test public void shouldNotReturnResponseForMatchingCookieWithNotOperator() { // when mockServerClient .when( request() .withMethod("GET") .withPath(calculatePath("some_pathRequest")) .withCookies( cookie(not("requestCookieNameOne"), not("requestCookieValueOne")), cookie("requestCookieNameTwo", "requestCookieValueTwo") ) ) .respond( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body_response") ); // then // wrong query string parameter name assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()), makeRequest( request() .withMethod("GET") .withPath(calculatePath("some_pathRequest")) .withCookies( cookie("requestCookieNameOne", "requestCookieValueOne"), cookie("requestCookieNameTwo", "requestCookieValueTwo") ), headersToIgnore) ); // wrong query string parameter name assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()), makeRequest( request() .withMethod("GET") .withPath(calculatePath("some_pathRequest")) .withCookies( cookie("requestCookieNameOne", "requestCookieValueOne"), cookie("requestCookieNameTwo", "requestCookieValueTwo") ), headersToIgnore) ); } @Test public void shouldNotReturnResponseForNonMatchingHeaderName() { // when mockServerClient .when( request() .withMethod("GET") .withPath(calculatePath("some_path")) .withQueryStringParameters( param("queryStringParameterOneName", "queryStringParameterOneValue"), param("queryStringParameterTwoName", "queryStringParameterTwoValue") ) .withBody(exact("some_body")) .withHeaders(header("headerName", "headerValue")) .withCookies(cookie("cookieName", "cookieValue")) ) .respond( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body") .withHeaders(header("headerName", "headerValue")) .withCookies(cookie("cookieName", "cookieValue")) ); // then // - in http assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()), makeRequest( request() .withMethod("GET") .withPath(calculatePath("some_path")) .withQueryStringParameters( param("queryStringParameterOneName", "queryStringParameterOneValue"), param("queryStringParameterTwoName", "queryStringParameterTwoValue") ) .withBody(exact("some_body")) .withHeaders(header("headerOtherName", "headerValue")) .withCookies(cookie("cookieName", "cookieValue")), headersToIgnore) ); // - in https assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()), makeRequest( request() .withMethod("GET") .withSecure(true) .withPath(calculatePath("some_path")) .withQueryStringParameters( param("queryStringParameterOneName", "queryStringParameterOneValue"), param("queryStringParameterTwoName", "queryStringParameterTwoValue") ) .withBody(exact("some_body")) .withHeaders(header("headerOtherName", "headerValue")) .withCookies(cookie("cookieName", "cookieValue")), headersToIgnore) ); } @Test public void shouldNotReturnResponseForNonMatchingHeaderValue() { // when mockServerClient .when( request() .withMethod("GET") .withPath(calculatePath("some_path")) .withQueryStringParameters( param("queryStringParameterOneName", "queryStringParameterOneValue"), param("queryStringParameterTwoName", "queryStringParameterTwoValue") ) .withBody(exact("some_body")) .withHeaders(header("headerName", "headerValue")) .withCookies(cookie("cookieName", "cookieValue")) ) .respond( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body") .withHeaders(header("headerName", "headerValue")) .withCookies(cookie("cookieName", "cookieValue")) ); // then // - in http assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()), makeRequest( request() .withMethod("GET") .withPath(calculatePath("some_path")) .withQueryStringParameters( param("queryStringParameterOneName", "queryStringParameterOneValue"), param("queryStringParameterTwoName", "queryStringParameterTwoValue") ) .withBody(exact("some_body")) .withHeaders(header("headerName", "headerOtherValue")) .withCookies(cookie("cookieName", "cookieValue")), headersToIgnore) ); // - in https assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()), makeRequest( request() .withMethod("GET") .withSecure(true) .withPath(calculatePath("some_path")) .withQueryStringParameters( param("queryStringParameterOneName", "queryStringParameterOneValue"), param("queryStringParameterTwoName", "queryStringParameterTwoValue") ) .withBody(exact("some_body")) .withHeaders(header("headerName", "headerOtherValue")) .withCookies(cookie("cookieName", "cookieValue")), headersToIgnore) ); } @Test public void shouldNotReturnResponseForMatchingHeaderWithNotOperator() { // when mockServerClient .when( request() .withMethod("GET") .withPath(calculatePath("some_pathRequest")) .withHeaders( header(not("requestHeaderNameOne"), not("requestHeaderValueOne")), header("requestHeaderNameTwo", "requestHeaderValueTwo") ) ) .respond( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body_response") ); // then // wrong query string parameter name assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()), makeRequest( request() .withMethod("GET") .withPath(calculatePath("some_pathRequest")) .withHeaders( header("requestHeaderNameOne", "requestHeaderValueOne"), header("requestHeaderNameTwo", "requestHeaderValueTwo") ), headersToIgnore) ); // wrong query string parameter name assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()), makeRequest( request() .withMethod("GET") .withPath(calculatePath("some_pathRequest")) .withHeaders( header("requestHeaderNameOne", "requestHeaderValueOne"), header("requestHeaderNameTwo", "requestHeaderValueTwo") ), headersToIgnore) ); } @Test public void shouldVerifyReceivedRequests() { // when mockServerClient .when( request() .withPath(calculatePath("some_path")), exactly(2) ) .respond( response() .withBody("some_body") ); // then // - in http assertEquals( response() .withHeader(HttpHeaders.CONTENT_TYPE, TEXT_PLAIN) .withStatusCode(HttpStatusCode.OK_200.code()) .withBody("some_body"), makeRequest( request() .withPath(calculatePath("some_path")), headersToIgnore) ); mockServerClient.verify(request() .withPath(calculatePath("some_path"))); mockServerClient.verify(request() .withPath(calculatePath("some_path")), VerificationTimes.exactly(1)); // - in https assertEquals( response() .withHeader(HttpHeaders.CONTENT_TYPE, TEXT_PLAIN) .withStatusCode(HttpStatusCode.OK_200.code()) .withBody("some_body"), makeRequest( request() .withSecure(true) .withPath(calculatePath("some_path")), headersToIgnore) ); mockServerClient.verify(request().withPath(calculatePath("some_path")), VerificationTimes.atLeast(1)); mockServerClient.verify(request().withPath(calculatePath("some_path")), VerificationTimes.exactly(2)); } @Test public void shouldVerifyReceivedRequestInSsl() { // when mockServerClient .when( request() .withPath(calculatePath("some.*path")), exactly(2) ) .respond( response() .withBody("some_body") ); // then // - in http assertEquals( response() .withHeader(HttpHeaders.CONTENT_TYPE, TEXT_PLAIN) .withStatusCode(HttpStatusCode.OK_200.code()) .withBody("some_body"), makeRequest( request() .withPath(calculatePath("some_path")), headersToIgnore) ); mockServerClient.verify(request() .withPath(calculatePath("some_path")) .withSecure(false)); mockServerClient.verify(request() .withPath(calculatePath("some_path")) .withSecure(false), VerificationTimes.exactly(1)); // - in https assertEquals( response() .withHeader(HttpHeaders.CONTENT_TYPE, TEXT_PLAIN) .withStatusCode(HttpStatusCode.OK_200.code()) .withBody("some_body"), makeRequest( request() .withPath(calculatePath("some_secure_path")) .withSecure(true), headersToIgnore) ); mockServerClient.verify(request() .withPath(calculatePath("some_secure_path")) .withSecure(true)); mockServerClient.verify(request() .withPath(calculatePath("some_secure_path")) .withSecure(true), VerificationTimes.exactly(1)); } @Test public void shouldVerifyReceivedRequestsWithNoBody() { // when mockServerClient.when(request().withPath(calculatePath("some_path")), exactly(2)).respond(response()); // then // - in http assertEquals( response() .withStatusCode(HttpStatusCode.OK_200.code()), makeRequest( request() .withPath(calculatePath("some_path")), headersToIgnore) ); mockServerClient.verify(request() .withPath(calculatePath("some_path"))); mockServerClient.verify(request() .withPath(calculatePath("some_path")), VerificationTimes.exactly(1)); } @Test public void shouldVerifyNotEnoughRequestsReceived() { // when mockServerClient.when(request().withPath(calculatePath("some_path")), exactly(2)).respond(response().withBody("some_body")); // then assertEquals( response() .withHeader(HttpHeaders.CONTENT_TYPE, TEXT_PLAIN) .withStatusCode(HttpStatusCode.OK_200.code()) .withBody("some_body"), makeRequest( request() .withPath(calculatePath("some_path")), headersToIgnore) ); try { mockServerClient.verify(request() .withPath(calculatePath("some_path")), VerificationTimes.atLeast(2)); fail(); } catch (AssertionError ae) { assertThat(ae.getMessage(), startsWith("Request not found at least 2 times, expected:<{" + System.getProperty("line.separator") + " \"path\" : \"" + calculatePath("some_path") + "\"" + System.getProperty("line.separator") + "}> but was:<{" + System.getProperty("line.separator") + " \"method\" : \"GET\"," + System.getProperty("line.separator") + " \"path\" : \"" + calculatePath("some_path") + "\"," + System.getProperty("line.separator"))); } } @Test public void shouldVerifyTooManyRequestsReceived() { // when mockServerClient.when(request().withPath(calculatePath("some_path")), exactly(2)).respond(response().withBody("some_body")); // then assertEquals( response() .withHeader(HttpHeaders.CONTENT_TYPE, TEXT_PLAIN) .withStatusCode(HttpStatusCode.OK_200.code()) .withBody("some_body"), makeRequest( request() .withPath(calculatePath("some_path")), headersToIgnore) ); try { mockServerClient.verify(request() .withPath(calculatePath("some_path")), VerificationTimes.exactly(0)); fail(); } catch (AssertionError ae) { assertThat(ae.getMessage(), startsWith("Request not found exactly 0 times, expected:<{" + System.getProperty("line.separator") + " \"path\" : \"" + calculatePath("some_path") + "\"" + System.getProperty("line.separator") + "}> but was:<{" + System.getProperty("line.separator") + " \"method\" : \"GET\"," + System.getProperty("line.separator") + " \"path\" : \"" + calculatePath("some_path") + "\"," + System.getProperty("line.separator"))); } } @Test public void shouldVerifyNoMatchingRequestsReceived() { // when mockServerClient.when(request().withPath(calculatePath("some_path")), exactly(2)).respond(response().withBody("some_body")); // then assertEquals( response() .withHeader(HttpHeaders.CONTENT_TYPE, TEXT_PLAIN) .withStatusCode(HttpStatusCode.OK_200.code()) .withBody("some_body"), makeRequest( request() .withPath(calculatePath("some_path")), headersToIgnore) ); try { mockServerClient.verify(request() .withPath(calculatePath("some_other_path")), VerificationTimes.exactly(2)); fail(); } catch (AssertionError ae) { assertThat(ae.getMessage(), startsWith("Request not found exactly 2 times, expected:<{" + System.getProperty("line.separator") + " \"path\" : \"" + calculatePath("some_other_path") + "\"" + System.getProperty("line.separator") + "}> but was:<{" + System.getProperty("line.separator") + " \"method\" : \"GET\"," + System.getProperty("line.separator") + " \"path\" : \"" + calculatePath("some_path") + "\"," + System.getProperty("line.separator"))); } } @Test public void shouldVerifyNoRequestsReceived() { // when mockServerClient.reset(); // then mockServerClient.verifyZeroInteractions(); } @Test public void shouldNotVerifyNoRequestsReceived() { // when mockServerClient.when(request().withPath(calculatePath("some_path")), exactly(2)).respond(response().withBody("some_body")); // then assertEquals( response() .withHeader(HttpHeaders.CONTENT_TYPE, TEXT_PLAIN) .withStatusCode(HttpStatusCode.OK_200.code()) .withBody("some_body"), makeRequest( request() .withPath(calculatePath("some_path")), headersToIgnore) ); try { mockServerClient.verifyZeroInteractions(); fail(); } catch (AssertionError ae) { assertThat(ae.getMessage(), startsWith("Request not found exactly 0 times, expected:<{ }> but was:<{" + System.getProperty("line.separator") + " \"method\" : \"GET\"," + System.getProperty("line.separator") + " \"path\" : \"" + calculatePath("some_path") + "\"," + System.getProperty("line.separator"))); } } @Test public void shouldVerifyNoMatchingRequestsReceivedInSsl() { // when mockServerClient.when(request().withPath(calculatePath("some.*path")), exactly(2)).respond(response().withBody("some_body")); // then // - in http assertEquals( response() .withHeader(HttpHeaders.CONTENT_TYPE, TEXT_PLAIN) .withStatusCode(HttpStatusCode.OK_200.code()) .withBody("some_body"), makeRequest( request() .withPath(calculatePath("some_path")), headersToIgnore) ); try { mockServerClient.verify( request() .withPath(calculatePath("some_path")) .withSecure(true), VerificationTimes.atLeast(1) ); fail(); } catch (AssertionError ae) { assertThat(ae.getMessage(), startsWith("Request not found at least once, expected:<{" + System.getProperty("line.separator") + " \"path\" : \"" + calculatePath("some_path") + "\"," + System.getProperty("line.separator") + " \"secure\" : true" + System.getProperty("line.separator") + "}> but was:<{" + System.getProperty("line.separator") + " \"method\" : \"GET\"," + System.getProperty("line.separator") + " \"path\" : \"" + calculatePath("some_path") + "\"," + System.getProperty("line.separator"))); } // - in https assertEquals( response() .withHeader(HttpHeaders.CONTENT_TYPE, TEXT_PLAIN) .withStatusCode(HttpStatusCode.OK_200.code()) .withBody("some_body"), makeRequest( request() .withPath(calculatePath("some_secure_path")) .withSecure(true), headersToIgnore) ); try { mockServerClient.verify( request() .withPath(calculatePath("some_secure_path")) .withSecure(false), VerificationTimes.atLeast(1) ); fail(); } catch (AssertionError ae) { assertThat(ae.getMessage(), startsWith("Request not found at least once, expected:<{" + System.getProperty("line.separator") + " \"path\" : \"" + calculatePath("some_secure_path") + "\"," + System.getProperty("line.separator") + " \"secure\" : false" + System.getProperty("line.separator") + "}> but was:<[ {" + System.getProperty("line.separator") + " \"method\" : \"GET\"," + System.getProperty("line.separator") + " \"path\" : \"" + calculatePath("some_path") + "\"," + System.getProperty("line.separator"))); } } @Test public void shouldVerifySequenceOfRequestsReceived() { // when mockServerClient.when(request().withPath(calculatePath("some_path.*")), exactly(6)).respond(response().withBody("some_body")); // then assertEquals( response("some_body").withHeader(HttpHeaders.CONTENT_TYPE, TEXT_PLAIN), makeRequest( request().withPath(calculatePath("some_path_one")), headersToIgnore) ); assertEquals( response("some_body").withHeader(HttpHeaders.CONTENT_TYPE, TEXT_PLAIN), makeRequest( request().withPath(calculatePath("some_path_two")), headersToIgnore) ); assertEquals( response("some_body").withHeader(HttpHeaders.CONTENT_TYPE, TEXT_PLAIN), makeRequest( request().withPath(calculatePath("some_path_three")), headersToIgnore) ); mockServerClient.verify(request(calculatePath("some_path_one")), request(calculatePath("some_path_three"))); mockServerClient.verify(request(calculatePath("some_path_one")), request(calculatePath("some_path_two"))); mockServerClient.verify(request(calculatePath("some_path_one")), request(calculatePath("some_path_two")), request(calculatePath("some_path_three"))); } @Test public void shouldVerifySequenceOfRequestsReceivedIncludingThoseNotMatchingAnException() { // when mockServerClient.when(request().withPath(calculatePath("some_path.*")), exactly(4)).respond(response().withBody("some_body")); // then assertEquals( response("some_body").withHeader(HttpHeaders.CONTENT_TYPE, TEXT_PLAIN), makeRequest( request().withPath(calculatePath("some_path_one")), headersToIgnore) ); assertEquals( notFoundResponse(), makeRequest( request().withPath(calculatePath("not_found")), headersToIgnore) ); assertEquals( response("some_body").withHeader(HttpHeaders.CONTENT_TYPE, TEXT_PLAIN), makeRequest( request().withPath(calculatePath("some_path_three")), headersToIgnore) ); mockServerClient.verify(request(calculatePath("some_path_one")), request(calculatePath("some_path_three"))); mockServerClient.verify(request(calculatePath("some_path_one")), request(calculatePath("not_found"))); mockServerClient.verify(request(calculatePath("some_path_one")), request(calculatePath("not_found")), request(calculatePath("some_path_three"))); mockServerClient.verify(request(calculatePath("some_path_one")), request(calculatePath("not_found")), request(calculatePath("some_path_three"))); } @Test public void shouldRetrieveSequenceOfRequestsReceivedIncludingThoseNotMatchingAnException() { // when mockServerClient.when(request().withPath(calculatePath("some_path.*")), exactly(4)).respond(response().withBody("some_body")); assertEquals( response("some_body").withHeader(HttpHeaders.CONTENT_TYPE, TEXT_PLAIN), makeRequest( request().withPath(calculatePath("some_path_one")), headersToIgnore) ); assertEquals( notFoundResponse(), makeRequest( request().withPath(calculatePath("not_found")), headersToIgnore) ); assertEquals( response("some_body").withHeader(HttpHeaders.CONTENT_TYPE, TEXT_PLAIN), makeRequest( request().withPath(calculatePath("some_path_three")), headersToIgnore) ); // then verifyRequestMatches( mockServerClient.retrieveRecordedRequests(request().withPath(calculatePath("some_path.*"))), request(calculatePath("some_path_one")), request(calculatePath("some_path_three")) ); verifyRequestMatches( mockServerClient.retrieveRecordedRequests(request()), request(calculatePath("some_path_one")), request(calculatePath("not_found")), request(calculatePath("some_path_three")) ); verifyRequestMatches( mockServerClient.retrieveRecordedRequests(null), request(calculatePath("some_path_one")), request(calculatePath("not_found")), request(calculatePath("some_path_three")) ); } @Test public void shouldRetrieveSequenceOfExpectationsSetup() { // when mockServerClient.when(request().withPath(calculatePath("some_path.*")), exactly(4)) .respond(response().withBody("some_body")); mockServerClient.when(request().withPath(calculatePath("some_path.*"))) .respond(response().withBody("some_body")); mockServerClient.when(request().withPath(calculatePath("some_other_path"))) .respond(response().withBody("some_other_body")); mockServerClient.when(request().withPath(calculatePath("some_forward_path"))) .forward(forward()); // then assertThat( mockServerClient.retrieveExistingExpectations(request().withPath(calculatePath("some_path.*"))), arrayContaining( new Expectation(request().withPath(calculatePath("some_path.*")), exactly(4), TimeToLive.unlimited()) .thenRespond(response().withBody("some_body")), expectation(request().withPath(calculatePath("some_path.*"))) .thenRespond(response().withBody("some_body")) ) ); assertThat( mockServerClient.retrieveExistingExpectations(null), arrayContaining( new Expectation(request().withPath(calculatePath("some_path.*")), exactly(4), TimeToLive.unlimited()) .thenRespond(response().withBody("some_body")), expectation(request().withPath(calculatePath("some_path.*"))) .thenRespond(response().withBody("some_body")), expectation(request().withPath(calculatePath("some_other_path"))) .thenRespond(response().withBody("some_other_body")), expectation(request().withPath(calculatePath("some_forward_path"))) .thenForward(forward()) ) ); assertThat( mockServerClient.retrieveExistingExpectations(request()), arrayContaining( new Expectation(request().withPath(calculatePath("some_path.*")), exactly(4), TimeToLive.unlimited()) .thenRespond(response().withBody("some_body")), expectation(request().withPath(calculatePath("some_path.*"))) .thenRespond(response().withBody("some_body")), expectation(request().withPath(calculatePath("some_other_path"))) .thenRespond(response().withBody("some_other_body")), expectation(request().withPath(calculatePath("some_forward_path"))) .thenForward(forward()) ) ); } @Test public void shouldVerifySequenceOfRequestsNotReceived() { // when mockServerClient.when(request().withPath(calculatePath("some_path.*")), exactly(6)).respond(response().withBody("some_body")); // then assertEquals( response("some_body").withHeader(HttpHeaders.CONTENT_TYPE, TEXT_PLAIN), makeRequest( request().withPath(calculatePath("some_path_one")), headersToIgnore) ); assertEquals( response("some_body").withHeader(HttpHeaders.CONTENT_TYPE, TEXT_PLAIN), makeRequest( request().withPath(calculatePath("some_path_two")), headersToIgnore) ); assertEquals( response("some_body").withHeader(HttpHeaders.CONTENT_TYPE, TEXT_PLAIN), makeRequest( request().withPath(calculatePath("some_path_three")), headersToIgnore) ); try { mockServerClient.verify(request(calculatePath("some_path_two")), request(calculatePath("some_path_one"))); fail(); } catch (AssertionError ae) { assertThat(ae.getMessage(), startsWith("Request sequence not found, expected:<[ {" + System.getProperty("line.separator") + " \"path\" : \"" + calculatePath("some_path_two") + "\"" + System.getProperty("line.separator") + "}, {" + System.getProperty("line.separator") + " \"path\" : \"" + calculatePath("some_path_one") + "\"" + System.getProperty("line.separator") + "} ]> but was:<[ {" + System.getProperty("line.separator") + " \"method\" : \"GET\"," + System.getProperty("line.separator") + " \"path\" : \"" + calculatePath("some_path_one") + "\"," + System.getProperty("line.separator"))); } try { mockServerClient.verify(request(calculatePath("some_path_three")), request(calculatePath("some_path_two"))); fail(); } catch (AssertionError ae) { assertThat(ae.getMessage(), startsWith("Request sequence not found, expected:<[ {" + System.getProperty("line.separator") + " \"path\" : \"" + calculatePath("some_path_three") + "\"" + System.getProperty("line.separator") + "}, {" + System.getProperty("line.separator") + " \"path\" : \"" + calculatePath("some_path_two") + "\"" + System.getProperty("line.separator") + "} ]> but was:<[ {" + System.getProperty("line.separator") + " \"method\" : \"GET\"," + System.getProperty("line.separator") + " \"path\" : \"" + calculatePath("some_path_one") + "\"," + System.getProperty("line.separator"))); } try { mockServerClient.verify(request(calculatePath("some_path_four"))); fail(); } catch (AssertionError ae) { assertThat(ae.getMessage(), startsWith("Request sequence not found, expected:<[ {" + System.getProperty("line.separator") + " \"path\" : \"" + calculatePath("some_path_four") + "\"" + System.getProperty("line.separator") + "} ]> but was:<[ {" + System.getProperty("line.separator") + " \"method\" : \"GET\"," + System.getProperty("line.separator") + " \"path\" : \"" + calculatePath("some_path_one") + "\"," + System.getProperty("line.separator"))); } } @Test public void shouldClearExpectationsAndLogs() { // given - some expectations mockServerClient .when( request() .withPath(calculatePath("some_path1")) ) .respond( response() .withBody("some_body1") ); mockServerClient .when( request() .withPath(calculatePath("some_path2")) ) .respond( response() .withBody("some_body2") ); // and - some matching requests assertEquals( response() .withHeader(HttpHeaders.CONTENT_TYPE, TEXT_PLAIN) .withStatusCode(HttpStatusCode.OK_200.code()) .withBody("some_body1"), makeRequest( request() .withPath(calculatePath("some_path1")), headersToIgnore) ); assertEquals( response() .withHeader(HttpHeaders.CONTENT_TYPE, TEXT_PLAIN) .withStatusCode(HttpStatusCode.OK_200.code()) .withBody("some_body2"), makeRequest( request() .withPath(calculatePath("some_path2")), headersToIgnore) ); // when mockServerClient .clear( request() .withPath(calculatePath("some_path1")) ); // then - expectations cleared assertThat( mockServerClient.retrieveExistingExpectations(null), arrayContaining( expectation( request() .withPath(calculatePath("some_path2")) ) .thenRespond( response() .withBody("some_body2") ) ) ); // and then - request log cleared verifyRequestMatches( mockServerClient.retrieveRecordedRequests(null), request(calculatePath("some_path2")) ); // and then - remaining expectations not cleared assertEquals( response() .withHeader(HttpHeaders.CONTENT_TYPE, TEXT_PLAIN) .withStatusCode(HttpStatusCode.OK_200.code()) .withBody("some_body2"), makeRequest( request() .withPath(calculatePath("some_path2")), headersToIgnore) ); assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()), makeRequest( request() .withPath(calculatePath("some_path1")), headersToIgnore) ); } @Test public void shouldClearExpectationsOnly() { // given - some expectations mockServerClient .when( request() .withPath(calculatePath("some_path1")) ) .respond( response() .withBody("some_body1") ); mockServerClient .when( request() .withPath(calculatePath("some_path2")) ) .respond( response() .withBody("some_body2") ); // and - some matching requests assertEquals( response() .withHeader(HttpHeaders.CONTENT_TYPE, TEXT_PLAIN) .withStatusCode(HttpStatusCode.OK_200.code()) .withBody("some_body1"), makeRequest( request() .withPath(calculatePath("some_path1")), headersToIgnore) ); assertEquals( response() .withHeader(HttpHeaders.CONTENT_TYPE, TEXT_PLAIN) .withStatusCode(HttpStatusCode.OK_200.code()) .withBody("some_body2"), makeRequest( request() .withPath(calculatePath("some_path2")), headersToIgnore) ); // when mockServerClient .clear( request() .withPath(calculatePath("some_path1")), MockServerClient.TYPE.EXPECTATION ); // then - expectations cleared assertThat( mockServerClient.retrieveExistingExpectations(null), arrayContaining( expectation( request() .withPath(calculatePath("some_path2")) ) .thenRespond( response() .withBody("some_body2") ) ) ); // and then - request log not cleared verifyRequestMatches( mockServerClient.retrieveRecordedRequests(null), request(calculatePath("some_path1")), request(calculatePath("some_path2")) ); } @Test public void shouldClearLogsOnly() { // given - some expectations mockServerClient .when( request() .withPath(calculatePath("some_path1")) ) .respond( response() .withBody("some_body1") ); mockServerClient .when( request() .withPath(calculatePath("some_path2")) ) .respond( response() .withBody("some_body2") ); // and - some matching requests assertEquals( response() .withHeader(HttpHeaders.CONTENT_TYPE, TEXT_PLAIN) .withStatusCode(HttpStatusCode.OK_200.code()) .withBody("some_body1"), makeRequest( request() .withPath(calculatePath("some_path1")), headersToIgnore) ); assertEquals( response() .withHeader(HttpHeaders.CONTENT_TYPE, TEXT_PLAIN) .withStatusCode(HttpStatusCode.OK_200.code()) .withBody("some_body2"), makeRequest( request() .withPath(calculatePath("some_path2")), headersToIgnore) ); // when mockServerClient .clear( request() .withPath(calculatePath("some_path1")), MockServerClient.TYPE.LOG ); // then - expectations cleared assertThat( mockServerClient.retrieveExistingExpectations(null), arrayContaining( expectation( request() .withPath(calculatePath("some_path1")) ) .thenRespond( response() .withBody("some_body1") ), expectation( request() .withPath(calculatePath("some_path2")) ) .thenRespond( response() .withBody("some_body2") ) ) ); // and then - request log cleared verifyRequestMatches( mockServerClient.retrieveRecordedRequests(null), request(calculatePath("some_path2")) ); } @Test public void shouldClearAllExpectationsWithNull() { // given mockServerClient .when( request() .withPath(calculatePath("some_path1")) ) .respond( response() .withBody("some_body1") ); mockServerClient .when( request() .withPath(calculatePath("some_path2")) ) .respond( response() .withBody("some_body2") ); assertEquals( response() .withHeader(HttpHeaders.CONTENT_TYPE, TEXT_PLAIN) .withStatusCode(HttpStatusCode.OK_200.code()) .withBody("some_body2"), makeRequest( request() .withPath(calculatePath("some_path2")), headersToIgnore) ); // when mockServerClient.clear(null); // then assertThat(mockServerClient.retrieveExistingExpectations(null), emptyArray()); assertThat(mockServerClient.retrieveRecordedRequests(null), emptyArray()); } @Test public void shouldClearAllExpectationsWithEmptyRequest() { // given mockServerClient .when( request() .withPath(calculatePath("some_path1")) ) .respond( response() .withBody("some_body1") ); mockServerClient .when( request() .withPath(calculatePath("some_path2")) ) .respond( response() .withBody("some_body2") ); assertEquals( response() .withHeader(HttpHeaders.CONTENT_TYPE, TEXT_PLAIN) .withStatusCode(HttpStatusCode.OK_200.code()) .withBody("some_body2"), makeRequest( request() .withPath(calculatePath("some_path2")), headersToIgnore) ); // when mockServerClient.clear(request()); // then assertThat(mockServerClient.retrieveExistingExpectations(null), emptyArray()); assertThat(mockServerClient.retrieveRecordedRequests(null), emptyArray()); } @Test public void shouldClearExpectationsWithXPathBody() { // given mockServerClient .when( request() .withBody(xpath("/bookstore/book[year=2005]/price")) ) .respond( response() .withBody("some_body1") ); mockServerClient .when( request() .withBody(xpath("/bookstore/book[year=2006]/price")) ) .respond( response() .withBody("some_body2") ); // and StringBody xmlBody = new StringBody("" + "<?xml version=\"1.0\" encoding=\"ISO-8859-1\"?>" + System.getProperty("line.separator") + "<bookstore>" + System.getProperty("line.separator") + " <book category=\"COOKING\">" + System.getProperty("line.separator") + " <title lang=\"en\">Everyday Italian</title>" + System.getProperty("line.separator") + " <author>Giada De Laurentiis</author>" + System.getProperty("line.separator") + " <year>2005</year>" + System.getProperty("line.separator") + " <price>30.00</price>" + System.getProperty("line.separator") + " </book>" + System.getProperty("line.separator") + " <book category=\"CHILDREN\">" + System.getProperty("line.separator") + " <title lang=\"en\">Harry Potter</title>" + System.getProperty("line.separator") + " <author>J K. Rowling</author>" + System.getProperty("line.separator") + " <year>2006</year>" + System.getProperty("line.separator") + " <price>29.99</price>" + System.getProperty("line.separator") + " </book>" + System.getProperty("line.separator") + " <book category=\"WEB\">" + System.getProperty("line.separator") + " <title lang=\"en\">Learning XML</title>" + System.getProperty("line.separator") + " <author>Erik T. Ray</author>" + System.getProperty("line.separator") + " <year>2003</year>" + System.getProperty("line.separator") + " <price>31.95</price>" + System.getProperty("line.separator") + " </book>" + System.getProperty("line.separator") + "</bookstore>"); // then assertEquals( response() .withHeader(HttpHeaders.CONTENT_TYPE, TEXT_PLAIN) .withStatusCode(HttpStatusCode.OK_200.code()) .withBody("some_body1"), makeRequest( request() .withBody(xmlBody), headersToIgnore) ); // when mockServerClient .clear( request() .withBody(xpath("/bookstore/book[year=2005]/price")) ); // then assertThat( mockServerClient.retrieveExistingExpectations(null), arrayContaining( expectation( request() .withBody(xpath("/bookstore/book[year=2006]/price")) ) .thenRespond( response() .withBody("some_body2") ) ) ); // - in http assertEquals( response() .withHeader(HttpHeaders.CONTENT_TYPE, TEXT_PLAIN) .withStatusCode(HttpStatusCode.OK_200.code()) .withBody("some_body2"), makeRequest( request() .withBody(xmlBody), headersToIgnore) ); // - in https assertEquals( response() .withHeader(HttpHeaders.CONTENT_TYPE, TEXT_PLAIN) .withStatusCode(HttpStatusCode.OK_200.code()) .withBody("some_body2"), makeRequest( request() .withSecure(true) .withBody(xmlBody), headersToIgnore) ); } @Test public void shouldClearExpectationsWithJsonSchemaBody() { // given JsonSchemaBody jsonSchemaBodyOne = jsonSchema("{" + System.getProperty("line.separator") + " \"$schema\": \"http://json-schema.org/draft-04/schema#\"," + System.getProperty("line.separator") + " \"title\": \"Product\"," + System.getProperty("line.separator") + " \"description\": \"A product from Acme's catalog\"," + System.getProperty("line.separator") + " \"type\": \"object\"," + System.getProperty("line.separator") + " \"properties\": {" + System.getProperty("line.separator") + " \"id\": {" + System.getProperty("line.separator") + " \"description\": \"The unique identifier for a product\"," + System.getProperty("line.separator") + " \"type\": \"integer\"" + System.getProperty("line.separator") + " }," + System.getProperty("line.separator") + " \"name\": {" + System.getProperty("line.separator") + " \"description\": \"Name of the product\"," + System.getProperty("line.separator") + " \"type\": \"string\"" + System.getProperty("line.separator") + " }," + System.getProperty("line.separator") + " \"price\": {" + System.getProperty("line.separator") + " \"type\": \"number\"," + System.getProperty("line.separator") + " \"minimum\": 0," + System.getProperty("line.separator") + " \"exclusiveMinimum\": true" + System.getProperty("line.separator") + " }," + System.getProperty("line.separator") + " \"tags\": {" + System.getProperty("line.separator") + " \"type\": \"array\"," + System.getProperty("line.separator") + " \"items\": {" + System.getProperty("line.separator") + " \"type\": \"string\"" + System.getProperty("line.separator") + " }," + System.getProperty("line.separator") + " \"minItems\": 1," + System.getProperty("line.separator") + " \"uniqueItems\": true" + System.getProperty("line.separator") + " }" + System.getProperty("line.separator") + " }," + System.getProperty("line.separator") + " \"required\": [\"id\", \"name\", \"price\"]" + System.getProperty("line.separator") + "}"); JsonSchemaBody jsonSchemaBodyTwo = jsonSchema("{" + System.getProperty("line.separator") + " \"$schema\": \"http://json-schema.org/draft-04/schema#\"," + System.getProperty("line.separator") + " \"title\": \"Product\"," + System.getProperty("line.separator") + " \"description\": \"A product from Acme's catalog\"," + System.getProperty("line.separator") + " \"type\": \"object\"," + System.getProperty("line.separator") + " \"properties\": {" + System.getProperty("line.separator") + " \"id\": {" + System.getProperty("line.separator") + " \"description\": \"The unique identifier for a product\"," + System.getProperty("line.separator") + " \"type\": \"integer\"" + System.getProperty("line.separator") + " }," + System.getProperty("line.separator") + " \"name\": {" + System.getProperty("line.separator") + " \"description\": \"Name of the product\"," + System.getProperty("line.separator") + " \"type\": \"string\"" + System.getProperty("line.separator") + " }," + System.getProperty("line.separator") + " \"price\": {" + System.getProperty("line.separator") + " \"type\": \"number\"," + System.getProperty("line.separator") + " \"minimum\": 10," + System.getProperty("line.separator") + " \"exclusiveMinimum\": true" + System.getProperty("line.separator") + " }," + System.getProperty("line.separator") + " \"tags\": {" + System.getProperty("line.separator") + " \"type\": \"array\"," + System.getProperty("line.separator") + " \"items\": {" + System.getProperty("line.separator") + " \"type\": \"string\"" + System.getProperty("line.separator") + " }," + System.getProperty("line.separator") + " \"minItems\": 1," + System.getProperty("line.separator") + " \"uniqueItems\": true" + System.getProperty("line.separator") + " }" + System.getProperty("line.separator") + " }," + System.getProperty("line.separator") + " \"required\": [\"id\", \"name\", \"price\"]" + System.getProperty("line.separator") + "}"); mockServerClient .when( request() .withBody(jsonSchemaBodyOne) ) .respond( response() .withBody("some_body1") ); mockServerClient .when( request() .withBody(jsonSchemaBodyTwo) ) .respond( response() .withBody("some_body2") ); // then assertEquals( response() .withHeader(HttpHeaders.CONTENT_TYPE, TEXT_PLAIN) .withStatusCode(HttpStatusCode.OK_200.code()) .withBody("some_body1"), makeRequest( request() .withBody("{" + System.getProperty("line.separator") + " \"id\": 1," + System.getProperty("line.separator") + " \"name\": \"A green door\"," + System.getProperty("line.separator") + " \"price\": 12.50," + System.getProperty("line.separator") + " \"tags\": [\"home\", \"green\"]" + System.getProperty("line.separator") + "}"), headersToIgnore) ); // when mockServerClient .clear( request() .withBody(jsonSchemaBodyOne) ); // then assertThat( mockServerClient.retrieveExistingExpectations(null), arrayContaining( expectation( request() .withBody(jsonSchemaBodyTwo) ) .thenRespond( response() .withBody("some_body2") ) ) ); // - in http assertEquals( response() .withHeader(HttpHeaders.CONTENT_TYPE, TEXT_PLAIN) .withStatusCode(HttpStatusCode.OK_200.code()) .withBody("some_body2"), makeRequest( request() .withBody("{" + System.getProperty("line.separator") + " \"id\": 1," + System.getProperty("line.separator") + " \"name\": \"A green door\"," + System.getProperty("line.separator") + " \"price\": 12.50," + System.getProperty("line.separator") + " \"tags\": [\"home\", \"green\"]" + System.getProperty("line.separator") + "}"), headersToIgnore) ); // - in https assertEquals( response() .withHeader(HttpHeaders.CONTENT_TYPE, TEXT_PLAIN) .withStatusCode(HttpStatusCode.OK_200.code()) .withBody("some_body2"), makeRequest( request() .withSecure(true) .withBody("{" + System.getProperty("line.separator") + " \"id\": 1," + System.getProperty("line.separator") + " \"name\": \"A green door\"," + System.getProperty("line.separator") + " \"price\": 12.50," + System.getProperty("line.separator") + " \"tags\": [\"home\", \"green\"]" + System.getProperty("line.separator") + "}"), headersToIgnore) ); } @Test public void shouldClearExpectationsWithParameterBody() { // given mockServerClient .when( request() .withBody(params(param("bodyParameterNameOne", "bodyParameterValueOne"))) ) .respond( response() .withBody("some_body1") ); mockServerClient .when( request() .withBody(params(param("bodyParameterNameTwo", "bodyParameterValueTwo"))) ) .respond( response() .withBody("some_body2") ); // then assertEquals( response() .withHeader(HttpHeaders.CONTENT_TYPE, TEXT_PLAIN) .withStatusCode(HttpStatusCode.OK_200.code()) .withBody("some_body1"), makeRequest( request() .withBody(params(param("bodyParameterName.*", "bodyParameterValue.*"))), headersToIgnore) ); // when mockServerClient .clear( request() .withBody(params(param("bodyParameterNameOne", "bodyParameterValueOne"))) ); // then assertThat( mockServerClient.retrieveExistingExpectations(null), arrayContaining( expectation( request() .withBody(params(param("bodyParameterNameTwo", "bodyParameterValueTwo"))) ) .thenRespond( response() .withBody("some_body2") ) ) ); // - in http assertEquals( response() .withHeader(HttpHeaders.CONTENT_TYPE, TEXT_PLAIN) .withStatusCode(HttpStatusCode.OK_200.code()) .withBody("some_body2"), makeRequest( request() .withBody(params(param("bodyParameterName.*", "bodyParameterValue.*"))), headersToIgnore) ); // - in https assertEquals( response() .withHeader(HttpHeaders.CONTENT_TYPE, TEXT_PLAIN) .withStatusCode(HttpStatusCode.OK_200.code()) .withBody("some_body2"), makeRequest( request() .withSecure(true) .withBody(params(param("bodyParameterName.*", "bodyParameterValue.*"))), headersToIgnore) ); } @Test public void shouldReset() { // given mockServerClient .when( request() .withPath(calculatePath("some_path1")) ) .respond( response() .withBody("some_body1") ); mockServerClient .when( request() .withPath(calculatePath("some_path2")) ) .respond( response() .withBody("some_body2") ); // when mockServerClient.reset(); // then // - in http assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()), makeRequest( request() .withPath(calculatePath("some_path1")), headersToIgnore) ); assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()), makeRequest( request() .withPath(calculatePath("some_path2")), headersToIgnore) ); // - in https assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()), makeRequest( request() .withSecure(true) .withPath(calculatePath("some_path1")), headersToIgnore) ); assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()), makeRequest( request() .withSecure(true) .withPath(calculatePath("some_path2")), headersToIgnore) ); } @Test public void shouldEnsureThatRequestDelaysDoNotAffectOtherRequests() throws Exception { mockServerClient .when( request("/slow") ) .respond( response("super slow") .withDelay(new Delay(TimeUnit.SECONDS, 8)) ); mockServerClient .when( request("/fast") ) .respond( response("quite fast") ); ExecutorService executorService = Executors.newFixedThreadPool(2); Future<Long> slowFuture = executorService.submit(new Callable<Long>() { @Override public Long call() throws Exception { long start = System.currentTimeMillis(); makeRequest(request("/slow")); return System.currentTimeMillis() - start; } }); // Let fast request come to the server slightly after slow request Uninterruptibles.sleepUninterruptibly(1, TimeUnit.SECONDS); Future<Long> fastFuture = executorService.submit(new Callable<Long>() { @Override public Long call() throws Exception { long start = System.currentTimeMillis(); makeRequest(request("/fast")); return System.currentTimeMillis() - start; } }); Long slowRequestElapsedMillis = slowFuture.get(); Long fastRequestElapsedMillis = fastFuture.get(); assertThat("Slow request takes less than expected", slowRequestElapsedMillis, is(greaterThan(7 * 1000L))); assertThat("Fast request takes longer than expected", fastRequestElapsedMillis, is(lessThan(3 * 1000L))); } protected void verifyRequestMatches(HttpRequest[] httpRequests, HttpRequest... httpRequestMatchers) { if (httpRequests.length != httpRequestMatchers.length) { throw new AssertionError("Number of request matchers does not match number of requests, expected:<" + httpRequestMatchers.length + "> but was:<" + httpRequests.length + ">"); } else { for (int i = 0; i < httpRequestMatchers.length; i++) { if (!new HttpRequestMatcher(httpRequestMatchers[i]).matches(httpRequests[i])) { throw new AssertionError("Request does not match request matcher, expected:<" + httpRequestMatchers[i] + "> but was:<" + httpRequests[i] + ">"); } } } } protected HttpResponse makeRequest(HttpRequest httpRequest) { return makeRequest(httpRequest, Collections.<String>emptySet()); } protected HttpResponse makeRequest(HttpRequest httpRequest, Collection<String> headersToIgnore) { int attemptsRemaining = 10; while (attemptsRemaining > 0) { try { boolean isSsl = httpRequest.isSecure() != null && httpRequest.isSecure(); int port = (isSsl ? getMockServerSecurePort() : getMockServerPort()); HttpResponse httpResponse = httpClient.sendRequest(outboundRequest("localhost", port, servletContext, httpRequest)); List<Header> headers = new ArrayList<Header>(); for (Header header : httpResponse.getHeaders()) { if (!headersToIgnore.contains(header.getName().getValue().toLowerCase())) { if (header.getName().getValue().equalsIgnoreCase(HttpHeaders.CONTENT_TYPE)) { // this fixes Tomcat which removes the space between // media type and charset in the Content-Type header for (NottableString value : new ArrayList<NottableString>(header.getValues())) { header.getValues().clear(); header.addValues(value.getValue().replace(";charset", "; charset")); } } headers.add(header); } } httpResponse.withHeaders(headers); return httpResponse; } catch (SocketConnectionException caught) { attemptsRemaining--; logger.info("Retrying connection to mock server, attempts remaining: " + attemptsRemaining); try { TimeUnit.MILLISECONDS.sleep(500); } catch (InterruptedException e) { // do nothing } } } throw new RuntimeException("Failed to send request:" + System.getProperty("line.separator") + httpRequest); } }
chrisjm/mockserver
mockserver-integration-testing/src/main/java/org/mockserver/integration/server/AbstractClientServerIntegrationTest.java
926
package testbed.review; import java.util.Arrays; import java.util.Comparator; /** * Έστω ένας δισδιάστατος πίνακας που περιέχει τα στοιχεία άφιξης και αναχώρησης αυτοκινήτων * σε μορφή arr[][] = {{1012, 1136}, {1317, 1417}, {1015, 1020}}. Αναπτύξτε μία εφαρμογή που * διαβάζει να εκτυπώνει τον μέγιστο αριθμό αυτοκινήτων που είναι σταθμευμένα το ίδιο χρονικό διάστημα. * Ως παράδειγμα στον παραπάνω πίνακα το αποτέλεσμα θα πρέπει να είναι: 2. Το 1ο αυτοκίνητο αφίχθη στις * 10:12 και αναχώρησε στις 11:36, το 3ο αυτοκίνητο αφίχθη στις 10:15 και αναχώρησε στις 10:20. * Επομένως, το 1ο και το 3ο αυτοκίνητο ήταν παρόντα το ίδιο χρονικό διάστημα. * * Hint. Με βάση τον αρχικό πίνακα, δημιουργήστε ένα δυσδιάστατο πίνακα που σε κάθε γραμμή θα περιέχει * δύο πεδία int. Στο πρώτο πεδίο θα εισάγεται η ώρα άφιξης ή αναχώρησης από τον αρχικό πίνακα και στο * 2ο πεδίο θα εισάγεται ο αριθμός 1 αν πρόκειται για άφιξη και 0 αν πρόκειται για αναχώρηση. * Ταξινομήστε τον πίνακα σε αύξουσα σειρά με βάση την ώρα. Στη συνέχεια υπολογίστε το μέγιστο αριθμό * αυτοκινήτων που είναι σταθμευμένα το ίδιο χρονικό διάστημα με ένα πέρασμα του πίνακα. */ public class MaxCarsApp { public static void main(String[] args) { int[][] arr = new int[][] {{1012, 1136}, {1022, 1126}, {1317, 1417}, {1015, 1025}}; int[][] transformed; transformed = transformArray(arr); sortByTime(transformed); for (int[] row : transformed) { System.out.print(row[0] + " "); System.out.println(row[1]); } //System.out.println("max: " + getMaxOnes(transformed)); System.out.println("Max Concurrent Cars: " + getMaxConcurrentCars(transformed)); } /** * Transforms the initial 2D array with one-row departures and arrivals * into a x2 2D array; one row for departure and one row for arrival. * The second column involves 1 for arrival and 0 for departure. * * @param arr the source array * @return the transformed array */ public static int[][] transformArray(int[][] arr) { int[][] transformed = new int[arr.length*2][2]; for (int i = 0; i < arr.length; i++) { for (int j = 0; j < arr[i].length; j++) { transformed[i*2][0] = arr[i][0]; transformed[i*2][1] = 1; transformed[i*2+1][0] = arr[i][1]; transformed[i*2+1][1] = 0; } } return transformed; } /** * Sorts the transformed array in ascending order * by the time of car arrival or departure. It uses * a Comparator for sorting the first column. * * @param arr the source transformed array */ public static void sortByTime(int[][] arr) { Arrays.sort(arr, Comparator.comparing((int[] a) -> a[0])); } /** * It counts the max 1s (arrivals) that are continuous. * * @param arr the transformed array * @return the max number of arrivals in a time * interval */ public static int getMaxOnes(int[][] arr) { int times = 0; int maxTimes = 0; int i = 0; while (i < arr.length) { times = 0; while ((i < arr.length) && (arr[i++][1] == 1)) { times++; } if (times > maxTimes) maxTimes = times; } return maxTimes; } /** * Returns the number of cars that are parked * during the same time interval. * * @param arr the source array with arrivals and departures * @return the concurrently parked cars */ public static int getMaxConcurrentCars(int[][] arr) { int count = 0; int maxCount = 0; for (int[] ints : arr) { if (ints[1] == 1){ count++; if (count > maxCount) maxCount = count; } else count--; } return maxCount; } }
a8anassis/cf-structured-review
MaxCarsApp.java
927
package com.example.eshop3; import androidx.room.Database; import androidx.room.RoomDatabase; import com.example.eshop3.Pelates; /* Δημιουργία της βάσης μου με τις κλάσεις Pelates, Proionta , Pwliseis , έκδοση δεν έχει τόσο θέμα βάζει ο καθένας ότι θελει αριθμό., exportScehma το έβαλα false για να μην βγάζει ένα warning πλεον H βάση μου κάνει extends την RoomDatabase που έχουμε εισάγει στο build grandle(Module :app) Επισης περιέχει τo myDao */ @Database(entities = {Pelates.class, Proionta.class, Pwliseis.class}, version = 1, exportSchema = false) public abstract class MyAppDatabase extends RoomDatabase { public abstract MyDao myDao(); }
EfthimisKele/E_Shop
app/src/main/java/com/example/eshop3/MyAppDatabase.java
928
package org.mockserver.integration.server; import com.fasterxml.jackson.databind.ObjectMapper; import com.google.common.net.MediaType; import com.google.common.util.concurrent.Uninterruptibles; import org.apache.commons.io.IOUtils; import org.junit.Test; import org.mockserver.echo.http.EchoServer; import org.mockserver.logging.MockServerLogger; import org.mockserver.matchers.MatchType; import org.mockserver.matchers.TimeToLive; import org.mockserver.mock.Expectation; import org.mockserver.model.*; import org.mockserver.serialization.ExpectationSerializer; import org.mockserver.serialization.HttpRequestSerializer; import org.mockserver.serialization.JsonArraySerializer; import org.mockserver.serialization.ObjectMapperFactory; import org.mockserver.serialization.java.ExpectationToJavaSerializer; import org.mockserver.verify.VerificationTimes; import java.io.IOException; import java.nio.charset.StandardCharsets; import java.util.*; import java.util.concurrent.*; import static io.netty.handler.codec.http.HttpHeaderNames.*; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.*; import static org.hamcrest.core.Is.is; import static org.hamcrest.core.StringStartsWith.startsWith; import static org.hamcrest.number.OrderingComparison.greaterThan; import static org.junit.Assert.assertEquals; import static org.junit.Assert.fail; import static org.mockserver.character.Character.NEW_LINE; import static org.mockserver.matchers.Times.exactly; import static org.mockserver.model.BinaryBody.binary; import static org.mockserver.model.Cookie.cookie; import static org.mockserver.model.Header.header; import static org.mockserver.model.HttpForward.forward; import static org.mockserver.model.HttpRequest.request; import static org.mockserver.model.HttpResponse.notFoundResponse; import static org.mockserver.model.HttpResponse.response; import static org.mockserver.model.HttpStatusCode.NOT_FOUND_404; import static org.mockserver.model.HttpStatusCode.OK_200; import static org.mockserver.model.JsonBody.json; import static org.mockserver.model.JsonSchemaBody.jsonSchema; import static org.mockserver.model.NottableString.not; import static org.mockserver.model.NottableString.string; import static org.mockserver.model.Parameter.param; import static org.mockserver.model.ParameterBody.params; import static org.mockserver.model.RegexBody.regex; import static org.mockserver.model.StringBody.exact; import static org.mockserver.model.StringBody.subString; import static org.mockserver.model.XPathBody.xpath; import static org.mockserver.model.XmlBody.xml; import static org.mockserver.model.XmlSchemaBody.xmlSchema; import static org.mockserver.model.XmlSchemaBody.xmlSchemaFromResource; /** * @author jamesdbloom */ public abstract class AbstractExtendedMockingIntegrationTest extends AbstractBasicMockingIntegrationTest { @Test public void shouldReturnResponseForRequestInSsl() { // when mockServerClient.when(request().withSecure(true)).respond(response().withBody("some_body")); // then // - in http assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()) .withReasonPhrase(HttpStatusCode.NOT_FOUND_404.reasonPhrase()), makeRequest( request() .withPath(calculatePath("")), headersToIgnore) ); // - in https assertEquals( response() .withStatusCode(OK_200.code()) .withReasonPhrase(OK_200.reasonPhrase()) .withBody("some_body"), makeRequest( request() .withSecure(true) .withPath(calculatePath("")), headersToIgnore) ); } @Test public void shouldReturnResponseForRequestNotInSsl() { // when mockServerClient.when(request().withSecure(false)).respond(response().withBody("some_body")); // then // - in http assertEquals( response() .withStatusCode(OK_200.code()) .withReasonPhrase(OK_200.reasonPhrase()) .withBody("some_body"), makeRequest( request() .withPath(calculatePath("")), headersToIgnore) ); // - in https assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()) .withReasonPhrase(HttpStatusCode.NOT_FOUND_404.reasonPhrase()), makeRequest( request() .withSecure(true) .withPath(calculatePath("")), headersToIgnore) ); } @Test public void shouldReturnResponseByMatchingPath() { // when mockServerClient .when( request() .withPath(calculatePath("some_path1")) ) .respond( response() .withBody("some_body1") ); mockServerClient .when( request() .withPath(calculatePath("some_path2")) ) .respond( response() .withBody("some_body2") ); // then // - in http assertEquals( response() .withStatusCode(OK_200.code()) .withReasonPhrase(OK_200.reasonPhrase()) .withBody("some_body2"), makeRequest( request() .withPath(calculatePath("some_path2")), headersToIgnore) ); assertEquals( response() .withStatusCode(OK_200.code()) .withReasonPhrase(OK_200.reasonPhrase()) .withBody("some_body1"), makeRequest( request() .withPath(calculatePath("some_path1")), headersToIgnore) ); // - in https assertEquals( response() .withStatusCode(OK_200.code()) .withReasonPhrase(OK_200.reasonPhrase()) .withBody("some_body2"), makeRequest( request() .withSecure(true) .withPath(calculatePath("some_path2")), headersToIgnore) ); assertEquals( response() .withStatusCode(OK_200.code()) .withReasonPhrase(OK_200.reasonPhrase()) .withBody("some_body1"), makeRequest( request() .withSecure(true) .withPath(calculatePath("some_path1")), headersToIgnore) ); } @Test public void shouldReturnResponseByMatchingPathExactTimes() { // when mockServerClient .when( request() .withPath(calculatePath("some_path")), exactly(2) ) .respond( response() .withBody("some_body") ); // then // - in http assertEquals( response() .withStatusCode(OK_200.code()) .withReasonPhrase(OK_200.reasonPhrase()) .withBody("some_body"), makeRequest( request() .withPath(calculatePath("some_path")), headersToIgnore) ); // - in https assertEquals( response() .withStatusCode(OK_200.code()) .withReasonPhrase(OK_200.reasonPhrase()) .withBody("some_body"), makeRequest( request() .withSecure(true) .withPath(calculatePath("some_path")), headersToIgnore) ); // - in http assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()) .withReasonPhrase(HttpStatusCode.NOT_FOUND_404.reasonPhrase()), makeRequest( request() .withPath(calculatePath("some_path")), headersToIgnore) ); // - in https assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()) .withReasonPhrase(HttpStatusCode.NOT_FOUND_404.reasonPhrase()), makeRequest( request() .withSecure(true) .withPath(calculatePath("some_path")), headersToIgnore) ); } @Test public void shouldReturnResponseWhenTimeToLiveHasNotExpired() { // when mockServerClient .when( request().withPath(calculatePath("some_path")), exactly(2), TimeToLive.exactly(TimeUnit.HOURS, 1L) ) .respond( response().withBody("some_body") ); // then // - in http assertEquals( response() .withStatusCode(OK_200.code()) .withReasonPhrase(OK_200.reasonPhrase()) .withBody("some_body"), makeRequest( request() .withPath(calculatePath("some_path")), headersToIgnore) ); // - in https assertEquals( response() .withStatusCode(OK_200.code()) .withReasonPhrase(OK_200.reasonPhrase()) .withBody("some_body"), makeRequest( request() .withSecure(true) .withPath(calculatePath("some_path")), headersToIgnore) ); // - in http assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()) .withReasonPhrase(HttpStatusCode.NOT_FOUND_404.reasonPhrase()), makeRequest( request() .withPath(calculatePath("some_path")), headersToIgnore) ); // - in https assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()) .withReasonPhrase(HttpStatusCode.NOT_FOUND_404.reasonPhrase()), makeRequest( request() .withSecure(true) .withPath(calculatePath("some_path")), headersToIgnore) ); } @Test public void shouldReturnMatchRequestWithBodyInUTF16() { // when String body = "我说中国话"; mockServerClient.when(request().withBody(body, StandardCharsets.UTF_16)).respond(response().withBody(body, StandardCharsets.UTF_8)); // then // - in http assertEquals( response() .withHeader(CONTENT_TYPE.toString(), MediaType.create("text", "plain").withCharset(StandardCharsets.UTF_8).toString()) .withStatusCode(OK_200.code()) .withReasonPhrase(OK_200.reasonPhrase()) .withBody(body), makeRequest( request() .withPath(calculatePath("")) .withBody(body, StandardCharsets.UTF_16), headersToIgnore) ); // - in https assertEquals( response() .withHeader(CONTENT_TYPE.toString(), MediaType.create("text", "plain").withCharset(StandardCharsets.UTF_8).toString()) .withStatusCode(OK_200.code()) .withReasonPhrase(OK_200.reasonPhrase()) .withBody(body), makeRequest( request() .withSecure(true) .withPath(calculatePath("")) .withBody(body, StandardCharsets.UTF_16), headersToIgnore) ); } @Test public void shouldReturnMatchRequestWithBodyInUTF8WithContentTypeHeader() { // when String body = "我说中国话"; mockServerClient .when( request() .withHeader(CONTENT_TYPE.toString(), MediaType.create("text", "plain").withCharset(StandardCharsets.UTF_8).toString()) .withBody(body) ) .respond( response() .withBody(body, StandardCharsets.UTF_8) ); // then // - in http assertEquals( response() .withHeader(CONTENT_TYPE.toString(), MediaType.create("text", "plain").withCharset(StandardCharsets.UTF_8).toString()) .withStatusCode(OK_200.code()) .withReasonPhrase(OK_200.reasonPhrase()) .withBody(body), makeRequest( request() .withHeader(CONTENT_TYPE.toString(), MediaType.create("text", "plain").withCharset(StandardCharsets.UTF_8).toString()) .withPath(calculatePath("")) .withBody(body), headersToIgnore) ); // - in https assertEquals( response() .withHeader(CONTENT_TYPE.toString(), MediaType.create("text", "plain").withCharset(StandardCharsets.UTF_8).toString()) .withStatusCode(OK_200.code()) .withReasonPhrase(OK_200.reasonPhrase()) .withBody(body), makeRequest( request() .withHeader(CONTENT_TYPE.toString(), MediaType.create("text", "plain").withCharset(StandardCharsets.UTF_8).toString()) .withSecure(true) .withPath(calculatePath("")) .withBody(body), headersToIgnore) ); } @Test public void shouldReturnResponseWithBodyInUTF16() { // when String body = "我说中国话"; mockServerClient.when(request()).respond(response().withBody(body, StandardCharsets.UTF_16)); // then // - in http assertEquals( response() .withHeader(CONTENT_TYPE.toString(), MediaType.create("text", "plain").withCharset(StandardCharsets.UTF_16).toString()) .withStatusCode(OK_200.code()) .withReasonPhrase(OK_200.reasonPhrase()) .withBody(body), makeRequest( request() .withPath(calculatePath("")), headersToIgnore) ); // - in https assertEquals( response() .withHeader(CONTENT_TYPE.toString(), MediaType.create("text", "plain").withCharset(StandardCharsets.UTF_16).toString()) .withStatusCode(OK_200.code()) .withReasonPhrase(OK_200.reasonPhrase()) .withBody(body), makeRequest( request() .withSecure(true) .withPath(calculatePath("")), headersToIgnore) ); } @Test public void shouldReturnResponseWithBodyInUTF8WithContentTypeHeader() { // when String body = "我说中国话"; mockServerClient .when( request() ) .respond( response() .withHeader(CONTENT_TYPE.toString(), MediaType.create("text", "plain").withCharset(StandardCharsets.UTF_8).toString()) .withBody(body) ); // then // - in http assertEquals( response() .withHeader(CONTENT_TYPE.toString(), MediaType.create("text", "plain").withCharset(StandardCharsets.UTF_8).toString()) .withStatusCode(OK_200.code()) .withReasonPhrase(OK_200.reasonPhrase()) .withBody(body), makeRequest( request() .withPath(calculatePath("")), headersToIgnore) ); // - in https assertEquals( response() .withHeader(CONTENT_TYPE.toString(), MediaType.create("text", "plain").withCharset(StandardCharsets.UTF_8).toString()) .withStatusCode(OK_200.code()) .withReasonPhrase(OK_200.reasonPhrase()) .withBody(body), makeRequest( request() .withSecure(true) .withPath(calculatePath("")), headersToIgnore) ); } @Test public void shouldReturnResponseByMatchingSubStringBody() { // when mockServerClient .when( request() .withBody( subString("random") ), exactly(2) ) .respond( response() .withBody("some_sub_string_body_response") ); // then // - in http assertEquals( response() .withStatusCode(OK_200.code()) .withReasonPhrase(OK_200.reasonPhrase()) .withBody("some_sub_string_body_response"), makeRequest( request() .withMethod("POST") .withPath(calculatePath("some_path")) .withBody("some_random_body"), headersToIgnore) ); // - in https assertEquals( response() .withStatusCode(OK_200.code()) .withReasonPhrase(OK_200.reasonPhrase()) .withBody("some_sub_string_body_response"), makeRequest( request() .withSecure(true) .withMethod("POST") .withPath(calculatePath("some_path")) .withBody("some_random_body"), headersToIgnore) ); } @Test public void shouldReturnResponseByMatchingBodyWithXPath() { // when mockServerClient.when(request().withBody(xpath("/bookstore/book[price>30]/price")), exactly(2)).respond(response().withBody("some_body")); // then // - in http assertEquals( response() .withStatusCode(OK_200.code()) .withReasonPhrase(OK_200.reasonPhrase()) .withBody("some_body"), makeRequest( request() .withPath(calculatePath("some_path")) .withMethod("POST") .withBody(new StringBody("" + "<?xml version=\"1.0\" encoding=\"ISO-8859-1\"?>" + NEW_LINE + "<bookstore>" + NEW_LINE + " <book category=\"COOKING\">" + NEW_LINE + " <title lang=\"en\">Everyday Italian</title>" + NEW_LINE + " <author>Giada De Laurentiis</author>" + NEW_LINE + " <year>2005</year>" + NEW_LINE + " <price>30.00</price>" + NEW_LINE + " </book>" + NEW_LINE + " <book category=\"CHILDREN\">" + NEW_LINE + " <title lang=\"en\">Harry Potter</title>" + NEW_LINE + " <author>J K. Rowling</author>" + NEW_LINE + " <year>2005</year>" + NEW_LINE + " <price>29.99</price>" + NEW_LINE + " </book>" + NEW_LINE + " <book category=\"WEB\">" + NEW_LINE + " <title lang=\"en\">Learning XML</title>" + NEW_LINE + " <author>Erik T. Ray</author>" + NEW_LINE + " <year>2003</year>" + NEW_LINE + " <price>31.95</price>" + NEW_LINE + " </book>" + NEW_LINE + "</bookstore>")), headersToIgnore) ); // - in https assertEquals( response() .withStatusCode(OK_200.code()) .withReasonPhrase(OK_200.reasonPhrase()) .withBody("some_body"), makeRequest( request() .withSecure(true) .withPath(calculatePath("some_path")) .withMethod("POST") .withBody(new StringBody("" + "<?xml version=\"1.0\" encoding=\"ISO-8859-1\"?>" + NEW_LINE + "<bookstore>" + NEW_LINE + " <book category=\"COOKING\">" + NEW_LINE + " <title lang=\"en\">Everyday Italian</title>" + NEW_LINE + " <author>Giada De Laurentiis</author>" + NEW_LINE + " <year>2005</year>" + NEW_LINE + " <price>30.00</price>" + NEW_LINE + " </book>" + NEW_LINE + " <book category=\"CHILDREN\">" + NEW_LINE + " <title lang=\"en\">Harry Potter</title>" + NEW_LINE + " <author>J K. Rowling</author>" + NEW_LINE + " <year>2005</year>" + NEW_LINE + " <price>29.99</price>" + NEW_LINE + " </book>" + NEW_LINE + " <book category=\"WEB\">" + NEW_LINE + " <title lang=\"en\">Learning XML</title>" + NEW_LINE + " <author>Erik T. Ray</author>" + NEW_LINE + " <year>2003</year>" + NEW_LINE + " <price>31.95</price>" + NEW_LINE + " </book>" + NEW_LINE + "</bookstore>")), headersToIgnore) ); } @Test public void shouldReturnResponseByMatchingBodyWithXml() { // when mockServerClient.when(request().withBody(xml("" + "<bookstore>" + NEW_LINE + " <book nationality=\"ITALIAN\" category=\"COOKING\"><title lang=\"en\">Everyday Italian</title><author>Giada De Laurentiis</author><year>2005</year><price>30.00</price></book>" + NEW_LINE + "</bookstore>")), exactly(2)).respond(response().withBody("some_body")); // then // - in http assertEquals( response() .withStatusCode(OK_200.code()) .withReasonPhrase(OK_200.reasonPhrase()) .withBody("some_body"), makeRequest( request() .withPath(calculatePath("some_path")) .withMethod("POST") .withBody(new StringBody("" + "<?xml version=\"1.0\" encoding=\"ISO-8859-1\"?>" + NEW_LINE + "<bookstore>" + NEW_LINE + " <book category=\"COOKING\" nationality=\"ITALIAN\">" + NEW_LINE + " <title lang=\"en\">Everyday Italian</title>" + NEW_LINE + " <author>Giada De Laurentiis</author>" + NEW_LINE + " <year>2005</year>" + NEW_LINE + " <price>30.00</price>" + NEW_LINE + " </book>" + NEW_LINE + "</bookstore>")), headersToIgnore) ); // - in https assertEquals( response() .withStatusCode(OK_200.code()) .withReasonPhrase(OK_200.reasonPhrase()) .withBody("some_body"), makeRequest( request() .withSecure(true) .withPath(calculatePath("some_path")) .withMethod("POST") .withBody(new StringBody("" + "<?xml version=\"1.0\" encoding=\"ISO-8859-1\"?>" + NEW_LINE + "<bookstore>" + NEW_LINE + " <book category=\"COOKING\" nationality=\"ITALIAN\">" + NEW_LINE + " <title lang=\"en\">Everyday Italian</title>" + NEW_LINE + " <author>Giada De Laurentiis</author>" + NEW_LINE + " <year>2005</year>" + NEW_LINE + " <price>30.00</price>" + NEW_LINE + " </book>" + NEW_LINE + "</bookstore>")), headersToIgnore) ); } @Test public void shouldReturnResponseByMatchingBodyWithJson() { // when mockServerClient .when( request() .withBody(json("{" + NEW_LINE + " \"id\": 1," + NEW_LINE + " \"name\": \"A green door\"," + NEW_LINE + " \"price\": 12.50," + NEW_LINE + " \"tags\": [\"home\", \"green\"]" + NEW_LINE + "}")), exactly(2) ) .respond( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withReasonPhrase(HttpStatusCode.ACCEPTED_202.reasonPhrase()) .withBody("some_body") ); // then // - in http assertEquals( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withReasonPhrase(HttpStatusCode.ACCEPTED_202.reasonPhrase()) .withBody("some_body"), makeRequest( request() .withPath(calculatePath("some_path")) .withMethod("POST") .withBody("{" + NEW_LINE + " \"id\": 1," + NEW_LINE + " \"extra ignored field\": \"some value\"," + NEW_LINE + " \"name\": \"A green door\"," + NEW_LINE + " \"price\": 12.50," + NEW_LINE + " \"tags\": [\"home\", \"green\"]" + NEW_LINE + "}"), headersToIgnore) ); // - in https assertEquals( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withReasonPhrase(HttpStatusCode.ACCEPTED_202.reasonPhrase()) .withBody("some_body"), makeRequest( request() .withSecure(true) .withPath(calculatePath("some_path")) .withMethod("POST") .withBody("{" + NEW_LINE + " \"id\": 1," + NEW_LINE + " \"extra ignored array\": [\"one\", \"two\"]," + NEW_LINE + " \"name\": \"A green door\"," + NEW_LINE + " \"price\": 12.50," + NEW_LINE + " \"tags\": [\"home\", \"green\"]" + NEW_LINE + "}"), headersToIgnore) ); } @Test public void shouldReturnResponseByMatchingBodyWithJsonWithCharsetUTF8() { // when mockServerClient .when( request() .withBody(json("{" + NEW_LINE + " \"ταυτότητα\": 1," + NEW_LINE + " \"όνομα\": \"μια πράσινη πόρτα\"," + NEW_LINE + " \"τιμή\": 12.50," + NEW_LINE + " \"ετικέτες\": [\"σπίτι\", \"πράσινος\"]" + NEW_LINE + "}", StandardCharsets.UTF_16, MatchType.ONLY_MATCHING_FIELDS)), exactly(2) ) .respond( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withReasonPhrase(HttpStatusCode.ACCEPTED_202.reasonPhrase()) .withBody("some_body") ); // then // - in http assertEquals( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withReasonPhrase(HttpStatusCode.ACCEPTED_202.reasonPhrase()) .withBody("some_body"), makeRequest( request() .withPath(calculatePath("some_path")) .withMethod("POST") .withBody(json("{" + NEW_LINE + " \"ταυτότητα\": 1," + NEW_LINE + " \"επιπλέον αγνοούνται τομέα\": \"κάποια αξία\"," + NEW_LINE + " \"όνομα\": \"μια πράσινη πόρτα\"," + NEW_LINE + " \"τιμή\": 12.50," + NEW_LINE + " \"ετικέτες\": [\"σπίτι\", \"πράσινος\"]" + NEW_LINE + "}", StandardCharsets.UTF_16, MatchType.ONLY_MATCHING_FIELDS)), headersToIgnore) ); // - in https assertEquals( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withReasonPhrase(HttpStatusCode.ACCEPTED_202.reasonPhrase()) .withBody("some_body"), makeRequest( request() .withSecure(true) .withPath(calculatePath("some_path")) .withMethod("POST") .withBody(json("{" + NEW_LINE + " \"ταυτότητα\": 1," + NEW_LINE + " \"επιπλέον αγνοούνται σειρά\": [\"ένας\", \"δυο\"]," + NEW_LINE + " \"όνομα\": \"μια πράσινη πόρτα\"," + NEW_LINE + " \"τιμή\": 12.50," + NEW_LINE + " \"ετικέτες\": [\"σπίτι\", \"πράσινος\"]" + NEW_LINE + "}", StandardCharsets.UTF_16, MatchType.ONLY_MATCHING_FIELDS)), headersToIgnore) ); } @Test public void shouldReturnResponseByMatchingBodyWithJsonWithContentTypeHeader() { // when mockServerClient .when( request() .withBody(json("{" + NEW_LINE + " \"ταυτότητα\": 1," + NEW_LINE + " \"όνομα\": \"μια πράσινη πόρτα\"," + NEW_LINE + " \"τιμή\": 12.50," + NEW_LINE + " \"ετικέτες\": [\"σπίτι\", \"πράσινος\"]" + NEW_LINE + "}", StandardCharsets.UTF_16, MatchType.ONLY_MATCHING_FIELDS)), exactly(2) ) .respond( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withReasonPhrase(HttpStatusCode.ACCEPTED_202.reasonPhrase()) .withBody("some_body") ); // then // - in http assertEquals( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withReasonPhrase(HttpStatusCode.ACCEPTED_202.reasonPhrase()) .withBody("some_body"), makeRequest( request() .withHeader(CONTENT_TYPE.toString(), MediaType.create("text", "plain").withCharset(StandardCharsets.UTF_16).toString()) .withPath(calculatePath("some_path")) .withMethod("POST") .withBody(json("{" + NEW_LINE + " \"ταυτότητα\": 1," + NEW_LINE + " \"επιπλέον αγνοούνται τομέα\": \"κάποια αξία\"," + NEW_LINE + " \"όνομα\": \"μια πράσινη πόρτα\"," + NEW_LINE + " \"τιμή\": 12.50," + NEW_LINE + " \"ετικέτες\": [\"σπίτι\", \"πράσινος\"]" + NEW_LINE + "}")), headersToIgnore) ); // - in https assertEquals( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withReasonPhrase(HttpStatusCode.ACCEPTED_202.reasonPhrase()) .withBody("some_body"), makeRequest( request() .withSecure(true) .withHeader(CONTENT_TYPE.toString(), MediaType.create("text", "plain").withCharset(StandardCharsets.UTF_16).toString()) .withPath(calculatePath("some_path")) .withMethod("POST") .withBody(json("{" + NEW_LINE + " \"ταυτότητα\": 1," + NEW_LINE + " \"επιπλέον αγνοούνται σειρά\": [\"ένας\", \"δυο\"]," + NEW_LINE + " \"όνομα\": \"μια πράσινη πόρτα\"," + NEW_LINE + " \"τιμή\": 12.50," + NEW_LINE + " \"ετικέτες\": [\"σπίτι\", \"πράσινος\"]" + NEW_LINE + "}")), headersToIgnore) ); } @Test public void shouldReturnResponseByMatchingBodyWithJsonWithMatchType() { // when mockServerClient .when( request() .withBody(json("{" + NEW_LINE + " \"id\": 1," + NEW_LINE + " \"name\": \"A green door\"," + NEW_LINE + " \"price\": 12.50," + NEW_LINE + " \"tags\": [\"home\", \"green\"]" + NEW_LINE + "}", MatchType.ONLY_MATCHING_FIELDS)), exactly(2) ) .respond( response() .withBody("some_body") ); // then // - in http assertEquals( response("some_body"), makeRequest( request() .withPath(calculatePath("some_path")) .withMethod("POST") .withBody("{" + NEW_LINE + " \"id\": 1," + NEW_LINE + " \"extra field\": \"some value\"," + NEW_LINE + " \"name\": \"A green door\"," + NEW_LINE + " \"price\": 12.50," + NEW_LINE + " \"tags\": [\"home\", \"green\"]" + NEW_LINE + "}"), headersToIgnore) ); // - in https assertEquals( response("some_body"), makeRequest( request() .withSecure(true) .withPath(calculatePath("some_path")) .withMethod("POST") .withBody("{" + NEW_LINE + " \"id\": 1," + NEW_LINE + " \"extra field\": \"some value\"," + NEW_LINE + " \"name\": \"A green door\"," + NEW_LINE + " \"price\": 12.50," + NEW_LINE + " \"tags\": [\"home\", \"green\"]" + NEW_LINE + "}"), headersToIgnore) ); } @Test public void shouldReturnResponseByMatchingBodyWithJsonSchema() { // when mockServerClient.when(request().withBody(jsonSchema("{" + NEW_LINE + " \"$schema\": \"http://json-schema.org/draft-04/schema#\"," + NEW_LINE + " \"title\": \"Product\"," + NEW_LINE + " \"description\": \"A product from Acme's catalog\"," + NEW_LINE + " \"type\": \"object\"," + NEW_LINE + " \"properties\": {" + NEW_LINE + " \"id\": {" + NEW_LINE + " \"description\": \"The unique identifier for a product\"," + NEW_LINE + " \"type\": \"integer\"" + NEW_LINE + " }," + NEW_LINE + " \"name\": {" + NEW_LINE + " \"description\": \"Name of the product\"," + NEW_LINE + " \"type\": \"string\"" + NEW_LINE + " }," + NEW_LINE + " \"price\": {" + NEW_LINE + " \"type\": \"number\"," + NEW_LINE + " \"minimum\": 0," + NEW_LINE + " \"exclusiveMinimum\": true" + NEW_LINE + " }," + NEW_LINE + " \"tags\": {" + NEW_LINE + " \"type\": \"array\"," + NEW_LINE + " \"items\": {" + NEW_LINE + " \"type\": \"string\"" + NEW_LINE + " }," + NEW_LINE + " \"minItems\": 1," + NEW_LINE + " \"uniqueItems\": true" + NEW_LINE + " }" + NEW_LINE + " }," + NEW_LINE + " \"required\": [\"id\", \"name\", \"price\"]" + NEW_LINE + "}")), exactly(2)).respond(response().withBody("some_body")); // then // - in http assertEquals( response() .withStatusCode(OK_200.code()) .withReasonPhrase(OK_200.reasonPhrase()) .withBody("some_body"), makeRequest( request() .withPath(calculatePath("some_path")) .withMethod("POST") .withBody("{" + NEW_LINE + " \"id\": 1," + NEW_LINE + " \"name\": \"A green door\"," + NEW_LINE + " \"price\": 12.50," + NEW_LINE + " \"tags\": [\"home\", \"green\"]" + NEW_LINE + "}"), headersToIgnore) ); // - in https assertEquals( response() .withStatusCode(OK_200.code()) .withReasonPhrase(OK_200.reasonPhrase()) .withBody("some_body"), makeRequest( request() .withSecure(true) .withPath(calculatePath("some_path")) .withMethod("POST") .withBody("{" + NEW_LINE + " \"id\": 1," + NEW_LINE + " \"name\": \"A green door\"," + NEW_LINE + " \"price\": 12.50," + NEW_LINE + " \"tags\": [\"home\", \"green\"]" + NEW_LINE + "}"), headersToIgnore) ); } @Test public void shouldReturnResponseByMatchingBodyWithXmlSchema() { // when mockServerClient.when(request() .withBody( xmlSchema("<?xml version=\"1.0\" encoding=\"UTF-8\"?>" + NEW_LINE + "<xs:schema xmlns:xs=\"http://www.w3.org/2001/XMLSchema\" elementFormDefault=\"qualified\" attributeFormDefault=\"unqualified\">" + NEW_LINE + " <!-- XML Schema Generated from XML Document on Wed Jun 28 2017 21:52:45 GMT+0100 (BST) -->" + NEW_LINE + " <!-- with XmlGrid.net Free Online Service http://xmlgrid.net -->" + NEW_LINE + " <xs:element name=\"notes\">" + NEW_LINE + " <xs:complexType>" + NEW_LINE + " <xs:sequence>" + NEW_LINE + " <xs:element name=\"note\" maxOccurs=\"unbounded\">" + NEW_LINE + " <xs:complexType>" + NEW_LINE + " <xs:sequence>" + NEW_LINE + " <xs:element name=\"to\" minOccurs=\"1\" maxOccurs=\"1\" type=\"xs:string\"></xs:element>" + NEW_LINE + " <xs:element name=\"from\" minOccurs=\"1\" maxOccurs=\"1\" type=\"xs:string\"></xs:element>" + NEW_LINE + " <xs:element name=\"heading\" minOccurs=\"1\" maxOccurs=\"1\" type=\"xs:string\"></xs:element>" + NEW_LINE + " <xs:element name=\"body\" minOccurs=\"1\" maxOccurs=\"1\" type=\"xs:string\"></xs:element>" + NEW_LINE + " </xs:sequence>" + NEW_LINE + " </xs:complexType>" + NEW_LINE + " </xs:element>" + NEW_LINE + " </xs:sequence>" + NEW_LINE + " </xs:complexType>" + NEW_LINE + " </xs:element>" + NEW_LINE + "</xs:schema>")), exactly(2) ) .respond( response() .withBody("some_body") ); // then // - in http assertEquals( response() .withStatusCode(NOT_FOUND_404.code()) .withReasonPhrase(NOT_FOUND_404.reasonPhrase()), makeRequest( request() .withMethod("POST") .withBody("<?xml version=\"1.0\" encoding=\"utf-8\"?>" + NEW_LINE + "<notes>" + NEW_LINE + " <note>" + NEW_LINE + " <to>Bob</to>" + NEW_LINE + " <heading>Reminder</heading>" + NEW_LINE + " <body>Buy Bread</body>" + NEW_LINE + " </note>" + NEW_LINE + " <note>" + NEW_LINE + " <to>Jack</to>" + NEW_LINE + " <from>Jill</from>" + NEW_LINE + " <heading>Reminder</heading>" + NEW_LINE + " <body>Wash Shirts</body>" + NEW_LINE + " </note>" + NEW_LINE + "</notes>"), headersToIgnore) ); assertEquals( response() .withStatusCode(OK_200.code()) .withReasonPhrase(OK_200.reasonPhrase()) .withBody("some_body"), makeRequest( request() .withPath(calculatePath("some_path")) .withMethod("POST") .withBody("<?xml version=\"1.0\" encoding=\"utf-8\"?>" + NEW_LINE + "<notes>" + NEW_LINE + " <note>" + NEW_LINE + " <to>Bob</to>" + NEW_LINE + " <from>Bill</from>" + NEW_LINE + " <heading>Reminder</heading>" + NEW_LINE + " <body>Buy Bread</body>" + NEW_LINE + " </note>" + NEW_LINE + " <note>" + NEW_LINE + " <to>Jack</to>" + NEW_LINE + " <from>Jill</from>" + NEW_LINE + " <heading>Reminder</heading>" + NEW_LINE + " <body>Wash Shirts</body>" + NEW_LINE + " </note>" + NEW_LINE + "</notes>"), headersToIgnore) ); // - in https assertEquals( response() .withStatusCode(OK_200.code()) .withReasonPhrase(OK_200.reasonPhrase()) .withBody("some_body"), makeRequest( request() .withSecure(true) .withPath(calculatePath("some_path")) .withMethod("POST") .withBody("<?xml version=\"1.0\" encoding=\"utf-8\"?>" + NEW_LINE + "<notes>" + NEW_LINE + " <note>" + NEW_LINE + " <to>Bob</to>" + NEW_LINE + " <from>Bill</from>" + NEW_LINE + " <heading>Reminder</heading>" + NEW_LINE + " <body>Buy Bread</body>" + NEW_LINE + " </note>" + NEW_LINE + " <note>" + NEW_LINE + " <to>Jack</to>" + NEW_LINE + " <from>Jill</from>" + NEW_LINE + " <heading>Reminder</heading>" + NEW_LINE + " <body>Wash Shirts</body>" + NEW_LINE + " </note>" + NEW_LINE + "</notes>"), headersToIgnore) ); } @Test public void shouldReturnResponseByMatchingBodyWithXmlSchemaByClasspath() { // when mockServerClient.when(request() .withBody( xmlSchemaFromResource("org/mockserver/model/testXmlSchema.xsd")), exactly(2) ) .respond( response() .withBody("some_body") ); // then // - in http assertEquals( response() .withStatusCode(NOT_FOUND_404.code()) .withReasonPhrase(NOT_FOUND_404.reasonPhrase()), makeRequest( request() .withMethod("POST") .withBody("<?xml version=\"1.0\" encoding=\"utf-8\"?>" + NEW_LINE + "<notes>" + NEW_LINE + " <note>" + NEW_LINE + " <to>Bob</to>" + NEW_LINE + " <heading>Reminder</heading>" + NEW_LINE + " <body>Buy Bread</body>" + NEW_LINE + " </note>" + NEW_LINE + " <note>" + NEW_LINE + " <to>Jack</to>" + NEW_LINE + " <from>Jill</from>" + NEW_LINE + " <heading>Reminder</heading>" + NEW_LINE + " <body>Wash Shirts</body>" + NEW_LINE + " </note>" + NEW_LINE + "</notes>"), headersToIgnore) ); assertEquals( response() .withStatusCode(OK_200.code()) .withReasonPhrase(OK_200.reasonPhrase()) .withBody("some_body"), makeRequest( request() .withPath(calculatePath("some_path")) .withMethod("POST") .withBody("<?xml version=\"1.0\" encoding=\"utf-8\"?>" + NEW_LINE + "<notes>" + NEW_LINE + " <note>" + NEW_LINE + " <to>Bob</to>" + NEW_LINE + " <from>Bill</from>" + NEW_LINE + " <heading>Reminder</heading>" + NEW_LINE + " <body>Buy Bread</body>" + NEW_LINE + " </note>" + NEW_LINE + " <note>" + NEW_LINE + " <to>Jack</to>" + NEW_LINE + " <from>Jill</from>" + NEW_LINE + " <heading>Reminder</heading>" + NEW_LINE + " <body>Wash Shirts</body>" + NEW_LINE + " </note>" + NEW_LINE + "</notes>"), headersToIgnore) ); // - in https assertEquals( response() .withStatusCode(OK_200.code()) .withReasonPhrase(OK_200.reasonPhrase()) .withBody("some_body"), makeRequest( request() .withSecure(true) .withPath(calculatePath("some_path")) .withMethod("POST") .withBody("<?xml version=\"1.0\" encoding=\"utf-8\"?>" + NEW_LINE + "<notes>" + NEW_LINE + " <note>" + NEW_LINE + " <to>Bob</to>" + NEW_LINE + " <from>Bill</from>" + NEW_LINE + " <heading>Reminder</heading>" + NEW_LINE + " <body>Buy Bread</body>" + NEW_LINE + " </note>" + NEW_LINE + " <note>" + NEW_LINE + " <to>Jack</to>" + NEW_LINE + " <from>Jill</from>" + NEW_LINE + " <heading>Reminder</heading>" + NEW_LINE + " <body>Wash Shirts</body>" + NEW_LINE + " </note>" + NEW_LINE + "</notes>"), headersToIgnore) ); } @Test public void shouldReturnPDFResponseByMatchingPath() throws IOException { // when byte[] pdfBytes = IOUtils.toByteArray(getClass().getClassLoader().getResourceAsStream("test.pdf")); mockServerClient .when( request() .withPath(calculatePath("ws/rest/user/[0-9]+/document/[0-9]+\\.pdf")) ) .respond( response() .withStatusCode(OK_200.code()) .withReasonPhrase(OK_200.reasonPhrase()) .withHeaders( header(CONTENT_TYPE.toString(), MediaType.PDF.toString()), header(CONTENT_DISPOSITION.toString(), "form-data; name=\"test.pdf\"; filename=\"test.pdf\""), header(CACHE_CONTROL.toString(), "must-revalidate, post-check=0, pre-check=0") ) .withBody(binary(pdfBytes)) ); // then // - in http assertEquals( response() .withStatusCode(OK_200.code()) .withReasonPhrase(OK_200.reasonPhrase()) .withHeaders( header(CONTENT_DISPOSITION.toString(), "form-data; name=\"test.pdf\"; filename=\"test.pdf\""), header(CACHE_CONTROL.toString(), "must-revalidate, post-check=0, pre-check=0"), header(CONTENT_TYPE.toString(), MediaType.PDF.toString()) ) .withBody(binary(pdfBytes)), makeRequest( request() .withPath(calculatePath("ws/rest/user/1/document/2.pdf")) .withMethod("GET"), headersToIgnore) ); // - in https assertEquals( response() .withStatusCode(OK_200.code()) .withReasonPhrase(OK_200.reasonPhrase()) .withHeaders( header(CONTENT_DISPOSITION.toString(), "form-data; name=\"test.pdf\"; filename=\"test.pdf\""), header(CACHE_CONTROL.toString(), "must-revalidate, post-check=0, pre-check=0"), header(CONTENT_TYPE.toString(), MediaType.PDF.toString()) ) .withBody(binary(pdfBytes)), makeRequest( request() .withSecure(true) .withPath(calculatePath("ws/rest/user/1/document/2.pdf")) .withMethod("GET"), headersToIgnore) ); } @Test public void shouldReturnPNGResponseByMatchingPath() throws IOException { // when byte[] pngBytes = IOUtils.toByteArray(getClass().getClassLoader().getResourceAsStream("test.png")); mockServerClient .when( request() .withPath(calculatePath("ws/rest/user/[0-9]+/icon/[0-9]+\\.png")) ) .respond( response() .withStatusCode(OK_200.code()) .withReasonPhrase(OK_200.reasonPhrase()) .withHeaders( header(CONTENT_TYPE.toString(), MediaType.PNG.toString()), header(CONTENT_DISPOSITION.toString(), "form-data; name=\"test.png\"; filename=\"test.png\"") ) .withBody(binary(pngBytes)) ); // then // - in http assertEquals( response() .withStatusCode(OK_200.code()) .withReasonPhrase(OK_200.reasonPhrase()) .withHeaders( header(CONTENT_DISPOSITION.toString(), "form-data; name=\"test.png\"; filename=\"test.png\""), header(CONTENT_TYPE.toString(), MediaType.PNG.toString()) ) .withBody(binary(pngBytes)), makeRequest( request() .withPath(calculatePath("ws/rest/user/1/icon/1.png")) .withMethod("GET"), headersToIgnore) ); // - in https assertEquals( response() .withStatusCode(OK_200.code()) .withReasonPhrase(OK_200.reasonPhrase()) .withHeaders( header(CONTENT_DISPOSITION.toString(), "form-data; name=\"test.png\"; filename=\"test.png\""), header(CONTENT_TYPE.toString(), MediaType.PNG.toString()) ) .withBody(binary(pngBytes)), makeRequest( request() .withSecure(true) .withPath(calculatePath("ws/rest/user/1/icon/1.png")) .withMethod("GET"), headersToIgnore) ); } @Test public void shouldReturnPDFResponseByMatchingBinaryPDFBody() throws IOException { // when byte[] pdfBytes = IOUtils.toByteArray(getClass().getClassLoader().getResourceAsStream("test.pdf")); mockServerClient .when( request().withBody(binary(pdfBytes)) ) .respond( response() .withStatusCode(OK_200.code()) .withReasonPhrase(OK_200.reasonPhrase()) .withHeaders( header(CONTENT_TYPE.toString(), MediaType.PDF.toString()), header(CONTENT_DISPOSITION.toString(), "form-data; name=\"test.pdf\"; filename=\"test.pdf\""), header(CACHE_CONTROL.toString(), "must-revalidate, post-check=0, pre-check=0") ) .withBody(binary(pdfBytes)) ); // then // - in http assertEquals( response() .withStatusCode(OK_200.code()) .withReasonPhrase(OK_200.reasonPhrase()) .withHeaders( header(CONTENT_DISPOSITION.toString(), "form-data; name=\"test.pdf\"; filename=\"test.pdf\""), header(CACHE_CONTROL.toString(), "must-revalidate, post-check=0, pre-check=0"), header(CONTENT_TYPE.toString(), MediaType.PDF.toString()) ) .withBody(binary(pdfBytes)), makeRequest( request() .withPath(calculatePath("ws/rest/user/1/document/2.pdf")) .withBody(binary(pdfBytes)) .withMethod("POST"), headersToIgnore) ); // - in https assertEquals( response() .withStatusCode(OK_200.code()) .withReasonPhrase(OK_200.reasonPhrase()) .withHeaders( header(CONTENT_DISPOSITION.toString(), "form-data; name=\"test.pdf\"; filename=\"test.pdf\""), header(CACHE_CONTROL.toString(), "must-revalidate, post-check=0, pre-check=0"), header(CONTENT_TYPE.toString(), MediaType.PDF.toString()) ) .withBody(binary(pdfBytes)), makeRequest( request() .withSecure(true) .withPath(calculatePath("ws/rest/user/1/document/2.pdf")) .withBody(binary(pdfBytes)) .withMethod("POST"), headersToIgnore) ); } @Test public void shouldReturnPNGResponseByMatchingBinaryPNGBody() throws IOException { // when byte[] pngBytes = IOUtils.toByteArray(getClass().getClassLoader().getResourceAsStream("test.png")); mockServerClient .when( request().withBody(binary(pngBytes)) ) .respond( response() .withStatusCode(OK_200.code()) .withReasonPhrase(OK_200.reasonPhrase()) .withHeaders( header(CONTENT_TYPE.toString(), MediaType.PNG.toString()), header(CONTENT_DISPOSITION.toString(), "form-data; name=\"test.png\"; filename=\"test.png\"") ) .withBody(binary(pngBytes)) ); // then // - in http assertEquals( response() .withStatusCode(OK_200.code()) .withReasonPhrase(OK_200.reasonPhrase()) .withHeaders( header(CONTENT_DISPOSITION.toString(), "form-data; name=\"test.png\"; filename=\"test.png\""), header(CONTENT_TYPE.toString(), MediaType.PNG.toString()) ) .withBody(binary(pngBytes)), makeRequest( request() .withPath(calculatePath("ws/rest/user/1/icon/1.png")) .withBody(binary(pngBytes)) .withMethod("POST"), headersToIgnore) ); // - in https assertEquals( response() .withStatusCode(OK_200.code()) .withReasonPhrase(OK_200.reasonPhrase()) .withHeaders( header(CONTENT_DISPOSITION.toString(), "form-data; name=\"test.png\"; filename=\"test.png\""), header(CONTENT_TYPE.toString(), MediaType.PNG.toString()) ) .withBody(binary(pngBytes)), makeRequest( request() .withSecure(true) .withPath(calculatePath("ws/rest/user/1/icon/1.png")) .withBody(binary(pngBytes)) .withMethod("POST"), headersToIgnore) ); } @Test public void shouldReturnResponseByNotMatchingPathWithNotOperator() { // when mockServerClient .when( request() .withPath(not(calculatePath("some_path"))) ) .respond( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withReasonPhrase(HttpStatusCode.ACCEPTED_202.reasonPhrase()) .withBody("some_body_response") ); // then // - in http assertEquals( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withReasonPhrase(HttpStatusCode.ACCEPTED_202.reasonPhrase()) .withBody("some_body_response"), makeRequest( request() .withPath(calculatePath("some_other_path")), headersToIgnore) ); // - in https assertEquals( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withReasonPhrase(HttpStatusCode.ACCEPTED_202.reasonPhrase()) .withBody("some_body_response"), makeRequest( request() .withPath(calculatePath("some_other_path")), headersToIgnore) ); } @Test public void shouldReturnResponseByNotMatchingMethodWithNotOperator() { // when mockServerClient .when( request() .withMethod(not("GET")) ) .respond( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withReasonPhrase(HttpStatusCode.ACCEPTED_202.reasonPhrase()) .withBody("some_body_response") ); // then // - in http assertEquals( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withReasonPhrase(HttpStatusCode.ACCEPTED_202.reasonPhrase()) .withBody("some_body_response"), makeRequest( request() .withMethod("POST"), headersToIgnore) ); // - in https assertEquals( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withReasonPhrase(HttpStatusCode.ACCEPTED_202.reasonPhrase()) .withBody("some_body_response"), makeRequest( request() .withMethod("POST"), headersToIgnore) ); } @Test public void shouldReturnResponseByMatchingPathAndMethodAndBody() { // when mockServerClient .when( request() .withMethod("POST") .withPath(calculatePath("some_pathRequest")) .withBody("some_bodyRequest") ) .respond( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withReasonPhrase(HttpStatusCode.ACCEPTED_202.reasonPhrase()) .withBody("some_body_response") .withHeaders(header("headerNameResponse", "headerValueResponse")) ); // then // - in http assertEquals( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withReasonPhrase(HttpStatusCode.ACCEPTED_202.reasonPhrase()) .withBody("some_body_response") .withHeaders( header("headerNameResponse", "headerValueResponse") ), makeRequest( request() .withMethod("POST") .withPath(calculatePath("some_pathRequest")) .withQueryStringParameters( param("queryStringParameterOneName", "queryStringParameterOneValue"), param("queryStringParameterTwoName", "queryStringParameterTwoValue") ) .withBody("some_bodyRequest") .withHeaders(header("headerNameRequest", "headerValueRequest")) .withCookies(cookie("cookieNameRequest", "cookieValueRequest")), headersToIgnore) ); // - in https assertEquals( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withReasonPhrase(HttpStatusCode.ACCEPTED_202.reasonPhrase()) .withBody("some_body_response") .withHeaders( header("headerNameResponse", "headerValueResponse") ), makeRequest( request() .withMethod("POST") .withSecure(true) .withPath(calculatePath("some_pathRequest")) .withQueryStringParameters( param("queryStringParameterOneName", "queryStringParameterOneValue"), param("queryStringParameterTwoName", "queryStringParameterTwoValue") ) .withBody("some_bodyRequest") .withHeaders(header("headerNameRequest", "headerValueRequest")) .withCookies(cookie("cookieNameRequest", "cookieValueRequest")), headersToIgnore) ); } @Test public void shouldReturnResponseByMatchingPathAndMethodAndQueryStringParameters() { // when mockServerClient .when( request() .withMethod("GET") .withPath(calculatePath("some_pathRequest")) .withQueryStringParameters( param("queryStringParameterOneName", "queryStringParameterOneValue"), param("queryStringParameterTwoName", "queryStringParameterTwoValue") ) ) .respond( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withReasonPhrase(HttpStatusCode.ACCEPTED_202.reasonPhrase()) .withBody("some_body_response") .withCookies(cookie("cookieNameResponse", "cookieValueResponse")) ); // then // - in http assertEquals( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withReasonPhrase(HttpStatusCode.ACCEPTED_202.reasonPhrase()) .withBody("some_body_response") .withCookies(cookie("cookieNameResponse", "cookieValueResponse")) .withHeaders( header(SET_COOKIE.toString(), "cookieNameResponse=cookieValueResponse") ), makeRequest( request() .withMethod("GET") .withPath(calculatePath("some_pathRequest")) .withQueryStringParameters( param("queryStringParameterOneName", "queryStringParameterOneValue"), param("queryStringParameterTwoName", "queryStringParameterTwoValue") ) .withHeaders(header("headerNameRequest", "headerValueRequest")) .withCookies(cookie("cookieNameRequest", "cookieValueRequest")), headersToIgnore) ); // - in https assertEquals( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withReasonPhrase(HttpStatusCode.ACCEPTED_202.reasonPhrase()) .withBody("some_body_response") .withCookies(cookie("cookieNameResponse", "cookieValueResponse")) .withHeaders( header(SET_COOKIE.toString(), "cookieNameResponse=cookieValueResponse") ), makeRequest( request() .withMethod("GET") .withSecure(true) .withPath(calculatePath("some_pathRequest")) .withQueryStringParameters( param("queryStringParameterOneName", "queryStringParameterOneValue"), param("queryStringParameterTwoName", "queryStringParameterTwoValue") ) .withHeaders(header("headerNameRequest", "headerValueRequest")) .withCookies(cookie("cookieNameRequest", "cookieValueRequest")), headersToIgnore) ); } @Test public void shouldReturnResponseByMatchingPathAndMethodAndHeaders() { // when mockServerClient .when( request() .withMethod("GET") .withPath(calculatePath("some_pathRequest")) .withHeaders( header("requestHeaderNameOne", "requestHeaderValueOne_One", "requestHeaderValueOne_Two"), header("requestHeaderNameTwo", "requestHeaderValueTwo") ) ) .respond( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withReasonPhrase(HttpStatusCode.ACCEPTED_202.reasonPhrase()) .withBody("some_body_response") .withCookies(cookie("cookieNameResponse", "cookieValueResponse")) ); // then // - in http assertEquals( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withReasonPhrase(HttpStatusCode.ACCEPTED_202.reasonPhrase()) .withBody("some_body_response") .withCookies(cookie("cookieNameResponse", "cookieValueResponse")) .withHeaders( header(SET_COOKIE.toString(), "cookieNameResponse=cookieValueResponse") ), makeRequest( request() .withMethod("GET") .withPath(calculatePath("some_pathRequest")) .withHeaders( header("requestHeaderNameOne", "requestHeaderValueOne_One", "requestHeaderValueOne_Two"), header("requestHeaderNameTwo", "requestHeaderValueTwo") ) .withCookies(cookie("cookieNameRequest", "cookieValueRequest")), headersToIgnore) ); // - in https assertEquals( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withReasonPhrase(HttpStatusCode.ACCEPTED_202.reasonPhrase()) .withBody("some_body_response") .withCookies(cookie("cookieNameResponse", "cookieValueResponse")) .withHeaders( header(SET_COOKIE.toString(), "cookieNameResponse=cookieValueResponse") ), makeRequest( request() .withMethod("GET") .withSecure(true) .withPath(calculatePath("some_pathRequest")) .withHeaders( header("requestHeaderNameOne", "requestHeaderValueOne_One", "requestHeaderValueOne_Two"), header("requestHeaderNameTwo", "requestHeaderValueTwo") ) .withCookies(cookie("cookieNameRequest", "cookieValueRequest")), headersToIgnore) ); } @Test public void shouldReturnResponseByMatchingPathAndMethodAndCookies() { // when mockServerClient .when( request() .withMethod("GET") .withPath(calculatePath("some_pathRequest")) .withCookies( cookie("requestCookieNameOne", "requestCookieValueOne"), cookie("requestCookieNameTwo", "requestCookieValueTwo") ) ) .respond( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withReasonPhrase(HttpStatusCode.ACCEPTED_202.reasonPhrase()) .withBody("some_body_response") .withCookies( cookie("responseCookieNameOne", "responseCookieValueOne"), cookie("responseCookieNameTwo", "responseCookieValueTwo") ) ); // then // - in http - cookie objects assertEquals( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withReasonPhrase(HttpStatusCode.ACCEPTED_202.reasonPhrase()) .withBody("some_body_response") .withCookies( cookie("responseCookieNameOne", "responseCookieValueOne"), cookie("responseCookieNameTwo", "responseCookieValueTwo") ) .withHeaders( header(SET_COOKIE.toString(), "responseCookieNameOne=responseCookieValueOne", "responseCookieNameTwo=responseCookieValueTwo") ), makeRequest( request() .withMethod("GET") .withPath(calculatePath("some_pathRequest")) .withHeaders( header("headerNameRequest", "headerValueRequest"), header(CONTENT_TYPE.toString(), MediaType.create("text", "plain").toString()) ) .withCookies( cookie("requestCookieNameOne", "requestCookieValueOne"), cookie("requestCookieNameTwo", "requestCookieValueTwo") ), headersToIgnore) ); // - in http - cookie header assertEquals( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withReasonPhrase(HttpStatusCode.ACCEPTED_202.reasonPhrase()) .withBody("some_body_response") .withCookies( cookie("responseCookieNameOne", "responseCookieValueOne"), cookie("responseCookieNameTwo", "responseCookieValueTwo") ) .withHeaders( header(SET_COOKIE.toString(), "responseCookieNameOne=responseCookieValueOne", "responseCookieNameTwo=responseCookieValueTwo") ), makeRequest( request() .withMethod("GET") .withPath(calculatePath("some_pathRequest")) .withHeaders( header("headerNameRequest", "headerValueRequest"), header("Cookie", "requestCookieNameOne=requestCookieValueOne; requestCookieNameTwo=requestCookieValueTwo") ), headersToIgnore) ); // - in https - cookie objects assertEquals( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withReasonPhrase(HttpStatusCode.ACCEPTED_202.reasonPhrase()) .withBody("some_body_response") .withCookies( cookie("responseCookieNameOne", "responseCookieValueOne"), cookie("responseCookieNameTwo", "responseCookieValueTwo") ) .withHeaders( header(SET_COOKIE.toString(), "responseCookieNameOne=responseCookieValueOne", "responseCookieNameTwo=responseCookieValueTwo") ), makeRequest( request() .withMethod("GET") .withSecure(true) .withPath(calculatePath("some_pathRequest")) .withHeaders( header("headerNameRequest", "headerValueRequest") ) .withCookies( cookie("requestCookieNameOne", "requestCookieValueOne"), cookie("requestCookieNameTwo", "requestCookieValueTwo") ), headersToIgnore) ); // - in https - cookie header assertEquals( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withReasonPhrase(HttpStatusCode.ACCEPTED_202.reasonPhrase()) .withBody("some_body_response") .withCookies( cookie("responseCookieNameOne", "responseCookieValueOne"), cookie("responseCookieNameTwo", "responseCookieValueTwo") ) .withHeaders( header(SET_COOKIE.toString(), "responseCookieNameOne=responseCookieValueOne", "responseCookieNameTwo=responseCookieValueTwo") ), makeRequest( request() .withMethod("GET") .withSecure(true) .withPath(calculatePath("some_pathRequest")) .withHeaders( header("headerNameRequest", "headerValueRequest"), header("Cookie", "requestCookieNameOne=requestCookieValueOne; requestCookieNameTwo=requestCookieValueTwo") ), headersToIgnore) ); } @Test public void shouldReturnResponseByMatchingPathAndMethodAndQueryStringParametersAndBodyParameters() { // when mockServerClient .when( request() .withMethod("POST") .withPath(calculatePath("some_pathRequest")) .withQueryStringParameters( param("queryStringParameterOneName", "queryStringParameterOneValueOne", "queryStringParameterOneValueTwo"), param("queryStringParameterTwoName", "queryStringParameterTwoValue") ) .withBody(params(param("bodyParameterName", "bodyParameterValue"))) ) .respond( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withReasonPhrase(HttpStatusCode.ACCEPTED_202.reasonPhrase()) .withBody("some_body") ); // then // - in http - url query string assertEquals( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withReasonPhrase(HttpStatusCode.ACCEPTED_202.reasonPhrase()) .withBody("some_body"), makeRequest( request() .withMethod("POST") .withPath(calculatePath("some_pathRequest")) .withQueryStringParameters( param("queryStringParameterOneName", "queryStringParameterOneValueOne", "queryStringParameterOneValueTwo"), param("queryStringParameterTwoName", "queryStringParameterTwoValue") ) .withBody(params(param("bodyParameterName", "bodyParameterValue"))), headersToIgnore) ); // - in https - query string parameter objects assertEquals( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withReasonPhrase(HttpStatusCode.ACCEPTED_202.reasonPhrase()) .withBody("some_body"), makeRequest( request() .withSecure(true) .withMethod("POST") .withPath(calculatePath("some_pathRequest")) .withQueryStringParameters( param("queryStringParameterOneName", "queryStringParameterOneValueOne", "queryStringParameterOneValueTwo"), param("queryStringParameterTwoName", "queryStringParameterTwoValue") ) .withBody(params(param("bodyParameterName", "bodyParameterValue"))), headersToIgnore) ); } @Test public void shouldReturnResponseByMatchingPathAndMethodAndQueryStringParametersAndBody() { // when mockServerClient .when( request() .withMethod("POST") .withPath(calculatePath("some_pathRequest")) .withQueryStringParameters( param("queryStringParameterOneName", "queryStringParameterOneValueOne", "queryStringParameterOneValueTwo"), param("queryStringParameterTwoName", "queryStringParameterTwoValue") ) .withBody("some_bodyRequest") ) .respond( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withReasonPhrase(HttpStatusCode.ACCEPTED_202.reasonPhrase()) .withBody("some_body_response") .withHeaders(header("headerNameResponse", "headerValueResponse")) .withCookies(cookie("cookieNameResponse", "cookieValueResponse")) ); // then // - in http - url query string assertEquals( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withReasonPhrase(HttpStatusCode.ACCEPTED_202.reasonPhrase()) .withBody("some_body_response") .withCookies(cookie("cookieNameResponse", "cookieValueResponse")) .withHeaders( header("headerNameResponse", "headerValueResponse"), header(SET_COOKIE.toString(), "cookieNameResponse=cookieValueResponse") ), makeRequest( request() .withMethod("POST") .withPath(calculatePath("some_pathRequest")) .withQueryStringParameters( param("queryStringParameterOneName", "queryStringParameterOneValueOne", "queryStringParameterOneValueTwo"), param("queryStringParameterTwoName", "queryStringParameterTwoValue") ) .withBody("some_bodyRequest") .withHeaders(header("headerNameRequest", "headerValueRequest")) .withCookies(cookie("cookieNameRequest", "cookieValueRequest")), headersToIgnore) ); // - in http - query string parameter objects assertEquals( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withReasonPhrase(HttpStatusCode.ACCEPTED_202.reasonPhrase()) .withBody("some_body_response") .withCookies(cookie("cookieNameResponse", "cookieValueResponse")) .withHeaders( header("headerNameResponse", "headerValueResponse"), header(SET_COOKIE.toString(), "cookieNameResponse=cookieValueResponse") ), makeRequest( request() .withMethod("POST") .withPath(calculatePath("some_pathRequest")) .withQueryStringParameters( param("queryStringParameterOneName", "queryStringParameterOneValueOne", "queryStringParameterOneValueTwo"), param("queryStringParameterTwoName", "queryStringParameterTwoValue") ) .withBody("some_bodyRequest") .withHeaders(header("headerNameRequest", "headerValueRequest")) .withCookies(cookie("cookieNameRequest", "cookieValueRequest")), headersToIgnore) ); // - in https - url string and query string parameter objects assertEquals( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withReasonPhrase(HttpStatusCode.ACCEPTED_202.reasonPhrase()) .withBody("some_body_response") .withCookies(cookie("cookieNameResponse", "cookieValueResponse")) .withHeaders( header("headerNameResponse", "headerValueResponse"), header(SET_COOKIE.toString(), "cookieNameResponse=cookieValueResponse") ), makeRequest( request() .withMethod("POST") .withPath(calculatePath("some_pathRequest")) .withQueryStringParameters( param("queryStringParameterOneName", "queryStringParameterOneValueOne", "queryStringParameterOneValueTwo"), param("queryStringParameterTwoName", "queryStringParameterTwoValue") ) .withBody("some_bodyRequest") .withHeaders(header("headerNameRequest", "headerValueRequest")) .withCookies(cookie("cookieNameRequest", "cookieValueRequest")), headersToIgnore) ); } @Test public void shouldReturnResponseByMatchingPathAndMethodAndBodyParameters() { // when mockServerClient .when( request() .withMethod("POST") .withPath(calculatePath("some_pathRequest")) .withBody(params( param("bodyParameterOneName", "Parameter One Value One", "Parameter One Value Two"), param("bodyParameterTwoName", "Parameter Two") )) ) .respond( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withReasonPhrase(HttpStatusCode.ACCEPTED_202.reasonPhrase()) .withBody("some_body_response") .withHeaders(header("headerNameResponse", "headerValueResponse")) .withCookies(cookie("cookieNameResponse", "cookieValueResponse")) ); // then // - in http - body string assertEquals( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withReasonPhrase(HttpStatusCode.ACCEPTED_202.reasonPhrase()) .withBody("some_body_response") .withCookies(cookie("cookieNameResponse", "cookieValueResponse")) .withHeaders( header("headerNameResponse", "headerValueResponse"), header(SET_COOKIE.toString(), "cookieNameResponse=cookieValueResponse") ), makeRequest( request() .withMethod("POST") .withPath(calculatePath("some_pathRequest")) .withBody(new StringBody("bodyParameterOneName=Parameter+One+Value+One" + "&bodyParameterOneName=Parameter+One+Value+Two" + "&bodyParameterTwoName=Parameter+Two")) .withHeaders(header("headerNameRequest", "headerValueRequest")) .withCookies(cookie("cookieNameRequest", "cookieValueRequest")), headersToIgnore) ); // - in http - body parameter objects assertEquals( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withReasonPhrase(HttpStatusCode.ACCEPTED_202.reasonPhrase()) .withBody("some_body_response") .withCookies(cookie("cookieNameResponse", "cookieValueResponse")) .withHeaders( header("headerNameResponse", "headerValueResponse"), header(SET_COOKIE.toString(), "cookieNameResponse=cookieValueResponse") ), makeRequest( request() .withMethod("POST") .withPath(calculatePath("some_pathRequest")) .withBody(params( param("bodyParameterOneName", "Parameter One Value One", "Parameter One Value Two"), param("bodyParameterTwoName", "Parameter Two") )) .withHeaders(header("headerNameRequest", "headerValueRequest")) .withCookies(cookie("cookieNameRequest", "cookieValueRequest")), headersToIgnore) ); // - in https - url string and query string parameter objects assertEquals( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withReasonPhrase(HttpStatusCode.ACCEPTED_202.reasonPhrase()) .withBody("some_body_response") .withCookies(cookie("cookieNameResponse", "cookieValueResponse")) .withHeaders( header("headerNameResponse", "headerValueResponse"), header(SET_COOKIE.toString(), "cookieNameResponse=cookieValueResponse") ), makeRequest( request() .withMethod("POST") .withPath(calculatePath("some_pathRequest")) .withBody(params( param("bodyParameterOneName", "Parameter One Value One", "Parameter One Value Two"), param("bodyParameterTwoName", "Parameter Two") )) .withHeaders(header("headerNameRequest", "headerValueRequest")) .withCookies(cookie("cookieNameRequest", "cookieValueRequest")), headersToIgnore) ); } @Test public void shouldReturnResponseByMatchingPathAndMethodAndParametersAndHeadersAndCookies() { // when mockServerClient .when( request() .withMethod("PUT") .withPath(calculatePath("some_pathRequest")) .withBody(new StringBody("bodyParameterOneName=Parameter+One+Value+One" + "&bodyParameterOneName=Parameter+One+Value+Two" + "&bodyParameterTwoName=Parameter+Two")) .withHeaders(header("headerNameRequest", "headerValueRequest")) .withCookies(cookie("cookieNameRequest", "cookieValueRequest")) ) .respond( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withReasonPhrase(HttpStatusCode.ACCEPTED_202.reasonPhrase()) .withBody("some_body_response") .withHeaders(header("headerNameResponse", "headerValueResponse")) .withCookies(cookie("cookieNameResponse", "cookieValueResponse")) ); // then // - in http - body string assertEquals( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withReasonPhrase(HttpStatusCode.ACCEPTED_202.reasonPhrase()) .withBody("some_body_response") .withCookies(cookie("cookieNameResponse", "cookieValueResponse")) .withHeaders( header("headerNameResponse", "headerValueResponse"), header(SET_COOKIE.toString(), "cookieNameResponse=cookieValueResponse") ), makeRequest( request() .withMethod("PUT") .withPath(calculatePath("some_pathRequest")) .withBody(new StringBody("bodyParameterOneName=Parameter+One+Value+One" + "&bodyParameterOneName=Parameter+One+Value+Two" + "&bodyParameterTwoName=Parameter+Two")) .withHeaders( header("headerNameRequest", "headerValueRequest"), header("Cookie", "cookieNameRequest=cookieValueRequest") ), headersToIgnore) ); // - in http - body parameter objects assertEquals( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withReasonPhrase(HttpStatusCode.ACCEPTED_202.reasonPhrase()) .withBody("some_body_response") .withCookies(cookie("cookieNameResponse", "cookieValueResponse")) .withHeaders( header("headerNameResponse", "headerValueResponse"), header(SET_COOKIE.toString(), "cookieNameResponse=cookieValueResponse") ), makeRequest( request() .withMethod("PUT") .withPath(calculatePath("some_pathRequest")) .withBody(params( param("bodyParameterOneName", "Parameter One Value One", "Parameter One Value Two"), param("bodyParameterTwoName", "Parameter Two") )) .withHeaders(header("headerNameRequest", "headerValueRequest")) .withCookies(cookie("cookieNameRequest", "cookieValueRequest")), headersToIgnore) ); } @Test public void shouldReturnResponseByNotMatchingBodyParameterWithNotOperatorForNameAndValue() { // when mockServerClient .when( request() .withMethod("POST") .withPath(calculatePath("some_pathRequest")) .withBody(params( param(not("bodyParameterOneName"), not("Parameter One Value One"), not("Parameter One Value Two")), param("bodyParameterTwoName", "Parameter Two") )) ) .respond( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withReasonPhrase(HttpStatusCode.ACCEPTED_202.reasonPhrase()) .withBody("some_body_response") ); // then // wrong query string parameter name assertEquals( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withReasonPhrase(HttpStatusCode.ACCEPTED_202.reasonPhrase()) .withBody("some_body_response"), makeRequest( request() .withMethod("POST") .withPath(calculatePath("some_pathRequest")) .withBody(params( param("OTHERBodyParameterOneName", "Parameter One Value One", "Parameter One Value Two"), param("bodyParameterTwoName", "Parameter Two") )) .withHeaders(header("headerNameRequest", "headerValueRequest")) .withCookies(cookie("cookieNameRequest", "cookieValueRequest")), headersToIgnore) ); // wrong query string parameter name assertEquals( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withReasonPhrase(HttpStatusCode.ACCEPTED_202.reasonPhrase()) .withBody("some_body_response"), makeRequest( request() .withMethod("POST") .withPath(calculatePath("some_pathRequest")) .withBody(new StringBody("OTHERBodyParameterOneName=Parameter+One+Value+One" + "&OTHERBodyParameterOneName=Parameter+One+Value+Two" + "&bodyParameterTwoName=Parameter+Two")) .withHeaders(header("headerNameRequest", "headerValueRequest")) .withCookies(cookie("cookieNameRequest", "cookieValueRequest")), headersToIgnore) ); // wrong query string parameter value assertEquals( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withReasonPhrase(HttpStatusCode.ACCEPTED_202.reasonPhrase()) .withBody("some_body_response"), makeRequest( request() .withMethod("POST") .withPath(calculatePath("some_pathRequest")) .withBody(params( param("bodyParameterOneName", "OTHER Parameter One Value One", "OTHER Parameter One Value Two"), param("bodyParameterTwoName", "Parameter Two") )) .withHeaders(header("headerNameRequest", "headerValueRequest")) .withCookies(cookie("cookieNameRequest", "cookieValueRequest")), headersToIgnore) ); // wrong query string parameter value assertEquals( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withReasonPhrase(HttpStatusCode.ACCEPTED_202.reasonPhrase()) .withBody("some_body_response"), makeRequest( request() .withMethod("POST") .withPath(calculatePath("some_pathRequest")) .withBody(new StringBody("bodyParameterOneName=OTHER Parameter+One+Value+One" + "&bodyParameterOneName=OTHER Parameter+One+Value+Two" + "&bodyParameterTwoName=Parameter+Two")) .withHeaders(header("headerNameRequest", "headerValueRequest")) .withCookies(cookie("cookieNameRequest", "cookieValueRequest")), headersToIgnore) ); } @Test public void shouldReturnResponseByNotMatchingBodyParameterWithNotOperatorForName() { // when mockServerClient .when( request() .withMethod("POST") .withPath(calculatePath("some_pathRequest")) .withBody(params( param(not("bodyParameterOneName"), string("Parameter One Value One"), string("Parameter One Value Two")), param("bodyParameterTwoName", "Parameter Two") )) ) .respond( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withReasonPhrase(HttpStatusCode.ACCEPTED_202.reasonPhrase()) .withBody("some_body_response") ); // then // wrong query string parameter name assertEquals( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withReasonPhrase(HttpStatusCode.ACCEPTED_202.reasonPhrase()) .withBody("some_body_response"), makeRequest( request() .withMethod("POST") .withPath(calculatePath("some_pathRequest")) .withBody(params( param("OTHERBodyParameterOneName", "Parameter One Value One", "Parameter One Value Two"), param("bodyParameterTwoName", "Parameter Two") )) .withHeaders(header("headerNameRequest", "headerValueRequest")) .withCookies(cookie("cookieNameRequest", "cookieValueRequest")), headersToIgnore) ); // wrong query string parameter name assertEquals( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withReasonPhrase(HttpStatusCode.ACCEPTED_202.reasonPhrase()) .withBody("some_body_response"), makeRequest( request() .withMethod("POST") .withPath(calculatePath("some_pathRequest")) .withBody(new StringBody("OTHERBodyParameterOneName=Parameter+One+Value+One" + "&OTHERBodyParameterOneName=Parameter+One+Value+Two" + "&bodyParameterTwoName=Parameter+Two")) .withHeaders(header("headerNameRequest", "headerValueRequest")) .withCookies(cookie("cookieNameRequest", "cookieValueRequest")), headersToIgnore) ); } @Test public void shouldReturnResponseByNotMatchingBodyParameterWithNotOperatorForValue() { // when mockServerClient .when( request() .withMethod("POST") .withPath(calculatePath("some_pathRequest")) .withBody(params( param(string("bodyParameterOneName"), not("Parameter One Value One"), not("Parameter One Value Two")), param("bodyParameterTwoName", "Parameter Two") )) ) .respond( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withReasonPhrase(HttpStatusCode.ACCEPTED_202.reasonPhrase()) .withBody("some_body_response") ); // then // wrong query string parameter value assertEquals( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withReasonPhrase(HttpStatusCode.ACCEPTED_202.reasonPhrase()) .withBody("some_body_response"), makeRequest( request() .withMethod("POST") .withPath(calculatePath("some_pathRequest")) .withBody(params( param("bodyParameterOneName", "OTHER Parameter One Value One", "OTHER Parameter One Value Two"), param("bodyParameterTwoName", "Parameter Two") )) .withHeaders(header("headerNameRequest", "headerValueRequest")) .withCookies(cookie("cookieNameRequest", "cookieValueRequest")), headersToIgnore) ); // wrong query string parameter value assertEquals( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withReasonPhrase(HttpStatusCode.ACCEPTED_202.reasonPhrase()) .withBody("some_body_response"), makeRequest( request() .withMethod("POST") .withPath(calculatePath("some_pathRequest")) .withBody(new StringBody("bodyParameterOneName=OTHER Parameter+One+Value+One" + "&bodyParameterOneName=OTHER Parameter+One+Value+Two" + "&bodyParameterTwoName=Parameter+Two")) .withHeaders(header("headerNameRequest", "headerValueRequest")) .withCookies(cookie("cookieNameRequest", "cookieValueRequest")), headersToIgnore) ); } @Test public void shouldReturnResponseByNotMatchingQueryStringParameterWithNotOperatorForNameAndValue() { // when mockServerClient .when( request() .withMethod("POST") .withPath(calculatePath("some_pathRequest")) .withQueryStringParameters( param(not("queryStringParameterOneName"), not("Parameter One Value One"), not("Parameter One Value Two")), param("queryStringParameterTwoName", "Parameter Two") ) ) .respond( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withReasonPhrase(HttpStatusCode.ACCEPTED_202.reasonPhrase()) .withBody("some_body_response") ); // then // wrong query string parameter name assertEquals( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withReasonPhrase(HttpStatusCode.ACCEPTED_202.reasonPhrase()) .withBody("some_body_response"), makeRequest( request() .withMethod("POST") .withPath(calculatePath("some_pathRequest")) .withQueryStringParameters( param("OTHERQueryStringParameterOneName", "Parameter One Value One", "Parameter One Value Two"), param("queryStringParameterTwoName", "Parameter Two") ), headersToIgnore) ); // wrong query string parameter value assertEquals( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withReasonPhrase(HttpStatusCode.ACCEPTED_202.reasonPhrase()) .withBody("some_body_response"), makeRequest( request() .withMethod("POST") .withPath(calculatePath("some_pathRequest")) .withQueryStringParameters( param("queryStringParameterOneName", "OTHER Parameter One Value One", "OTHER Parameter One Value Two"), param("queryStringParameterTwoName", "Parameter Two") ), headersToIgnore) ); } @Test public void shouldReturnResponseByNotMatchingQueryStringParameterWithNotOperatorForName() { // when mockServerClient .when( request() .withMethod("POST") .withPath(calculatePath("some_pathRequest")) .withQueryStringParameters( param(not("queryStringParameterOneName"), string("Parameter One Value One"), string("Parameter One Value Two")), param("queryStringParameterTwoName", "Parameter Two") ) ) .respond( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withReasonPhrase(HttpStatusCode.ACCEPTED_202.reasonPhrase()) .withBody("some_body_response") ); // then // wrong query string parameter name assertEquals( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withReasonPhrase(HttpStatusCode.ACCEPTED_202.reasonPhrase()) .withBody("some_body_response"), makeRequest( request() .withMethod("POST") .withPath(calculatePath("some_pathRequest")) .withQueryStringParameters( param("OTHERQueryStringParameterOneName", "Parameter One Value One", "Parameter One Value Two"), param("queryStringParameterTwoName", "Parameter Two") ), headersToIgnore) ); } @Test public void shouldReturnResponseByNotMatchingQueryStringParameterWithNotOperatorForValue() { // when mockServerClient .when( request() .withMethod("POST") .withPath(calculatePath("some_pathRequest")) .withQueryStringParameters( param(string("queryStringParameterOneName"), not("Parameter One Value One"), not("Parameter One Value Two")), param("queryStringParameterTwoName", "Parameter Two") ) ) .respond( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withReasonPhrase(HttpStatusCode.ACCEPTED_202.reasonPhrase()) .withBody("some_body_response") ); // then // wrong query string parameter value assertEquals( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withReasonPhrase(HttpStatusCode.ACCEPTED_202.reasonPhrase()) .withBody("some_body_response"), makeRequest( request() .withMethod("POST") .withPath(calculatePath("some_pathRequest")) .withQueryStringParameters( param("queryStringParameterOneName", "OTHER Parameter One Value One", "OTHER Parameter One Value Two"), param("queryStringParameterTwoName", "Parameter Two") ), headersToIgnore) ); } @Test public void shouldReturnResponseByNotMatchingCookieWithNotOperatorForNameAndValue() { // when mockServerClient .when( request() .withMethod("GET") .withPath(calculatePath("some_pathRequest")) .withCookies( cookie(not("requestCookieNameOne"), not("requestCookieValueOne")), cookie("requestCookieNameTwo", "requestCookieValueTwo") ) ) .respond( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withReasonPhrase(HttpStatusCode.ACCEPTED_202.reasonPhrase()) .withBody("some_body_response") ); // then // wrong query string cookie name assertEquals( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withReasonPhrase(HttpStatusCode.ACCEPTED_202.reasonPhrase()) .withBody("some_body_response"), makeRequest( request() .withMethod("GET") .withPath(calculatePath("some_pathRequest")) .withCookies( cookie("OTHERrequestCookieNameOne", "requestCookieValueOne"), cookie("requestCookieNameTwo", "requestCookieValueTwo") ), headersToIgnore) ); // wrong query string cookie value assertEquals( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withReasonPhrase(HttpStatusCode.ACCEPTED_202.reasonPhrase()) .withBody("some_body_response"), makeRequest( request() .withMethod("GET") .withPath(calculatePath("some_pathRequest")) .withCookies( cookie("requestCookieNameOne", "OTHERrequestCookieValueOne"), cookie("requestCookieNameTwo", "requestCookieValueTwo") ), headersToIgnore) ); } @Test public void shouldReturnResponseByNotMatchingCookieWithNotOperatorForName() { // when mockServerClient .when( request() .withMethod("GET") .withPath(calculatePath("some_pathRequest")) .withCookies( cookie(not("requestCookieNameOne"), string("requestCookieValueOne")), cookie("requestCookieNameTwo", "requestCookieValueTwo") ) ) .respond( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withReasonPhrase(HttpStatusCode.ACCEPTED_202.reasonPhrase()) .withBody("some_body_response") ); // then // wrong query string cookie name assertEquals( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withReasonPhrase(HttpStatusCode.ACCEPTED_202.reasonPhrase()) .withBody("some_body_response"), makeRequest( request() .withMethod("GET") .withPath(calculatePath("some_pathRequest")) .withCookies( cookie("OTHERrequestCookieNameOne", "requestCookieValueOne"), cookie("requestCookieNameTwo", "requestCookieValueTwo") ), headersToIgnore) ); } @Test public void shouldReturnResponseByNotMatchingCookieWithNotOperatorForValue() { // when mockServerClient .when( request() .withMethod("GET") .withPath(calculatePath("some_pathRequest")) .withCookies( cookie(string("requestCookieNameOne"), not("requestCookieValueOne")), cookie("requestCookieNameTwo", "requestCookieValueTwo") ) ) .respond( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withReasonPhrase(HttpStatusCode.ACCEPTED_202.reasonPhrase()) .withBody("some_body_response") ); // then // wrong query string cookie value assertEquals( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withReasonPhrase(HttpStatusCode.ACCEPTED_202.reasonPhrase()) .withBody("some_body_response"), makeRequest( request() .withMethod("GET") .withPath(calculatePath("some_pathRequest")) .withCookies( cookie("requestCookieNameOne", "OTHERrequestCookieValueOne"), cookie("requestCookieNameTwo", "requestCookieValueTwo") ), headersToIgnore) ); } @Test public void shouldReturnResponseByNotMatchingHeaderWithNotOperatorForNameAndValue() { // when mockServerClient .when( request() .withMethod("GET") .withPath(calculatePath("some_pathRequest")) .withHeaders( header(not("requestHeaderNameOne"), not("requestHeaderValueOne")), header("requestHeaderNameTwo", "requestHeaderValueTwo") ) ) .respond( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withReasonPhrase(HttpStatusCode.ACCEPTED_202.reasonPhrase()) .withBody("some_body_response") ); // then // wrong query string header name assertEquals( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withReasonPhrase(HttpStatusCode.ACCEPTED_202.reasonPhrase()) .withBody("some_body_response"), makeRequest( request() .withMethod("GET") .withPath(calculatePath("some_pathRequest")) .withHeaders( header("OTHERrequestHeaderNameOne", "requestHeaderValueOne"), header("requestHeaderNameTwo", "requestHeaderValueTwo") ), headersToIgnore) ); // wrong query string header value assertEquals( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withReasonPhrase(HttpStatusCode.ACCEPTED_202.reasonPhrase()) .withBody("some_body_response"), makeRequest( request() .withMethod("GET") .withPath(calculatePath("some_pathRequest")) .withHeaders( header("requestHeaderNameOne", "OTHERrequestHeaderValueOne"), header("requestHeaderNameTwo", "requestHeaderValueTwo") ), headersToIgnore) ); } @Test public void shouldReturnResponseByNotMatchingHeaderWithNotOperatorForName() { // when mockServerClient .when( request() .withMethod("GET") .withPath(calculatePath("some_pathRequest")) .withHeaders( header(not("requestHeaderNameOne"), string("requestHeaderValueOne")), header("requestHeaderNameTwo", "requestHeaderValueTwo") ) ) .respond( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withReasonPhrase(HttpStatusCode.ACCEPTED_202.reasonPhrase()) .withBody("some_body_response") ); // then // wrong query string header name assertEquals( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withReasonPhrase(HttpStatusCode.ACCEPTED_202.reasonPhrase()) .withBody("some_body_response"), makeRequest( request() .withMethod("GET") .withPath(calculatePath("some_pathRequest")) .withHeaders( header("OTHERrequestHeaderNameOne", "requestHeaderValueOne"), header("requestHeaderNameTwo", "requestHeaderValueTwo") ), headersToIgnore) ); } @Test public void shouldReturnResponseByNotMatchingHeaderWithNotOperatorForValue() { // when mockServerClient .when( request() .withMethod("GET") .withPath(calculatePath("some_pathRequest")) .withHeaders( header(string("requestHeaderNameOne"), not("requestHeaderValueOne")), header("requestHeaderNameTwo", "requestHeaderValueTwo") ) ) .respond( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withReasonPhrase(HttpStatusCode.ACCEPTED_202.reasonPhrase()) .withBody("some_body_response") ); // then // wrong query string header value assertEquals( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withReasonPhrase(HttpStatusCode.ACCEPTED_202.reasonPhrase()) .withBody("some_body_response"), makeRequest( request() .withMethod("GET") .withPath(calculatePath("some_pathRequest")) .withHeaders( header("requestHeaderNameOne", "OTHERrequestHeaderValueOne"), header("requestHeaderNameTwo", "requestHeaderValueTwo") ), headersToIgnore) ); } @Test public void shouldNotReturnResponseForWhenTimeToLiveExpired() { // when mockServerClient .when( request().withPath(calculatePath("some_path")), exactly(2), TimeToLive.exactly(TimeUnit.SECONDS, 3L) ) .respond( response().withBody("some_body").withDelay(TimeUnit.SECONDS, 3L) ); // then assertEquals( response() .withStatusCode(OK_200.code()) .withReasonPhrase(OK_200.reasonPhrase()) .withBody("some_body"), makeRequest( request() .withPath(calculatePath("some_path")), headersToIgnore) ); // - in http assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()) .withReasonPhrase(HttpStatusCode.NOT_FOUND_404.reasonPhrase()), makeRequest( request() .withPath(calculatePath("some_path")), headersToIgnore) ); // - in https assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()) .withReasonPhrase(HttpStatusCode.NOT_FOUND_404.reasonPhrase()), makeRequest( request() .withSecure(true) .withPath(calculatePath("some_path")), headersToIgnore) ); } @Test public void shouldNotReturnResponseForMatchingBodyWithNotOperator() { // when mockServerClient .when( request() .withBody(Not.not(json("{" + NEW_LINE + " \"id\": 1," + NEW_LINE + " \"name\": \"A green door\"," + NEW_LINE + " \"price\": 12.50," + NEW_LINE + " \"tags\": [\"home\", \"green\"]" + NEW_LINE + "}"))), exactly(2) ) .respond( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withReasonPhrase(HttpStatusCode.ACCEPTED_202.reasonPhrase()) .withBody("some_body") ); // then // - in http assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()) .withReasonPhrase(HttpStatusCode.NOT_FOUND_404.reasonPhrase()), makeRequest( request() .withPath(calculatePath("some_path")) .withMethod("POST") .withBody("{" + NEW_LINE + " \"id\": 1," + NEW_LINE + " \"extra_ignored_field\": \"some value\"," + NEW_LINE + " \"name\": \"A green door\"," + NEW_LINE + " \"price\": 12.50," + NEW_LINE + " \"tags\": [\"home\", \"green\"]" + NEW_LINE + "}"), headersToIgnore) ); // - in https assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()) .withReasonPhrase(HttpStatusCode.NOT_FOUND_404.reasonPhrase()), makeRequest( request() .withSecure(true) .withPath(calculatePath("some_path")) .withMethod("POST") .withBody("{" + NEW_LINE + " \"id\": 1," + NEW_LINE + " \"extra_ignored_array\": [\"one\", \"two\"]," + NEW_LINE + " \"name\": \"A green door\"," + NEW_LINE + " \"price\": 12.50," + NEW_LINE + " \"tags\": [\"home\", \"green\"]" + NEW_LINE + "}"), headersToIgnore) ); } @Test public void shouldNotReturnResponseForNonMatchingXPathBody() { // when mockServerClient.when(request().withBody(new XPathBody("/bookstore/book[price>35]/price")), exactly(2)).respond(response().withBody("some_body")); // then // - in http assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()) .withReasonPhrase(HttpStatusCode.NOT_FOUND_404.reasonPhrase()), makeRequest( request() .withSecure(true) .withPath(calculatePath("some_path")) .withMethod("POST") .withBody(new StringBody("" + "<?xml version=\"1.0\" encoding=\"ISO-8859-1\"?>" + NEW_LINE + "<bookstore>" + NEW_LINE + " <book category=\"COOKING\">" + NEW_LINE + " <title lang=\"en\">Everyday Italian</title>" + NEW_LINE + " <author>Giada De Laurentiis</author>" + NEW_LINE + " <year>2005</year>" + NEW_LINE + " <price>30.00</price>" + NEW_LINE + " </book>" + NEW_LINE + " <book category=\"CHILDREN\">" + NEW_LINE + " <title lang=\"en\">Harry Potter</title>" + NEW_LINE + " <author>J K. Rowling</author>" + NEW_LINE + " <year>2005</year>" + NEW_LINE + " <price>29.99</price>" + NEW_LINE + " </book>" + NEW_LINE + " <book category=\"WEB\">" + NEW_LINE + " <title lang=\"en\">Learning XML</title>" + NEW_LINE + " <author>Erik T. Ray</author>" + NEW_LINE + " <year>2003</year>" + NEW_LINE + " <price>31.95</price>" + NEW_LINE + " </book>" + NEW_LINE + "</bookstore>")), headersToIgnore) ); // - in https assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()) .withReasonPhrase(HttpStatusCode.NOT_FOUND_404.reasonPhrase()), makeRequest( request() .withSecure(true) .withPath(calculatePath("some_path")) .withMethod("POST") .withBody(new StringBody("" + "<?xml version=\"1.0\" encoding=\"ISO-8859-1\"?>" + NEW_LINE + "<bookstore>" + NEW_LINE + " <book category=\"COOKING\">" + NEW_LINE + " <title lang=\"en\">Everyday Italian</title>" + NEW_LINE + " <author>Giada De Laurentiis</author>" + NEW_LINE + " <year>2005</year>" + NEW_LINE + " <price>30.00</price>" + NEW_LINE + " </book>" + NEW_LINE + " <book category=\"CHILDREN\">" + NEW_LINE + " <title lang=\"en\">Harry Potter</title>" + NEW_LINE + " <author>J K. Rowling</author>" + NEW_LINE + " <year>2005</year>" + NEW_LINE + " <price>29.99</price>" + NEW_LINE + " </book>" + NEW_LINE + " <book category=\"WEB\">" + NEW_LINE + " <title lang=\"en\">Learning XML</title>" + NEW_LINE + " <author>Erik T. Ray</author>" + NEW_LINE + " <year>2003</year>" + NEW_LINE + " <price>31.95</price>" + NEW_LINE + " </book>" + NEW_LINE + "</bookstore>")), headersToIgnore) ); } @Test public void shouldNotReturnResponseForNonMatchingXmlBody() { // when mockServerClient.when(request().withBody(xml("" + "<?xml version=\"1.0\" encoding=\"ISO-8859-1\"?>" + NEW_LINE + "<bookstore>" + NEW_LINE + " <book category=\"COOKING\" nationality=\"ITALIAN\">" + NEW_LINE + " <title lang=\"en\">Everyday Italian</title>" + NEW_LINE + " <author>Giada De Laurentiis</author>" + NEW_LINE + " <year>2005</year>" + NEW_LINE + " <price>30.00</price>" + NEW_LINE + " </book>" + NEW_LINE + "</bookstore>")), exactly(2)).respond(response().withBody("some_body")); // then // - in http assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()) .withReasonPhrase(HttpStatusCode.NOT_FOUND_404.reasonPhrase()), makeRequest( request() .withSecure(true) .withPath(calculatePath("some_path")) .withMethod("POST") .withBody(new StringBody("" + "<?xml version=\"1.0\" encoding=\"ISO-8859-1\"?>" + NEW_LINE + "<bookstore>" + NEW_LINE + " <book category=\"COOKING\">" + NEW_LINE + " <title lang=\"en\">Everyday Italian</title>" + NEW_LINE + " <author>Giada De Laurentiis</author>" + NEW_LINE + " <year>2005</year>" + NEW_LINE + " <price>30.00</price>" + NEW_LINE + " </book>" + NEW_LINE + "</bookstore>")), headersToIgnore) ); // - in https assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()) .withReasonPhrase(HttpStatusCode.NOT_FOUND_404.reasonPhrase()), makeRequest( request() .withSecure(true) .withPath(calculatePath("some_path")) .withMethod("POST") .withBody(new StringBody("" + "<?xml version=\"1.0\" encoding=\"ISO-8859-1\"?>" + NEW_LINE + "<bookstore>" + NEW_LINE + " <book category=\"COOKING\">" + NEW_LINE + " <title lang=\"en\">Everyday Italian</title>" + NEW_LINE + " <author>Giada De Laurentiis</author>" + NEW_LINE + " <year>2005</year>" + NEW_LINE + " <price>30.00</price>" + NEW_LINE + " </book>" + NEW_LINE + "</bookstore>")), headersToIgnore) ); } @Test public void shouldNotReturnResponseForNonMatchingJsonBody() { // when mockServerClient.when(request().withBody(json("{" + NEW_LINE + " \"id\": 1," + NEW_LINE + " \"name\": \"A green door\"," + NEW_LINE + " \"price\": 12.50," + NEW_LINE + " \"tags\": [\"home\", \"green\"]" + NEW_LINE + "}")), exactly(2)).respond(response().withBody("some_body")); // then // - in http assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()) .withReasonPhrase(HttpStatusCode.NOT_FOUND_404.reasonPhrase()), makeRequest( request() .withPath(calculatePath("some_path")) .withMethod("POST") .withBody("{" + NEW_LINE + " \"id\": 1," + NEW_LINE + " \"name\": \"---- XXXX WRONG VALUE XXXX ----\"," + NEW_LINE + " \"price\": 12.50," + NEW_LINE + " \"tags\": [\"home\", \"green\"]" + NEW_LINE + "}"), headersToIgnore) ); // - in https assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()) .withReasonPhrase(HttpStatusCode.NOT_FOUND_404.reasonPhrase()), makeRequest( request() .withSecure(true) .withPath(calculatePath("some_path")) .withMethod("POST") .withBody("{" + NEW_LINE + " \"id\": 1," + NEW_LINE + " \"name\": \"---- XXXX WRONG VALUE XXXX ----\"," + NEW_LINE + " \"price\": 12.50," + NEW_LINE + " \"tags\": [\"home\", \"green\"]" + NEW_LINE + "}"), headersToIgnore) ); } @Test public void shouldNotReturnResponseForNonMatchingJsonBodyWithMatchType() { // when mockServerClient .when( request() .withBody(json("{" + NEW_LINE + " \"id\": 1," + NEW_LINE + " \"name\": \"A green door\"," + NEW_LINE + " \"price\": 12.50," + NEW_LINE + " \"tags\": [\"home\", \"green\"]" + NEW_LINE + "}", MatchType.STRICT)), exactly(2)) .respond( response() .withBody("some_body") ); // then // - in http assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()) .withReasonPhrase(HttpStatusCode.NOT_FOUND_404.reasonPhrase()), makeRequest( request() .withPath(calculatePath("some_path")) .withMethod("POST") .withBody("{" + NEW_LINE + " \"id\": 1," + NEW_LINE + " \"extra field\": \"some value\"," + NEW_LINE + " \"name\": \"A green door\"," + NEW_LINE + " \"price\": 12.50," + NEW_LINE + " \"tags\": [\"home\", \"green\"]" + NEW_LINE + "}"), headersToIgnore) ); // - in https assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()) .withReasonPhrase(HttpStatusCode.NOT_FOUND_404.reasonPhrase()), makeRequest( request() .withSecure(true) .withPath(calculatePath("some_path")) .withMethod("POST") .withBody("{" + NEW_LINE + " \"id\": 1," + NEW_LINE + " \"extra field\": \"some value\"," + NEW_LINE + " \"name\": \"A green door\"," + NEW_LINE + " \"price\": 12.50," + NEW_LINE + " \"tags\": [\"home\", \"green\"]" + NEW_LINE + "}"), headersToIgnore) ); } @Test public void shouldNotReturnResponseForNonMatchingJsonSchema() { // when mockServerClient.when(request().withBody(jsonSchema("{" + NEW_LINE + " \"$schema\": \"http://json-schema.org/draft-04/schema#\"," + NEW_LINE + " \"title\": \"Product\"," + NEW_LINE + " \"description\": \"A product from Acme's catalog\"," + NEW_LINE + " \"type\": \"object\"," + NEW_LINE + " \"properties\": {" + NEW_LINE + " \"id\": {" + NEW_LINE + " \"description\": \"The unique identifier for a product\"," + NEW_LINE + " \"type\": \"integer\"" + NEW_LINE + " }," + NEW_LINE + " \"name\": {" + NEW_LINE + " \"description\": \"Name of the product\"," + NEW_LINE + " \"type\": \"string\"" + NEW_LINE + " }," + NEW_LINE + " \"price\": {" + NEW_LINE + " \"type\": \"number\"," + NEW_LINE + " \"minimum\": 0," + NEW_LINE + " \"exclusiveMinimum\": true" + NEW_LINE + " }," + NEW_LINE + " \"tags\": {" + NEW_LINE + " \"type\": \"array\"," + NEW_LINE + " \"items\": {" + NEW_LINE + " \"type\": \"string\"" + NEW_LINE + " }," + NEW_LINE + " \"minItems\": 1," + NEW_LINE + " \"uniqueItems\": true" + NEW_LINE + " }" + NEW_LINE + " }," + NEW_LINE + " \"required\": [\"id\", \"name\", \"price\"]" + NEW_LINE + "}")), exactly(2)).respond(response().withBody("some_body")); // then // - in http assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()) .withReasonPhrase(HttpStatusCode.NOT_FOUND_404.reasonPhrase()), makeRequest( request() .withPath(calculatePath("some_path")) .withMethod("POST") .withBody("{" + NEW_LINE + " \"id\": 1," + NEW_LINE + " \"wrong field name\": \"A green door\"," + NEW_LINE + " \"price\": 12.50," + NEW_LINE + " \"tags\": [\"home\", \"green\"]" + NEW_LINE + "}"), headersToIgnore) ); // - in https assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()) .withReasonPhrase(HttpStatusCode.NOT_FOUND_404.reasonPhrase()), makeRequest( request() .withSecure(true) .withPath(calculatePath("some_path")) .withMethod("POST") .withBody("{" + NEW_LINE + " \"id\": 1," + NEW_LINE + " \"name\": \"A green door\"," + NEW_LINE + " \"wrong field name\": 12.50," + NEW_LINE + " \"tags\": [\"home\", \"green\"]" + NEW_LINE + "}"), headersToIgnore) ); } @Test public void shouldNotReturnResponseForMatchingPathWithNotOperator() { // when mockServerClient .when( request() .withPath(not(calculatePath("some_path"))) ) .respond( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withReasonPhrase(HttpStatusCode.ACCEPTED_202.reasonPhrase()) .withBody("some_body_response") ); // then // - in http assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()) .withReasonPhrase(HttpStatusCode.NOT_FOUND_404.reasonPhrase()), makeRequest( request() .withPath(calculatePath("some_path")), headersToIgnore) ); // - in https assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()) .withReasonPhrase(HttpStatusCode.NOT_FOUND_404.reasonPhrase()), makeRequest( request() .withPath(calculatePath("some_path")), headersToIgnore) ); } @Test public void shouldNotReturnResponseForMatchingMethodWithNotOperator() { // when mockServerClient .when( request() .withMethod(not("GET")) ) .respond( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withReasonPhrase(HttpStatusCode.ACCEPTED_202.reasonPhrase()) .withBody("some_body_response") ); // then // - in http assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()) .withReasonPhrase(HttpStatusCode.NOT_FOUND_404.reasonPhrase()), makeRequest( request() .withMethod("GET"), headersToIgnore) ); // - in https assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()) .withReasonPhrase(HttpStatusCode.NOT_FOUND_404.reasonPhrase()), makeRequest( request() .withMethod("GET"), headersToIgnore) ); } @Test public void shouldNotReturnResponseForNonMatchingBodyParameterName() { // when mockServerClient .when( request() .withMethod("POST") .withPath(calculatePath("some_pathRequest")) .withBody(params( param("bodyParameterOneName", "Parameter One Value One", "Parameter One Value Two"), param("bodyParameterTwoName", "Parameter Two") )) ) .respond( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withReasonPhrase(HttpStatusCode.ACCEPTED_202.reasonPhrase()) .withBody("some_body_response") .withHeaders(header("headerNameResponse", "headerValueResponse")) .withCookies(cookie("cookieNameResponse", "cookieValueResponse")) ); // then // wrong query string parameter name assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()) .withReasonPhrase(HttpStatusCode.NOT_FOUND_404.reasonPhrase()), makeRequest( request() .withMethod("POST") .withPath(calculatePath("some_pathRequest")) .withBody(params( param("OTHERBodyParameterOneName", "Parameter One Value One", "Parameter One Value Two"), param("bodyParameterTwoName", "Parameter Two") )) .withHeaders(header("headerNameRequest", "headerValueRequest")) .withCookies(cookie("cookieNameRequest", "cookieValueRequest")), headersToIgnore) ); // wrong query string parameter name assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()) .withReasonPhrase(HttpStatusCode.NOT_FOUND_404.reasonPhrase()), makeRequest( request() .withMethod("POST") .withPath(calculatePath("some_pathRequest")) .withBody(new StringBody("OTHERBodyParameterOneName=Parameter+One+Value+One" + "&bodyParameterOneName=Parameter+One+Value+Two" + "&bodyParameterTwoName=Parameter+Two")) .withHeaders(header("headerNameRequest", "headerValueRequest")) .withCookies(cookie("cookieNameRequest", "cookieValueRequest")), headersToIgnore) ); } @Test public void shouldNotReturnResponseForMatchingBodyParameterWithNotOperator() { // when mockServerClient .when( request() .withMethod("POST") .withPath(calculatePath("some_pathRequest")) .withBody(params( param(not("bodyParameterOneName"), not("Parameter One Value One"), not("Parameter One Value Two")), param("bodyParameterTwoName", "Parameter Two") )) ) .respond( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withReasonPhrase(HttpStatusCode.ACCEPTED_202.reasonPhrase()) .withBody("some_body_response") ); // then // wrong query string parameter name assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()) .withReasonPhrase(HttpStatusCode.NOT_FOUND_404.reasonPhrase()), makeRequest( request() .withMethod("POST") .withPath(calculatePath("some_pathRequest")) .withBody(params( param("bodyParameterOneName", "Parameter One Value One", "Parameter One Value Two"), param("bodyParameterTwoName", "Parameter Two") )) .withHeaders(header("headerNameRequest", "headerValueRequest")) .withCookies(cookie("cookieNameRequest", "cookieValueRequest")), headersToIgnore) ); // wrong query string parameter name assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()) .withReasonPhrase(HttpStatusCode.NOT_FOUND_404.reasonPhrase()), makeRequest( request() .withMethod("POST") .withPath(calculatePath("some_pathRequest")) .withBody(new StringBody("bodyParameterOneName=Other Parameter+One+Value+One" + "&bodyParameterOneName=Parameter+One+Value+Two" + "&bodyParameterTwoName=Parameter+Two")) .withHeaders(header("headerNameRequest", "headerValueRequest")) .withCookies(cookie("cookieNameRequest", "cookieValueRequest")), headersToIgnore) ); } @Test public void shouldNotReturnResponseForNonMatchingBodyParameterValue() { // when mockServerClient .when( request() .withMethod("POST") .withPath(calculatePath("some_pathRequest")) .withBody(params( param("bodyParameterOneName", "Parameter One Value One", "Parameter One Value Two"), param("bodyParameterTwoName", "Parameter Two") )) ) .respond( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withReasonPhrase(HttpStatusCode.ACCEPTED_202.reasonPhrase()) .withBody("some_body_response") .withHeaders(header("headerNameResponse", "headerValueResponse")) .withCookies(cookie("cookieNameResponse", "cookieValueResponse")) ); // then // wrong body parameter value assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()) .withReasonPhrase(HttpStatusCode.NOT_FOUND_404.reasonPhrase()), makeRequest( request() .withMethod("POST") .withPath(calculatePath("some_pathRequest")) .withBody(params( param("bodyParameterOneName", "Other Parameter One Value One", "Parameter One Value Two"), param("bodyParameterTwoName", "Parameter Two") )) .withHeaders(header("headerNameRequest", "headerValueRequest")) .withCookies(cookie("cookieNameRequest", "cookieValueRequest")), headersToIgnore) ); // wrong body parameter value assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()) .withReasonPhrase(HttpStatusCode.NOT_FOUND_404.reasonPhrase()), makeRequest( request() .withMethod("POST") .withPath(calculatePath("some_pathRequest")) .withBody(new StringBody("bodyParameterOneName=Other Parameter+One+Value+One" + "&bodyParameterOneName=Parameter+One+Value+Two" + "&bodyParameterTwoName=Parameter+Two")) .withHeaders(header("headerNameRequest", "headerValueRequest")) .withCookies(cookie("cookieNameRequest", "cookieValueRequest")), headersToIgnore) ); } @Test public void shouldNotReturnResponseForNonMatchingQueryStringParameterName() { // when mockServerClient .when( request() .withMethod("POST") .withPath(calculatePath("some_pathRequest")) .withQueryStringParameters( param("queryStringParameterOneName", "queryStringParameterOneValueOne", "queryStringParameterOneValueTwo"), param("queryStringParameterTwoName", "queryStringParameterTwoValue") ) .withBody("some_bodyRequest") ) .respond( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withReasonPhrase(HttpStatusCode.ACCEPTED_202.reasonPhrase()) .withBody("some_body_response") .withHeaders(header("headerNameResponse", "headerValueResponse")) .withCookies(cookie("cookieNameResponse", "cookieValueResponse")) ); // then // wrong query string parameter name assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()) .withReasonPhrase(HttpStatusCode.NOT_FOUND_404.reasonPhrase()), makeRequest( request() .withMethod("POST") .withPath(calculatePath("some_pathRequest")) .withQueryStringParameters( param("OTHERQueryStringParameterOneName", "queryStringParameterOneValueOne", "queryStringParameterOneValueTwo"), param("queryStringParameterTwoName", "queryStringParameterTwoValue") ) .withBody("some_bodyRequest") .withHeaders( header("headerNameRequest", "headerValueRequest") ) .withCookies(cookie("cookieNameRequest", "cookieValueRequest")), headersToIgnore) ); } @Test public void shouldNotReturnResponseForNonMatchingQueryStringParameterValue() { // when mockServerClient .when( request() .withMethod("POST") .withPath(calculatePath("some_pathRequest")) .withQueryStringParameters( param("queryStringParameterOneName", "queryStringParameterOneValueOne", "queryStringParameterOneValueTwo"), param("queryStringParameterTwoName", "queryStringParameterTwoValue") ) .withBody("some_bodyRequest") ) .respond( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withReasonPhrase(HttpStatusCode.ACCEPTED_202.reasonPhrase()) .withBody("some_body_response") .withHeaders(header("headerNameResponse", "headerValueResponse")) .withCookies(cookie("cookieNameResponse", "cookieValueResponse")) ); // then // wrong query string parameter value assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()) .withReasonPhrase(HttpStatusCode.NOT_FOUND_404.reasonPhrase()), makeRequest( request() .withMethod("POST") .withPath(calculatePath("some_pathRequest")) .withQueryStringParameters( param("queryStringParameterOneName", "OTHERqueryStringParameterOneValueOne", "queryStringParameterOneValueTwo"), param("queryStringParameterTwoName", "queryStringParameterTwoValue") ) .withBody("some_bodyRequest") .withHeaders(header("headerNameRequest", "headerValueRequest")) .withCookies(cookie("cookieNameRequest", "cookieValueRequest")), headersToIgnore) ); } @Test public void shouldNotReturnResponseForMatchingQueryStringParameterWithNotOperator() { // when mockServerClient .when( request() .withMethod("POST") .withPath(calculatePath("some_pathRequest")) .withQueryStringParameters( param(not("queryStringParameterOneName"), not("Parameter One Value One"), not("Parameter One Value Two")), param("queryStringParameterTwoName", "Parameter Two") ) ) .respond( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withReasonPhrase(HttpStatusCode.ACCEPTED_202.reasonPhrase()) .withBody("some_body_response") ); // then // wrong query string parameter name assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()) .withReasonPhrase(HttpStatusCode.NOT_FOUND_404.reasonPhrase()), makeRequest( request() .withMethod("POST") .withPath(calculatePath("some_pathRequest")) .withQueryStringParameters( param("queryStringParameterOneName", "Parameter One Value One", "Parameter One Value Two"), param("queryStringParameterTwoName", "Parameter Two") ), headersToIgnore) ); // wrong query string parameter name assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()) .withReasonPhrase(HttpStatusCode.NOT_FOUND_404.reasonPhrase()), makeRequest( request() .withMethod("POST") .withPath(calculatePath("some_pathRequest")) .withQueryStringParameters( param("queryStringParameterOneName", "Parameter One Value One", "Parameter One Value Two"), param("queryStringParameterTwoName", "Parameter Two") ), headersToIgnore) ); } @Test public void shouldNotReturnResponseForNonMatchingCookieName() { // when mockServerClient .when( request() .withMethod("GET") .withPath(calculatePath("some_path")) .withQueryStringParameters( param("queryStringParameterOneName", "queryStringParameterOneValue"), param("queryStringParameterTwoName", "queryStringParameterTwoValue") ) .withBody(exact("some_body")) .withHeaders(header("headerName", "headerValue")) .withCookies(cookie("cookieName", "cookieValue")) ) .respond( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withReasonPhrase(HttpStatusCode.ACCEPTED_202.reasonPhrase()) .withBody("some_body") .withHeaders(header("headerName", "headerValue")) .withCookies(cookie("cookieName", "cookieValue")) ); // then // - in http assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()) .withReasonPhrase(HttpStatusCode.NOT_FOUND_404.reasonPhrase()), makeRequest( request() .withMethod("GET") .withPath(calculatePath("some_path")) .withQueryStringParameters( param("queryStringParameterOneName", "queryStringParameterOneValue"), param("queryStringParameterTwoName", "queryStringParameterTwoValue") ) .withBody(exact("some_body")) .withHeaders(header("headerName", "headerValue")) .withCookies(cookie("cookieOtherName", "cookieValue")), headersToIgnore) ); // - in https assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()) .withReasonPhrase(HttpStatusCode.NOT_FOUND_404.reasonPhrase()), makeRequest( request() .withMethod("GET") .withSecure(true) .withPath(calculatePath("some_path")) .withQueryStringParameters( param("queryStringParameterOneName", "queryStringParameterOneValue"), param("queryStringParameterTwoName", "queryStringParameterTwoValue") ) .withBody(exact("some_body")) .withHeaders(header("headerName", "headerValue")) .withCookies(cookie("cookieOtherName", "cookieValue")), headersToIgnore) ); } @Test public void shouldNotReturnResponseForNonMatchingCookieValue() { // when mockServerClient .when( request() .withMethod("GET") .withPath(calculatePath("some_path")) .withQueryStringParameters( param("queryStringParameterOneName", "queryStringParameterOneValue"), param("queryStringParameterTwoName", "queryStringParameterTwoValue") ) .withBody(exact("some_body")) .withHeaders(header("headerName", "headerValue")) .withCookies(cookie("cookieName", "cookieValue")) ) .respond( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withReasonPhrase(HttpStatusCode.ACCEPTED_202.reasonPhrase()) .withBody("some_body") .withHeaders(header("headerName", "headerValue")) .withCookies(cookie("cookieName", "cookieValue")) ); // then // - in http assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()) .withReasonPhrase(HttpStatusCode.NOT_FOUND_404.reasonPhrase()), makeRequest( request() .withMethod("GET") .withPath(calculatePath("some_path")) .withQueryStringParameters( param("queryStringParameterOneName", "queryStringParameterOneValue"), param("queryStringParameterTwoName", "queryStringParameterTwoValue") ) .withBody(exact("some_body")) .withHeaders(header("headerName", "headerValue")) .withCookies(cookie("cookieName", "cookieOtherValue")), headersToIgnore) ); // - in https assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()) .withReasonPhrase(HttpStatusCode.NOT_FOUND_404.reasonPhrase()), makeRequest( request() .withMethod("GET") .withSecure(true) .withPath(calculatePath("some_path")) .withQueryStringParameters( param("queryStringParameterOneName", "queryStringParameterOneValue"), param("queryStringParameterTwoName", "queryStringParameterTwoValue") ) .withBody(exact("some_body")) .withHeaders(header("headerName", "headerValue")) .withCookies(cookie("cookieName", "cookieOtherValue")), headersToIgnore) ); } @Test public void shouldNotReturnResponseForMatchingCookieWithNotOperator() { // when mockServerClient .when( request() .withMethod("GET") .withPath(calculatePath("some_pathRequest")) .withCookies( cookie(not("requestCookieNameOne"), not("requestCookieValueOne")), cookie("requestCookieNameTwo", "requestCookieValueTwo") ) ) .respond( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withReasonPhrase(HttpStatusCode.ACCEPTED_202.reasonPhrase()) .withBody("some_body_response") ); // then // wrong query string parameter name assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()) .withReasonPhrase(HttpStatusCode.NOT_FOUND_404.reasonPhrase()), makeRequest( request() .withMethod("GET") .withPath(calculatePath("some_pathRequest")) .withCookies( cookie("requestCookieNameOne", "requestCookieValueOne"), cookie("requestCookieNameTwo", "requestCookieValueTwo") ), headersToIgnore) ); // wrong query string parameter name assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()) .withReasonPhrase(HttpStatusCode.NOT_FOUND_404.reasonPhrase()), makeRequest( request() .withMethod("GET") .withPath(calculatePath("some_pathRequest")) .withCookies( cookie("requestCookieNameOne", "requestCookieValueOne"), cookie("requestCookieNameTwo", "requestCookieValueTwo") ), headersToIgnore) ); } @Test public void shouldNotReturnResponseForNonMatchingHeaderName() { // when mockServerClient .when( request() .withMethod("GET") .withPath(calculatePath("some_path")) .withQueryStringParameters( param("queryStringParameterOneName", "queryStringParameterOneValue"), param("queryStringParameterTwoName", "queryStringParameterTwoValue") ) .withBody(exact("some_body")) .withHeaders(header("headerName", "headerValue")) .withCookies(cookie("cookieName", "cookieValue")) ) .respond( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withReasonPhrase(HttpStatusCode.ACCEPTED_202.reasonPhrase()) .withBody("some_body") .withHeaders(header("headerName", "headerValue")) .withCookies(cookie("cookieName", "cookieValue")) ); // then // - in http assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()) .withReasonPhrase(HttpStatusCode.NOT_FOUND_404.reasonPhrase()), makeRequest( request() .withMethod("GET") .withPath(calculatePath("some_path")) .withQueryStringParameters( param("queryStringParameterOneName", "queryStringParameterOneValue"), param("queryStringParameterTwoName", "queryStringParameterTwoValue") ) .withBody(exact("some_body")) .withHeaders(header("headerOtherName", "headerValue")) .withCookies(cookie("cookieName", "cookieValue")), headersToIgnore) ); // - in https assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()) .withReasonPhrase(HttpStatusCode.NOT_FOUND_404.reasonPhrase()), makeRequest( request() .withMethod("GET") .withSecure(true) .withPath(calculatePath("some_path")) .withQueryStringParameters( param("queryStringParameterOneName", "queryStringParameterOneValue"), param("queryStringParameterTwoName", "queryStringParameterTwoValue") ) .withBody(exact("some_body")) .withHeaders(header("headerOtherName", "headerValue")) .withCookies(cookie("cookieName", "cookieValue")), headersToIgnore) ); } @Test public void shouldNotReturnResponseForNonMatchingHeaderValue() { // when mockServerClient .when( request() .withMethod("GET") .withPath(calculatePath("some_path")) .withQueryStringParameters( param("queryStringParameterOneName", "queryStringParameterOneValue"), param("queryStringParameterTwoName", "queryStringParameterTwoValue") ) .withBody(exact("some_body")) .withHeaders(header("headerName", "headerValue")) .withCookies(cookie("cookieName", "cookieValue")) ) .respond( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withReasonPhrase(HttpStatusCode.ACCEPTED_202.reasonPhrase()) .withBody("some_body") .withHeaders(header("headerName", "headerValue")) .withCookies(cookie("cookieName", "cookieValue")) ); // then // - in http assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()) .withReasonPhrase(HttpStatusCode.NOT_FOUND_404.reasonPhrase()), makeRequest( request() .withMethod("GET") .withPath(calculatePath("some_path")) .withQueryStringParameters( param("queryStringParameterOneName", "queryStringParameterOneValue"), param("queryStringParameterTwoName", "queryStringParameterTwoValue") ) .withBody(exact("some_body")) .withHeaders(header("headerName", "headerOtherValue")) .withCookies(cookie("cookieName", "cookieValue")), headersToIgnore) ); // - in https assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()) .withReasonPhrase(HttpStatusCode.NOT_FOUND_404.reasonPhrase()), makeRequest( request() .withMethod("GET") .withSecure(true) .withPath(calculatePath("some_path")) .withQueryStringParameters( param("queryStringParameterOneName", "queryStringParameterOneValue"), param("queryStringParameterTwoName", "queryStringParameterTwoValue") ) .withBody(exact("some_body")) .withHeaders(header("headerName", "headerOtherValue")) .withCookies(cookie("cookieName", "cookieValue")), headersToIgnore) ); } @Test public void shouldNotReturnResponseForMatchingHeaderWithNotOperator() { // when mockServerClient .when( request() .withMethod("GET") .withPath(calculatePath("some_pathRequest")) .withHeaders( header(not("requestHeaderNameOne"), not("requestHeaderValueOne")), header("requestHeaderNameTwo", "requestHeaderValueTwo") ) ) .respond( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withReasonPhrase(HttpStatusCode.ACCEPTED_202.reasonPhrase()) .withBody("some_body_response") ); // then // wrong query string parameter name assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()) .withReasonPhrase(HttpStatusCode.NOT_FOUND_404.reasonPhrase()), makeRequest( request() .withMethod("GET") .withPath(calculatePath("some_pathRequest")) .withHeaders( header("requestHeaderNameOne", "requestHeaderValueOne"), header("requestHeaderNameTwo", "requestHeaderValueTwo") ), headersToIgnore) ); // wrong query string parameter name assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()) .withReasonPhrase(HttpStatusCode.NOT_FOUND_404.reasonPhrase()), makeRequest( request() .withMethod("GET") .withPath(calculatePath("some_pathRequest")) .withHeaders( header("requestHeaderNameOne", "requestHeaderValueOne"), header("requestHeaderNameTwo", "requestHeaderValueTwo") ), headersToIgnore) ); } @Test public void shouldVerifyReceivedRequestInSsl() { // when mockServerClient .when( request() .withPath(calculatePath("some.*path")), exactly(2) ) .respond( response() .withBody("some_body") ); // then // - in http assertEquals( response() .withStatusCode(OK_200.code()) .withReasonPhrase(OK_200.reasonPhrase()) .withBody("some_body"), makeRequest( request() .withPath(calculatePath("some_path")), headersToIgnore) ); mockServerClient.verify(request() .withPath(calculatePath("some_path")) .withSecure(false)); mockServerClient.verify(request() .withPath(calculatePath("some_path")) .withSecure(false), VerificationTimes.exactly(1)); // - in https assertEquals( response() .withStatusCode(OK_200.code()) .withReasonPhrase(OK_200.reasonPhrase()) .withBody("some_body"), makeRequest( request() .withPath(calculatePath("some_secure_path")) .withSecure(true), headersToIgnore) ); mockServerClient.verify(request() .withPath(calculatePath("some_secure_path")) .withSecure(true)); mockServerClient.verify(request() .withPath(calculatePath("some_secure_path")) .withSecure(true), VerificationTimes.exactly(1)); } @Test public void shouldVerifyReceivedRequestsWithRegexBody() { // when mockServerClient .when( request() .withMethod("POST") .withPath(calculatePath("some_path")) .withBody("{type: 'some_random_type', value: 'some_random_value'}"), exactly(2) ) .respond( response() .withBody("some_response") ); // then // - in http assertEquals( response() .withStatusCode(OK_200.code()) .withReasonPhrase(OK_200.reasonPhrase()) .withBody("some_response"), makeRequest( request() .withMethod("POST") .withPath(calculatePath("some_path")) .withBody("{type: 'some_random_type', value: 'some_random_value'}"), headersToIgnore) ); mockServerClient.verify( request() .withBody(regex("\\{type\\: \\'some_random_type\\'\\, value\\: \\'some_random_value\\'\\}")) ); mockServerClient.verify( request() .withBody(regex("\\{type\\: \\'some_random_type\\'\\, value\\: \\'some_random_value\\'\\}")), VerificationTimes.exactly(1) ); // - in https assertEquals( response() .withStatusCode(OK_200.code()) .withReasonPhrase(OK_200.reasonPhrase()) .withBody("some_response"), makeRequest( request() .withSecure(true) .withMethod("POST") .withPath(calculatePath("some_path")) .withBody("{type: 'some_random_type', value: 'some_random_value'}"), headersToIgnore) ); mockServerClient.verify( request() .withSecure(true) .withBody(regex("\\{type\\: \\'some_random_type\\'\\, value\\: \\'some_random_value\\'\\}")) ); mockServerClient.verify( request() .withSecure(true) .withBody(regex("\\{type\\: \\'some_random_type\\'\\, value\\: \\'some_random_value\\'\\}")), VerificationTimes.atLeast(1) ); } @Test public void shouldVerifyReceivedRequestsWithNoBody() { // when mockServerClient.when(request().withPath(calculatePath("some_path")), exactly(2)).respond(response()); // then // - in http assertEquals( response() .withStatusCode(OK_200.code()) .withReasonPhrase(OK_200.reasonPhrase()), makeRequest( request() .withPath(calculatePath("some_path")), headersToIgnore) ); mockServerClient.verify(request() .withPath(calculatePath("some_path"))); mockServerClient.verify(request() .withPath(calculatePath("some_path")), VerificationTimes.exactly(1)); } @Test public void shouldVerifyTooManyRequestsReceived() { // when mockServerClient.when(request().withPath(calculatePath("some_path")), exactly(2)).respond(response().withBody("some_body")); // then assertEquals( response() .withStatusCode(OK_200.code()) .withReasonPhrase(OK_200.reasonPhrase()) .withBody("some_body"), makeRequest( request() .withPath(calculatePath("some_path")), headersToIgnore) ); try { mockServerClient.verify(request() .withPath(calculatePath("some_path")), VerificationTimes.exactly(0)); fail(); } catch (AssertionError ae) { assertThat(ae.getMessage(), startsWith("Request not found exactly 0 times, expected:<{" + NEW_LINE + " \"path\" : \"" + calculatePath("some_path") + "\"" + NEW_LINE + "}> but was:<{" + NEW_LINE + " \"method\" : \"GET\"," + NEW_LINE + " \"path\" : \"" + calculatePath("some_path") + "\"," + NEW_LINE)); } } @Test public void shouldVerifyNoMatchingRequestsReceived() { // when mockServerClient.when(request().withPath(calculatePath("some_path")), exactly(2)).respond(response().withBody("some_body")); // then assertEquals( response() .withStatusCode(OK_200.code()) .withReasonPhrase(OK_200.reasonPhrase()) .withBody("some_body"), makeRequest( request() .withPath(calculatePath("some_path")), headersToIgnore) ); try { mockServerClient.verify(request() .withPath(calculatePath("some_other_path")), VerificationTimes.exactly(2)); fail(); } catch (AssertionError ae) { assertThat(ae.getMessage(), startsWith("Request not found exactly 2 times, expected:<{" + NEW_LINE + " \"path\" : \"" + calculatePath("some_other_path") + "\"" + NEW_LINE + "}> but was:<{" + NEW_LINE + " \"method\" : \"GET\"," + NEW_LINE + " \"path\" : \"" + calculatePath("some_path") + "\"," + NEW_LINE)); } } @Test public void shouldNotVerifyNoRequestsReceived() { // when mockServerClient.when(request().withPath(calculatePath("some_path")), exactly(2)).respond(response().withBody("some_body")); // then assertEquals( response() .withStatusCode(OK_200.code()) .withReasonPhrase(OK_200.reasonPhrase()) .withBody("some_body"), makeRequest( request() .withPath(calculatePath("some_path")), headersToIgnore) ); try { mockServerClient.verifyZeroInteractions(); fail(); } catch (AssertionError ae) { assertThat(ae.getMessage(), startsWith("Request not found exactly 0 times, expected:<{ }> but was:<{" + NEW_LINE + " \"method\" : \"GET\"," + NEW_LINE + " \"path\" : \"" + calculatePath("some_path") + "\"," + NEW_LINE)); } } @Test public void shouldVerifyNoMatchingRequestsReceivedInSsl() { // when mockServerClient.when(request().withPath(calculatePath("some.*path")), exactly(2)).respond(response().withBody("some_body")); // then // - in http assertEquals( response() .withStatusCode(OK_200.code()) .withReasonPhrase(OK_200.reasonPhrase()) .withBody("some_body"), makeRequest( request() .withPath(calculatePath("some_path")), headersToIgnore) ); try { mockServerClient.verify( request() .withPath(calculatePath("some_path")) .withSecure(true), VerificationTimes.atLeast(1) ); fail(); } catch (AssertionError ae) { assertThat(ae.getMessage(), startsWith("Request not found at least once, expected:<{" + NEW_LINE + " \"path\" : \"" + calculatePath("some_path") + "\"," + NEW_LINE + " \"secure\" : true" + NEW_LINE + "}> but was:<{" + NEW_LINE + " \"method\" : \"GET\"," + NEW_LINE + " \"path\" : \"" + calculatePath("some_path") + "\"," + NEW_LINE)); } // - in https assertEquals( response() .withStatusCode(OK_200.code()) .withReasonPhrase(OK_200.reasonPhrase()) .withBody("some_body"), makeRequest( request() .withPath(calculatePath("some_secure_path")) .withSecure(true), headersToIgnore) ); try { mockServerClient.verify( request() .withPath(calculatePath("some_secure_path")) .withSecure(false), VerificationTimes.atLeast(1) ); fail(); } catch (AssertionError ae) { assertThat(ae.getMessage(), startsWith("Request not found at least once, expected:<{" + NEW_LINE + " \"path\" : \"" + calculatePath("some_secure_path") + "\"," + NEW_LINE + " \"secure\" : false" + NEW_LINE + "}> but was:<[ {" + NEW_LINE + " \"method\" : \"GET\"," + NEW_LINE + " \"path\" : \"" + calculatePath("some_path") + "\"," + NEW_LINE)); } } @Test public void shouldVerifySequenceOfRequestsReceivedIncludingThoseNotMatchingAnException() { // when mockServerClient.when(request().withPath(calculatePath("some_path.*")), exactly(4)).respond(response().withBody("some_body")); // then assertEquals( response("some_body"), makeRequest( request().withPath(calculatePath("some_path_one")), headersToIgnore) ); assertEquals( notFoundResponse(), makeRequest( request().withPath(calculatePath("not_found")), headersToIgnore) ); assertEquals( response("some_body"), makeRequest( request().withPath(calculatePath("some_path_three")), headersToIgnore) ); mockServerClient.verify(request(calculatePath("some_path_one")), request(calculatePath("some_path_three"))); mockServerClient.verify(request(calculatePath("some_path_one")), request(calculatePath("not_found"))); mockServerClient.verify(request(calculatePath("some_path_one")), request(calculatePath("not_found")), request(calculatePath("some_path_three"))); mockServerClient.verify(request(calculatePath("some_path_one")), request(calculatePath("not_found")), request(calculatePath("some_path_three"))); } @Test public void shouldVerifySequenceOfRequestsNotReceived() { // when mockServerClient.when(request().withPath(calculatePath("some_path.*")), exactly(6)).respond(response().withBody("some_body")); // then assertEquals( response("some_body"), makeRequest( request().withPath(calculatePath("some_path_one")), headersToIgnore) ); assertEquals( response("some_body"), makeRequest( request().withPath(calculatePath("some_path_two")), headersToIgnore) ); assertEquals( response("some_body"), makeRequest( request().withPath(calculatePath("some_path_three")), headersToIgnore) ); try { mockServerClient.verify(request(calculatePath("some_path_two")), request(calculatePath("some_path_one"))); fail(); } catch (AssertionError ae) { assertThat(ae.getMessage(), startsWith("Request sequence not found, expected:<[ {" + NEW_LINE + " \"path\" : \"" + calculatePath("some_path_two") + "\"" + NEW_LINE + "}, {" + NEW_LINE + " \"path\" : \"" + calculatePath("some_path_one") + "\"" + NEW_LINE + "} ]> but was:<[ {" + NEW_LINE + " \"method\" : \"GET\"," + NEW_LINE + " \"path\" : \"" + calculatePath("some_path_one") + "\"," + NEW_LINE)); } try { mockServerClient.verify(request(calculatePath("some_path_three")), request(calculatePath("some_path_two"))); fail(); } catch (AssertionError ae) { assertThat(ae.getMessage(), startsWith("Request sequence not found, expected:<[ {" + NEW_LINE + " \"path\" : \"" + calculatePath("some_path_three") + "\"" + NEW_LINE + "}, {" + NEW_LINE + " \"path\" : \"" + calculatePath("some_path_two") + "\"" + NEW_LINE + "} ]> but was:<[ {" + NEW_LINE + " \"method\" : \"GET\"," + NEW_LINE + " \"path\" : \"" + calculatePath("some_path_one") + "\"," + NEW_LINE)); } try { mockServerClient.verify(request(calculatePath("some_path_four"))); fail(); } catch (AssertionError ae) { assertThat(ae.getMessage(), startsWith("Request sequence not found, expected:<[ {" + NEW_LINE + " \"path\" : \"" + calculatePath("some_path_four") + "\"" + NEW_LINE + "} ]> but was:<[ {" + NEW_LINE + " \"method\" : \"GET\"," + NEW_LINE + " \"path\" : \"" + calculatePath("some_path_one") + "\"," + NEW_LINE)); } } @Test public void shouldRetrieveRecordedRequestsAsJson() { // when mockServerClient.when(request().withPath(calculatePath("some_path.*")), exactly(4)).respond(response().withBody("some_body")); assertEquals( response("some_body"), makeRequest( request().withPath(calculatePath("some_path_one")), headersToIgnore) ); assertEquals( notFoundResponse(), makeRequest( request().withPath(calculatePath("not_found")), headersToIgnore) ); assertEquals( response("some_body"), makeRequest( request().withPath(calculatePath("some_path_three")), headersToIgnore) ); // then verifyRequestsMatches( new HttpRequestSerializer(new MockServerLogger()).deserializeArray(mockServerClient.retrieveRecordedRequests(request().withPath(calculatePath("some_path.*")), Format.JSON)), request(calculatePath("some_path_one")), request(calculatePath("some_path_three")) ); verifyRequestsMatches( new HttpRequestSerializer(new MockServerLogger()).deserializeArray(mockServerClient.retrieveRecordedRequests(request(), Format.JSON)), request(calculatePath("some_path_one")), request(calculatePath("not_found")), request(calculatePath("some_path_three")) ); verifyRequestsMatches( new HttpRequestSerializer(new MockServerLogger()).deserializeArray(mockServerClient.retrieveRecordedRequests(null, Format.JSON)), request(calculatePath("some_path_one")), request(calculatePath("not_found")), request(calculatePath("some_path_three")) ); } @Test public void shouldRetrieveRecordedRequestsAsLogEntries() throws IOException { // when mockServerClient.when(request().withPath(calculatePath("some_path.*")), exactly(4)).respond(response().withBody("some_body")); assertEquals( response("some_body"), makeRequest( request().withPath(calculatePath("some_path_one")), headersToIgnore) ); assertEquals( notFoundResponse(), makeRequest( request().withPath(calculatePath("not_found")), headersToIgnore) ); assertEquals( response("some_body"), makeRequest( request().withPath(calculatePath("some_path_three")), headersToIgnore) ); final ObjectMapper objectMapper = ObjectMapperFactory.createObjectMapper(); final JsonArraySerializer jsonArraySerializer = new JsonArraySerializer(); // then List<String> logEntries = jsonArraySerializer.returnJSONObjects(mockServerClient.retrieveRecordedRequests(request().withPath(calculatePath("some_path.*")), Format.LOG_ENTRIES)); assertThat(logEntries.size(), is(2)); HashMap itemOne = objectMapper.readValue(logEntries.get(0), HashMap.class); assertThat(new ArrayList<String>(itemOne.keySet()), containsInAnyOrder("httpRequest", "timestamp", "expectation")); assertThat(String.valueOf(((LinkedHashMap) itemOne.get("httpRequest")).get("path")), is(calculatePath("some_path_one"))); HashMap itemTwo = objectMapper.readValue(logEntries.get(1), HashMap.class); assertThat(new ArrayList<String>(itemTwo.keySet()), containsInAnyOrder("httpRequest", "timestamp", "expectation")); assertThat(String.valueOf(((LinkedHashMap) itemTwo.get("httpRequest")).get("path")), is(calculatePath("some_path_three"))); logEntries = jsonArraySerializer.returnJSONObjects(mockServerClient.retrieveRecordedRequests(request(), Format.LOG_ENTRIES)); assertThat(logEntries.size(), is(3)); itemOne = objectMapper.readValue(logEntries.get(0), HashMap.class); assertThat(new ArrayList<String>(itemOne.keySet()), containsInAnyOrder("httpRequest", "timestamp", "expectation")); assertThat(String.valueOf(((LinkedHashMap) itemOne.get("httpRequest")).get("path")), is(calculatePath("some_path_one"))); itemTwo = objectMapper.readValue(logEntries.get(1), HashMap.class); assertThat(itemTwo.containsKey("expectation"), is(false)); assertThat(new ArrayList<String>(itemTwo.keySet()), containsInAnyOrder("httpRequest", "timestamp")); assertThat(String.valueOf(((LinkedHashMap) itemTwo.get("httpRequest")).get("path")), is(calculatePath("not_found"))); HashMap itemThree = objectMapper.readValue(logEntries.get(2), HashMap.class); assertThat(new ArrayList<String>(itemThree.keySet()), containsInAnyOrder("httpRequest", "timestamp", "expectation")); assertThat(String.valueOf(((LinkedHashMap) itemThree.get("httpRequest")).get("path")), is(calculatePath("some_path_three"))); logEntries = jsonArraySerializer.returnJSONObjects(mockServerClient.retrieveRecordedRequests(null, Format.LOG_ENTRIES)); assertThat(logEntries.size(), is(3)); itemOne = objectMapper.readValue(logEntries.get(0), HashMap.class); assertThat(new ArrayList<String>(itemOne.keySet()), containsInAnyOrder("httpRequest", "timestamp", "expectation")); assertThat(String.valueOf(((LinkedHashMap) itemOne.get("httpRequest")).get("path")), is(calculatePath("some_path_one"))); itemTwo = objectMapper.readValue(logEntries.get(1), HashMap.class); assertThat(itemTwo.containsKey("expectation"), is(false)); assertThat(new ArrayList<String>(itemTwo.keySet()), containsInAnyOrder("httpRequest", "timestamp")); assertThat(String.valueOf(((LinkedHashMap) itemTwo.get("httpRequest")).get("path")), is(calculatePath("not_found"))); itemThree = objectMapper.readValue(logEntries.get(2), HashMap.class); assertThat(new ArrayList<String>(itemThree.keySet()), containsInAnyOrder("httpRequest", "timestamp", "expectation")); assertThat(String.valueOf(((LinkedHashMap) itemThree.get("httpRequest")).get("path")), is(calculatePath("some_path_three"))); } @Test public void shouldRetrieveActiveExpectationsAsJson() { // when mockServerClient.when(request().withPath(calculatePath("some_path.*")), exactly(4)) .respond(response().withBody("some_body")); mockServerClient.when(request().withPath(calculatePath("some_path.*"))) .respond(response().withBody("some_body")); mockServerClient.when(request().withPath(calculatePath("some_other_path"))) .respond(response().withBody("some_other_body")); mockServerClient.when(request().withPath(calculatePath("some_forward_path"))) .forward(forward()); // then assertThat( mockServerClient.retrieveActiveExpectations(request().withPath(calculatePath("some_path.*")), Format.JSON), is(new ExpectationSerializer(new MockServerLogger()).serialize(Arrays.asList( new Expectation(request().withPath(calculatePath("some_path.*")), exactly(4), TimeToLive.unlimited()) .thenRespond(response().withBody("some_body")), new Expectation(request().withPath(calculatePath("some_path.*"))) .thenRespond(response().withBody("some_body")) ))) ); assertThat( mockServerClient.retrieveActiveExpectations(null, Format.JSON), is(new ExpectationSerializer(new MockServerLogger()).serialize(Arrays.asList( new Expectation(request().withPath(calculatePath("some_path.*")), exactly(4), TimeToLive.unlimited()) .thenRespond(response().withBody("some_body")), new Expectation(request().withPath(calculatePath("some_path.*"))) .thenRespond(response().withBody("some_body")), new Expectation(request().withPath(calculatePath("some_other_path"))) .thenRespond(response().withBody("some_other_body")), new Expectation(request().withPath(calculatePath("some_forward_path"))) .thenForward(forward()) ))) ); assertThat( mockServerClient.retrieveActiveExpectations(request(), Format.JSON), is(new ExpectationSerializer(new MockServerLogger()).serialize(Arrays.asList( new Expectation(request().withPath(calculatePath("some_path.*")), exactly(4), TimeToLive.unlimited()) .thenRespond(response().withBody("some_body")), new Expectation(request().withPath(calculatePath("some_path.*"))) .thenRespond(response().withBody("some_body")), new Expectation(request().withPath(calculatePath("some_other_path"))) .thenRespond(response().withBody("some_other_body")), new Expectation(request().withPath(calculatePath("some_forward_path"))) .thenForward(forward()) ))) ); } @Test public void shouldRetrieveActiveExpectationsAsJava() { // when mockServerClient.when(request().withPath(calculatePath("some_path.*")), exactly(4)) .respond(response().withBody("some_body")); mockServerClient.when(request().withPath(calculatePath("some_path.*"))) .respond(response().withBody("some_body")); mockServerClient.when(request().withPath(calculatePath("some_other_path"))) .respond(response().withBody("some_other_body")); mockServerClient.when(request().withPath(calculatePath("some_forward_path"))) .forward(forward()); // then assertThat( mockServerClient.retrieveActiveExpectations(request().withPath(calculatePath("some_path.*")), Format.JAVA), is(new ExpectationToJavaSerializer().serialize(Arrays.asList( new Expectation(request().withPath(calculatePath("some_path.*")), exactly(4), TimeToLive.unlimited()) .thenRespond(response().withBody("some_body")), new Expectation(request().withPath(calculatePath("some_path.*"))) .thenRespond(response().withBody("some_body")) ))) ); assertThat( mockServerClient.retrieveActiveExpectations(null, Format.JAVA), is(new ExpectationToJavaSerializer().serialize(Arrays.asList( new Expectation(request().withPath(calculatePath("some_path.*")), exactly(4), TimeToLive.unlimited()) .thenRespond(response().withBody("some_body")), new Expectation(request().withPath(calculatePath("some_path.*"))) .thenRespond(response().withBody("some_body")), new Expectation(request().withPath(calculatePath("some_other_path"))) .thenRespond(response().withBody("some_other_body")), new Expectation(request().withPath(calculatePath("some_forward_path"))) .thenForward(forward()) ))) ); assertThat( mockServerClient.retrieveActiveExpectations(request(), Format.JAVA), is(new ExpectationToJavaSerializer().serialize(Arrays.asList( new Expectation(request().withPath(calculatePath("some_path.*")), exactly(4), TimeToLive.unlimited()) .thenRespond(response().withBody("some_body")), new Expectation(request().withPath(calculatePath("some_path.*"))) .thenRespond(response().withBody("some_body")), new Expectation(request().withPath(calculatePath("some_other_path"))) .thenRespond(response().withBody("some_other_body")), new Expectation(request().withPath(calculatePath("some_forward_path"))) .thenForward(forward()) ))) ); } @Test public void shouldRetrieveRecordedExpectationsAsJson() { // when EchoServer secureEchoServer = new EchoServer(false); try { mockServerClient.when(request().withPath(calculatePath("some_path.*")), exactly(4)).forward( forward() .withHost("127.0.0.1") .withPort(secureEchoServer.getPort()) ); assertEquals( response("some_body_one"), makeRequest( request().withPath(calculatePath("some_path_one")).withBody("some_body_one"), headersToIgnore ) ); assertEquals( response("some_body_three"), makeRequest( request().withPath(calculatePath("some_path_three")).withBody("some_body_three"), headersToIgnore ) ); // then Expectation[] recordedExpectations = new ExpectationSerializer(new MockServerLogger()).deserializeArray( mockServerClient.retrieveRecordedExpectations(request().withPath(calculatePath("some_path_one")), Format.JSON) ); assertThat(recordedExpectations.length, is(1)); verifyRequestsMatches( new HttpRequest[]{ recordedExpectations[0].getHttpRequest() }, request(calculatePath("some_path_one")).withBody("some_body_one") ); assertThat(recordedExpectations[0].getHttpResponse().getBodyAsString(), is("some_body_one")); // and recordedExpectations = new ExpectationSerializer(new MockServerLogger()).deserializeArray( mockServerClient.retrieveRecordedExpectations(request(), Format.JSON) ); assertThat(recordedExpectations.length, is(2)); verifyRequestsMatches( new HttpRequest[]{ recordedExpectations[0].getHttpRequest(), recordedExpectations[1].getHttpRequest() }, request(calculatePath("some_path_one")).withBody("some_body_one"), request(calculatePath("some_path_three")).withBody("some_body_three") ); assertThat(recordedExpectations[0].getHttpResponse().getBodyAsString(), is("some_body_one")); assertThat(recordedExpectations[1].getHttpResponse().getBodyAsString(), is("some_body_three")); // and recordedExpectations = new ExpectationSerializer(new MockServerLogger()).deserializeArray( mockServerClient.retrieveRecordedExpectations(null, Format.JSON) ); assertThat(recordedExpectations.length, is(2)); verifyRequestsMatches( new HttpRequest[]{ recordedExpectations[0].getHttpRequest(), recordedExpectations[1].getHttpRequest() }, request(calculatePath("some_path_one")).withBody("some_body_one"), request(calculatePath("some_path_three")).withBody("some_body_three") ); assertThat(recordedExpectations[0].getHttpResponse().getBodyAsString(), is("some_body_one")); assertThat(recordedExpectations[1].getHttpResponse().getBodyAsString(), is("some_body_three")); } finally { secureEchoServer.stop(); } } @Test public void shouldClearExpectationsOnly() { // given - some expectations mockServerClient .when( request() .withPath(calculatePath("some_path1")) ) .respond( response() .withBody("some_body1") ); mockServerClient .when( request() .withPath(calculatePath("some_path2")) ) .respond( response() .withBody("some_body2") ); // and - some matching requests assertEquals( response() .withStatusCode(OK_200.code()) .withReasonPhrase(OK_200.reasonPhrase()) .withBody("some_body1"), makeRequest( request() .withPath(calculatePath("some_path1")), headersToIgnore) ); assertEquals( response() .withStatusCode(OK_200.code()) .withReasonPhrase(OK_200.reasonPhrase()) .withBody("some_body2"), makeRequest( request() .withPath(calculatePath("some_path2")), headersToIgnore) ); // when mockServerClient .clear( request() .withPath(calculatePath("some_path1")), ClearType.EXPECTATIONS ); // then - expectations cleared assertThat( mockServerClient.retrieveActiveExpectations(null), arrayContaining( new Expectation(request() .withPath(calculatePath("some_path2"))) .thenRespond( response() .withBody("some_body2") ) ) ); // and then - request log not cleared verifyRequestsMatches( mockServerClient.retrieveRecordedRequests(null), request(calculatePath("some_path1")), request(calculatePath("some_path2")) ); } @Test public void shouldClearLogsOnly() { // given - some expectations mockServerClient .when( request() .withPath(calculatePath("some_path1")) ) .respond( response() .withBody("some_body1") ); mockServerClient .when( request() .withPath(calculatePath("some_path2")) ) .respond( response() .withBody("some_body2") ); // and - some matching requests assertEquals( response() .withStatusCode(OK_200.code()) .withReasonPhrase(OK_200.reasonPhrase()) .withBody("some_body1"), makeRequest( request() .withPath(calculatePath("some_path1")), headersToIgnore) ); assertEquals( response() .withStatusCode(OK_200.code()) .withReasonPhrase(OK_200.reasonPhrase()) .withBody("some_body2"), makeRequest( request() .withPath(calculatePath("some_path2")), headersToIgnore) ); // when mockServerClient .clear( request() .withPath(calculatePath("some_path1")), ClearType.LOG ); // then - expectations cleared assertThat( mockServerClient.retrieveActiveExpectations(null), arrayContaining( new Expectation(request() .withPath(calculatePath("some_path1"))) .thenRespond( response() .withBody("some_body1") ), new Expectation(request() .withPath(calculatePath("some_path2"))) .thenRespond( response() .withBody("some_body2") ) ) ); // and then - request log cleared verifyRequestsMatches( mockServerClient.retrieveRecordedRequests(null), request(calculatePath("some_path2")) ); } @Test public void shouldClearAllExpectationsWithNull() { // given mockServerClient .when( request() .withPath(calculatePath("some_path1")) ) .respond( response() .withBody("some_body1") ); mockServerClient .when( request() .withPath(calculatePath("some_path2")) ) .respond( response() .withBody("some_body2") ); assertEquals( response() .withStatusCode(OK_200.code()) .withReasonPhrase(OK_200.reasonPhrase()) .withBody("some_body2"), makeRequest( request() .withPath(calculatePath("some_path2")), headersToIgnore) ); // when mockServerClient.clear(null); // then assertThat(mockServerClient.retrieveActiveExpectations(null), emptyArray()); assertThat(mockServerClient.retrieveRecordedRequests(null), emptyArray()); } @Test public void shouldClearAllExpectationsWithEmptyRequest() { // given mockServerClient .when( request() .withPath(calculatePath("some_path1")) ) .respond( response() .withBody("some_body1") ); mockServerClient .when( request() .withPath(calculatePath("some_path2")) ) .respond( response() .withBody("some_body2") ); assertEquals( response() .withStatusCode(OK_200.code()) .withReasonPhrase(OK_200.reasonPhrase()) .withBody("some_body2"), makeRequest( request() .withPath(calculatePath("some_path2")), headersToIgnore) ); // when mockServerClient.clear(request()); // then assertThat(mockServerClient.retrieveActiveExpectations(null), emptyArray()); assertThat(mockServerClient.retrieveRecordedRequests(null), emptyArray()); } @Test public void shouldClearExpectationsWithXPathBody() { // given mockServerClient .when( request() .withBody(xpath("/bookstore/book[year=2005]/price")) ) .respond( response() .withBody("some_body1") ); mockServerClient .when( request() .withBody(xpath("/bookstore/book[year=2006]/price")) ) .respond( response() .withBody("some_body2") ); // and StringBody xmlBody = new StringBody("" + "<?xml version=\"1.0\" encoding=\"ISO-8859-1\"?>" + NEW_LINE + "<bookstore>" + NEW_LINE + " <book category=\"COOKING\">" + NEW_LINE + " <title lang=\"en\">Everyday Italian</title>" + NEW_LINE + " <author>Giada De Laurentiis</author>" + NEW_LINE + " <year>2005</year>" + NEW_LINE + " <price>30.00</price>" + NEW_LINE + " </book>" + NEW_LINE + " <book category=\"CHILDREN\">" + NEW_LINE + " <title lang=\"en\">Harry Potter</title>" + NEW_LINE + " <author>J K. Rowling</author>" + NEW_LINE + " <year>2006</year>" + NEW_LINE + " <price>29.99</price>" + NEW_LINE + " </book>" + NEW_LINE + " <book category=\"WEB\">" + NEW_LINE + " <title lang=\"en\">Learning XML</title>" + NEW_LINE + " <author>Erik T. Ray</author>" + NEW_LINE + " <year>2003</year>" + NEW_LINE + " <price>31.95</price>" + NEW_LINE + " </book>" + NEW_LINE + "</bookstore>"); // then assertEquals( response() .withStatusCode(OK_200.code()) .withReasonPhrase(OK_200.reasonPhrase()) .withBody("some_body1"), makeRequest( request() .withBody(xmlBody), headersToIgnore) ); // when mockServerClient .clear( request() .withBody(xpath("/bookstore/book[year=2005]/price")) ); // then assertThat( mockServerClient.retrieveActiveExpectations(null), arrayContaining( new Expectation(request() .withBody(xpath("/bookstore/book[year=2006]/price"))) .thenRespond( response() .withBody("some_body2") ) ) ); // - in http assertEquals( response() .withStatusCode(OK_200.code()) .withReasonPhrase(OK_200.reasonPhrase()) .withBody("some_body2"), makeRequest( request() .withBody(xmlBody), headersToIgnore) ); // - in https assertEquals( response() .withStatusCode(OK_200.code()) .withReasonPhrase(OK_200.reasonPhrase()) .withBody("some_body2"), makeRequest( request() .withSecure(true) .withBody(xmlBody), headersToIgnore) ); } @Test public void shouldClearExpectationsWithJsonSchemaBody() { // given JsonSchemaBody jsonSchemaBodyOne = jsonSchema("{" + NEW_LINE + " \"$schema\": \"http://json-schema.org/draft-04/schema#\"," + NEW_LINE + " \"title\": \"Product\"," + NEW_LINE + " \"description\": \"A product from Acme's catalog\"," + NEW_LINE + " \"type\": \"object\"," + NEW_LINE + " \"properties\": {" + NEW_LINE + " \"id\": {" + NEW_LINE + " \"description\": \"The unique identifier for a product\"," + NEW_LINE + " \"type\": \"integer\"" + NEW_LINE + " }," + NEW_LINE + " \"name\": {" + NEW_LINE + " \"description\": \"Name of the product\"," + NEW_LINE + " \"type\": \"string\"" + NEW_LINE + " }," + NEW_LINE + " \"price\": {" + NEW_LINE + " \"type\": \"number\"," + NEW_LINE + " \"minimum\": 0," + NEW_LINE + " \"exclusiveMinimum\": true" + NEW_LINE + " }," + NEW_LINE + " \"tags\": {" + NEW_LINE + " \"type\": \"array\"," + NEW_LINE + " \"items\": {" + NEW_LINE + " \"type\": \"string\"" + NEW_LINE + " }," + NEW_LINE + " \"minItems\": 1," + NEW_LINE + " \"uniqueItems\": true" + NEW_LINE + " }" + NEW_LINE + " }," + NEW_LINE + " \"required\": [\"id\", \"name\", \"price\"]" + NEW_LINE + "}"); JsonSchemaBody jsonSchemaBodyTwo = jsonSchema("{" + NEW_LINE + " \"$schema\": \"http://json-schema.org/draft-04/schema#\"," + NEW_LINE + " \"title\": \"Product\"," + NEW_LINE + " \"description\": \"A product from Acme's catalog\"," + NEW_LINE + " \"type\": \"object\"," + NEW_LINE + " \"properties\": {" + NEW_LINE + " \"id\": {" + NEW_LINE + " \"description\": \"The unique identifier for a product\"," + NEW_LINE + " \"type\": \"integer\"" + NEW_LINE + " }," + NEW_LINE + " \"name\": {" + NEW_LINE + " \"description\": \"Name of the product\"," + NEW_LINE + " \"type\": \"string\"" + NEW_LINE + " }," + NEW_LINE + " \"price\": {" + NEW_LINE + " \"type\": \"number\"," + NEW_LINE + " \"minimum\": 10," + NEW_LINE + " \"exclusiveMinimum\": true" + NEW_LINE + " }," + NEW_LINE + " \"tags\": {" + NEW_LINE + " \"type\": \"array\"," + NEW_LINE + " \"items\": {" + NEW_LINE + " \"type\": \"string\"" + NEW_LINE + " }," + NEW_LINE + " \"minItems\": 1," + NEW_LINE + " \"uniqueItems\": true" + NEW_LINE + " }" + NEW_LINE + " }," + NEW_LINE + " \"required\": [\"id\", \"name\", \"price\"]" + NEW_LINE + "}"); mockServerClient .when( request() .withBody(jsonSchemaBodyOne) ) .respond( response() .withBody("some_body1") ); mockServerClient .when( request() .withBody(jsonSchemaBodyTwo) ) .respond( response() .withBody("some_body2") ); // then assertEquals( response() .withStatusCode(OK_200.code()) .withReasonPhrase(OK_200.reasonPhrase()) .withBody("some_body1"), makeRequest( request() .withBody("{" + NEW_LINE + " \"id\": 1," + NEW_LINE + " \"name\": \"A green door\"," + NEW_LINE + " \"price\": 12.50," + NEW_LINE + " \"tags\": [\"home\", \"green\"]" + NEW_LINE + "}"), headersToIgnore) ); // when mockServerClient .clear( request() .withBody(jsonSchemaBodyOne) ); // then assertThat( mockServerClient.retrieveActiveExpectations(null), arrayContaining( new Expectation(request() .withBody(jsonSchemaBodyTwo)) .thenRespond( response() .withBody("some_body2") ) ) ); // - in http assertEquals( response() .withStatusCode(OK_200.code()) .withReasonPhrase(OK_200.reasonPhrase()) .withBody("some_body2"), makeRequest( request() .withBody("{" + NEW_LINE + " \"id\": 1," + NEW_LINE + " \"name\": \"A green door\"," + NEW_LINE + " \"price\": 12.50," + NEW_LINE + " \"tags\": [\"home\", \"green\"]" + NEW_LINE + "}"), headersToIgnore) ); // - in https assertEquals( response() .withStatusCode(OK_200.code()) .withReasonPhrase(OK_200.reasonPhrase()) .withBody("some_body2"), makeRequest( request() .withSecure(true) .withBody("{" + NEW_LINE + " \"id\": 1," + NEW_LINE + " \"name\": \"A green door\"," + NEW_LINE + " \"price\": 12.50," + NEW_LINE + " \"tags\": [\"home\", \"green\"]" + NEW_LINE + "}"), headersToIgnore) ); } @Test public void shouldClearExpectationsWithParameterBody() { // given mockServerClient .when( request() .withBody(params(param("bodyParameterNameOne", "bodyParameterValueOne"))) ) .respond( response() .withBody("some_body1") ); mockServerClient .when( request() .withBody(params(param("bodyParameterNameTwo", "bodyParameterValueTwo"))) ) .respond( response() .withBody("some_body2") ); // then assertEquals( response() .withStatusCode(OK_200.code()) .withReasonPhrase(OK_200.reasonPhrase()) .withBody("some_body1"), makeRequest( request() .withBody(params(param("bodyParameterName.*", "bodyParameterValue.*"))), headersToIgnore) ); // when mockServerClient .clear( request() .withBody(params(param("bodyParameterNameOne", "bodyParameterValueOne"))) ); // then assertThat( mockServerClient.retrieveActiveExpectations(null), arrayContaining( new Expectation(request() .withBody(params(param("bodyParameterNameTwo", "bodyParameterValueTwo")))) .thenRespond( response() .withBody("some_body2") ) ) ); // - in http assertEquals( response() .withStatusCode(OK_200.code()) .withReasonPhrase(OK_200.reasonPhrase()) .withBody("some_body2"), makeRequest( request() .withBody(params(param("bodyParameterName.*", "bodyParameterValue.*"))), headersToIgnore) ); // - in https assertEquals( response() .withStatusCode(OK_200.code()) .withReasonPhrase(OK_200.reasonPhrase()) .withBody("some_body2"), makeRequest( request() .withSecure(true) .withBody(params(param("bodyParameterName.*", "bodyParameterValue.*"))), headersToIgnore) ); } @Test public void shouldEnsureThatInterruptedRequestsAreVerifiable() throws Exception { mockServerClient .when( request(calculatePath("delayed")) ) .respond( response("delayed data") .withDelay(new Delay(TimeUnit.SECONDS, 3)) ); Future<HttpResponse> delayedFuture = Executors.newSingleThreadExecutor().submit(new Callable<HttpResponse>() { @Override public HttpResponse call() throws Exception { return httpClient.sendRequest( request(addContextToPath(calculatePath("delayed"))) .withHeader(HOST.toString(), "localhost:" + getServerPort()) ).get(10, TimeUnit.SECONDS); } }); Uninterruptibles.sleepUninterruptibly(1, TimeUnit.SECONDS); // Let request reach server delayedFuture.cancel(true); // Then interrupt requesting thread mockServerClient.verify(request(calculatePath("delayed"))); // We should be able to verify request that reached server even though its later interrupted } @Test public void shouldEnsureThatRequestDelaysDoNotAffectOtherRequests() throws Exception { mockServerClient .when( request("/slow") ) .respond( response("super slow") .withDelay(new Delay(TimeUnit.SECONDS, 5)) ); mockServerClient .when( request("/fast") ) .respond( response("quite fast") ); ExecutorService executorService = Executors.newFixedThreadPool(2); Future<Long> slowFuture = executorService.submit(new Callable<Long>() { @Override public Long call() throws Exception { long start = System.currentTimeMillis(); makeRequest(request("/slow"), Collections.<String>emptySet()); return System.currentTimeMillis() - start; } }); // Let fast request come to the server slightly after slow request Uninterruptibles.sleepUninterruptibly(1, TimeUnit.SECONDS); Future<Long> fastFuture = executorService.submit(new Callable<Long>() { @Override public Long call() throws Exception { long start = System.currentTimeMillis(); makeRequest(request("/fast"), Collections.<String>emptySet()); return System.currentTimeMillis() - start; } }); Long slowRequestElapsedMillis = slowFuture.get(); Long fastRequestElapsedMillis = fastFuture.get(); assertThat("Slow request takes less than expected", slowRequestElapsedMillis, is(greaterThan(5 * 1000L))); assertThat("Fast request takes longer than expected", fastRequestElapsedMillis, is(lessThan(5 * 1000L))); } }
stepanataccolade/mockserver
mockserver-integration-testing/src/main/java/org/mockserver/integration/server/AbstractExtendedMockingIntegrationTest.java
929
package gr.cti.eslate.base.container; import java.util.ListResourceBundle; public class BeanInfoDialogBundle_el_GR extends ListResourceBundle { public Object [][] getContents() { return contents; } static final Object[][] contents={ {"DialogTitle", "Ιδιότητες"}, {"Microworld", "Μικρόκοσμος"}, {"Close", "Κλείσιμο"}, {"NoComponent", "Καμία ενεργή ψηφίδα"}, {"ObjectHierachy", "Ιεραρχία αντικειμένων"}, {"UIHierachy", "Ιεραρχία user interface αντικειμένων"}, {"ComponentHierachy", "Ιεραρχία ψηφίδων"}, {"Properties", "Ιδιότητες"}, {"Refresh", "Ανανέωση"}, {"Edit", "Επεξεργασία"}, {"Add", "Προσθήκη ψηφίδας"}, {"Remove", "Αφαίρεση ψηδίδας"}, {"Properties", "Ιδιότητες"}, {"Events", "Γεγονότα"}, {"BorderLayoutPos", "Επιλογή θέσης ψηφίδας"}, {"BorderLayoutTitle", "Θέση ψηφίδας"}, {"Settings", "Ρυθμίσεις"}, {"PropertyType", "Τύπος"}, {"ReadWrite", "Μεταβαλλόμενες"}, {"ReadOnly", "Μη μεταβαλλόμενες"}, {"All", "Όλες"}, {"Expert", "Για έμπειρους"}, {"Basic", "Βασικές"}, {"Preferred", "Προτεινόμενες"}, {"Bound", "Εξαρτημένες"}, {"Constrained", "Υπό περιορισμό"}, {"Hidden", "Κρυφές"}, {"Error", "Λάθος"}, {"CustomizerMenu", "Προσαρμοστής..."}, {"Customizer", "Προσαρμοστής"}, {"Customizer1", "Ο προσαρμοστής δεν είναι ορατός. Ένας χρήσιμος προσαρμοστής πρέπει οπωσδήποτε να είναι ορατός."}, {"Customizer2", "Ο συγκεκριμένος προσαρμοστής δεν υλοποιεί το \"java.beans.Customizer\" interface."}, {"Customizer3", "Αδύνατη η αρχικοποίηση του προσαρμοστή"}, {"Message1", "Δεν είναι δυνατή η δημιουργία ψηφίδας της κλάσσης \""}, {"Message2", "Δεν στάθηκε δυνατή η δημιουργία της ψηφίδας."}, {"Message3", "Δεν επιλέχτηκε κάποια ψηφίδα."}, {"Message4", "Υποστηρίζεται η δημιουργία μόνο ορατών ψηφίδων."}, {"Sounds", "Ήχοι"}, {"Bounds", "Όρια"}, {"BoundsTip", "Δώστε τα όρια τής ψηφίδας"}, {"Location", "Θέση"}, {"LocationTip", "Δώστε τη θέση τής ψηφίδας"}, }; }
vpapakir/myeslate
widgetESlate/src/gr/cti/eslate/base/container/BeanInfoDialogBundle_el_GR.java
931
/* * Copyright (c) 2017, salesforce.com, inc. * All rights reserved. * Licensed under the BSD 3-Clause license. * For full license text, see LICENSE.txt file in the repo root or https://opensource.org/licenses/BSD-3-Clause */ package com.force.i18n.grammar.impl; import static com.force.i18n.commons.util.settings.IniFileUtil.intern; import java.util.*; import java.util.logging.Logger; import com.force.i18n.HumanLanguage; import com.force.i18n.commons.text.TrieMatcher; import com.force.i18n.grammar.*; import com.force.i18n.grammar.Noun.NounType; import com.google.common.collect.ImmutableMap; /** * Greek is *not* germanic, but it's close enough for salesforce work. * TODO: This really should be a separate declension from germanic, because only greek has a starts with that's interesting. * * @author stamm */ class GreekDeclension extends GermanicDeclension { private static final Logger logger = Logger.getLogger(GreekDeclension.class.getName()); private final Map<ArticleForm,String> indefiniteOverrides; private final Map<ArticleForm,String> definiteOverrides; public GreekDeclension(HumanLanguage language) { super(language); // Setup the map for "plosive endings" definiteOverrides = ImmutableMap.<ArticleForm, String>of( getArticleForm(LanguageStartsWith.SPECIAL, LanguageGender.MASCULINE, LanguageNumber.SINGULAR, LanguageCase.ACCUSATIVE), "\u03c4\u03bf\u03bd", // τον getArticleForm(LanguageStartsWith.SPECIAL, LanguageGender.FEMININE, LanguageNumber.SINGULAR, LanguageCase.ACCUSATIVE), "\u03c4\u03b7\u03bd"); // την indefiniteOverrides = Collections.singletonMap( getArticleForm(LanguageStartsWith.SPECIAL, LanguageGender.MASCULINE, LanguageNumber.SINGULAR, LanguageCase.ACCUSATIVE), "\u03ad\u03bd\u03b1\u03bd"); // έναν } private final Map<LanguageCase, ImmutableMap<LanguageNumber, ImmutableMap<LanguageGender,String>>> DEFINITE_ARTICLE = ImmutableMap.of( LanguageCase.NOMINATIVE, ImmutableMap.of(LanguageNumber.SINGULAR, ImmutableMap.of( LanguageGender.NEUTER, "\u03c4\u03bf", // το LanguageGender.FEMININE, "\u03b7", // η LanguageGender.MASCULINE, "\u03bf" // ο ), LanguageNumber.PLURAL, ImmutableMap.of( LanguageGender.NEUTER, "\u03c4\u03b1", // τα LanguageGender.FEMININE, "\u03bf\u03b9", // οι LanguageGender.MASCULINE, "\u03bf\u03b9" // οι )), LanguageCase.ACCUSATIVE, ImmutableMap.of(LanguageNumber.SINGULAR, ImmutableMap.of( LanguageGender.NEUTER, "\u03c4\u03bf", // το LanguageGender.FEMININE, "\u03c4\u03b7", // τη(ν) LanguageGender.MASCULINE, "\u03c4\u03bf" // το(ν) ), LanguageNumber.PLURAL, ImmutableMap.of( LanguageGender.NEUTER, "\u03c4\u03b1", // τα LanguageGender.FEMININE, "\u03c4\u03b9\u03c2", // τις LanguageGender.MASCULINE, "\u03c4\u03bf\u03c5\u03c2" // τους )), LanguageCase.GENITIVE, ImmutableMap.of(LanguageNumber.SINGULAR, ImmutableMap.of( LanguageGender.NEUTER, "\u03c4\u03bf\u03c5", // του LanguageGender.FEMININE, "\u03c4\u03b7\u03c2", // της LanguageGender.MASCULINE, "\u03c4\u03bf\u03c5" // του ), LanguageNumber.PLURAL, ImmutableMap.of( LanguageGender.NEUTER, "\u03c4\u03c9\u03bd", // των LanguageGender.FEMININE, "\u03c4\u03c9\u03bd", // των LanguageGender.MASCULINE, "\u03c4\u03c9\u03bd" // των )) ); private static final Map<LanguageCase, ImmutableMap<LanguageGender, String>> INDEFINITE_ARTICLE = ImmutableMap.of( LanguageCase.NOMINATIVE, ImmutableMap.of( LanguageGender.NEUTER, "\u03ad\u03bd\u03b1", // ένα LanguageGender.FEMININE, "\u03bc\u03af\u03b1", // μία LanguageGender.MASCULINE, "\u03ad\u03bd\u03b1\u03c2" // ένας ), LanguageCase.ACCUSATIVE, ImmutableMap.of( LanguageGender.NEUTER, "\u03ad\u03bd\u03b1", // ένα LanguageGender.FEMININE, "\u03bc\u03af\u03b1", // μία LanguageGender.MASCULINE, "\u03ad\u03bd\u03b1" // ένα(ν) ), LanguageCase.GENITIVE, ImmutableMap.of( LanguageGender.NEUTER, "\u03b5\u03bd\u03cc\u03c2", // ενός LanguageGender.FEMININE, "\u03bc\u03b9\u03b1\u03c2", // μιας LanguageGender.MASCULINE, "\u03b5\u03bd\u03cc\u03c2" // ενός ) ); public static class GreekNoun extends GermanicNoun { /** * */ private static final long serialVersionUID = 1L; public GreekNoun(GermanicDeclension declension, String name, String pluralAlias, NounType type, String entityName, LanguageGender gender, String access, boolean isStandardField, boolean isCopied) { super(declension, name, pluralAlias, type, entityName, gender, access, isStandardField, isCopied); } @Override public void setString(String value, NounForm form) { super.setString(intern(value), form); if (form == getDeclension().getAllNounForms().get(0)) { setStartsWith(startsWithGreekPlosive(value) ? LanguageStartsWith.SPECIAL : LanguageStartsWith.CONSONANT); } } } @Override protected Noun createNoun(String name, String pluralAlias, NounType type, String entityName, LanguageStartsWith startsWith, LanguageGender gender, String access, boolean isStandardField, boolean isCopied) { return new GreekNoun(this, name, pluralAlias, type, entityName, gender, access, isStandardField, isCopied); } public static boolean startsWithGreekPlosive(String value) { return PLOSIVE_MATCHER.begins(value); } @Override protected EnumSet<LanguageArticle> getRequiredAdjectiveArticles() { return EnumSet.of(LanguageArticle.ZERO); // Greek adjectives are not inflected for definitiveness } @Override protected String getDefaultArticleString(ArticleForm form, LanguageArticle articleType) { switch (articleType) { case DEFINITE: String override = definiteOverrides.get(form); if (override != null) return override; ImmutableMap<LanguageNumber, ImmutableMap<LanguageGender,String>> byCase = DEFINITE_ARTICLE.get(form.getCase()); if (byCase == null) { logger.fine("Trying to retrieve an illegal definite article form in greek"); return ""; } return byCase.get(form.getNumber()).get(form.getGender()); case INDEFINITE: if (form.getNumber() == LanguageNumber.PLURAL) return null; override = indefiniteOverrides.get(form); if (override != null) return override; return INDEFINITE_ARTICLE.get(form.getCase()).get(form.getGender()); default: return null; } } @Override public boolean hasStartsWith() { return true; } // κ, π, τ, μπ, ντ, γκ, τσ, τζ, ξ, ψ private static final String[] PLOSIVES = new String[] {"\u03ba","\u03c0","\u03c4", "\u03bc\u03c0", "\u03bd\u03c4", "\u03b3\u03ba", "\u03c4\u03c3", "\u03c4\u03b6", "\u03be", "\u03c8"}; private static final TrieMatcher PLOSIVE_MATCHER = TrieMatcher.compile(PLOSIVES, PLOSIVES); @Override public boolean hasAutoDerivedStartsWith() { return true; } @Override public EnumSet<LanguageStartsWith> getRequiredStartsWith() { return EnumSet.of(LanguageStartsWith.CONSONANT, LanguageStartsWith.SPECIAL); // Special is plosive in greek. } @Override public EnumSet<LanguageCase> getRequiredCases() { return EnumSet.of(LanguageCase.NOMINATIVE, LanguageCase.ACCUSATIVE, LanguageCase.GENITIVE, LanguageCase.VOCATIVE); } @Override public EnumSet<LanguageGender> getRequiredGenders() { return EnumSet.of(LanguageGender.NEUTER, LanguageGender.FEMININE, LanguageGender.MASCULINE); } @Override public String formLowercaseNounForm(String s, NounForm form) { return hasCapitalization() ? (s == null ? null : s.toLowerCase()) : s; } }
seratch/grammaticus
src/main/java/com/force/i18n/grammar/impl/GreekDeclension.java
932
package com.aspectsense.greektools; import java.util.HashMap; import java.util.Map; import java.util.Set; import java.util.StringTokenizer; /** * Implements ISO 843 / ΕΛΟΤ 743 for the transliteration of Greek text to the Latin alphabet. * * @see <a href="https://en.wikipedia.org/wiki/ISO_843#1997_edition">ISO 843 on Wikipedia</a> * @see <a href="http://www.geonoma.gov.cy/index.php/typopoiisi/metagrafi-ellnikou-alfavitou"> * Metagrafi ellinikou alfavitou</a> * * @author Nearchos Paspallis * Created: 29-Mar-20 */ public class Greeklish { private static final Map<String, String> mappingBase = new HashMap<>(); private static final Map<String, String> mappingWithAccents = new HashMap<>(); private static final Map<String, String> exceptions = new HashMap<>(); private static final Map<String, String[]> exceptionsNotes_1_2 = new HashMap<>(); private static final Map<String, String> exceptionsWithAccents = new HashMap<>(); private static final Map<String, String[]> exceptionsWithAccentsNotes_1_2 = new HashMap<>(); private static final Map<String, String> exceptionsAllCaps = new HashMap<>(); static { mappingBase.put("Α", "A"); mappingBase.put("Ά", "A"); mappingBase.put("α", "a"); mappingBase.put("ά", "a"); mappingBase.put("Β", "V"); mappingBase.put("β", "v"); mappingBase.put("Γ", "G"); mappingBase.put("γ", "g"); mappingBase.put("Δ", "D"); mappingBase.put("δ", "d"); mappingBase.put("Ε", "E"); mappingBase.put("Έ", "E"); mappingBase.put("ε", "e"); mappingBase.put("έ", "e"); mappingBase.put("Ζ", "Z"); mappingBase.put("ζ", "z"); mappingBase.put("Η", "I"); mappingBase.put("Ή", "I"); mappingBase.put("η", "i"); mappingBase.put("ή", "i"); mappingBase.put("Θ", "Th"); mappingBase.put("θ", "th"); mappingBase.put("Ι", "I"); mappingBase.put("Ί", "I"); mappingBase.put("Ϊ", "I"); mappingBase.put("ι", "i"); mappingBase.put("ί", "i"); mappingBase.put("ϊ", "i"); mappingBase.put("ΐ", "i"); mappingBase.put("Κ", "K"); mappingBase.put("κ", "k"); mappingBase.put("Λ", "L"); mappingBase.put("λ", "l"); mappingBase.put("Μ", "M"); mappingBase.put("μ", "m"); mappingBase.put("Ν", "N"); mappingBase.put("ν", "n"); mappingBase.put("Ξ", "X"); mappingBase.put("ξ", "x"); mappingBase.put("Ο", "O"); mappingBase.put("Ό", "O"); mappingBase.put("ο", "o"); mappingBase.put("ό", "o"); mappingBase.put("Π", "P"); mappingBase.put("π", "p"); mappingBase.put("Ρ", "R"); mappingBase.put("ρ", "r"); mappingBase.put("Σ", "S"); mappingBase.put("σ", "s"); mappingBase.put("ς", "s"); mappingBase.put("Τ", "T"); mappingBase.put("τ", "t"); mappingBase.put("Υ", "Y"); mappingBase.put("Ύ", "Y"); mappingBase.put("Ϋ", "Y"); mappingBase.put("υ", "y"); mappingBase.put("ύ", "y"); mappingBase.put("ϋ", "y"); mappingBase.put("ΰ", "y"); mappingBase.put("Φ", "F"); mappingBase.put("φ", "f"); mappingBase.put("Χ", "Ch"); mappingBase.put("χ", "ch"); mappingBase.put("Ψ", "Ps"); mappingBase.put("ψ", "ps"); mappingBase.put("Ω", "O"); mappingBase.put("Ώ", "O"); mappingBase.put("ω", "o"); mappingBase.put("ώ", "o"); mappingBase.put(";", "?"); mappingWithAccents.put("Ά", "Á"); mappingWithAccents.put("ά", "á"); mappingWithAccents.put("Έ", "É"); mappingWithAccents.put("έ", "é"); mappingWithAccents.put("Η", "Ī"); mappingWithAccents.put("Ή", "Ī́"); mappingWithAccents.put("η", "ī"); mappingWithAccents.put("ή", "ī́"); mappingWithAccents.put("Ί", "Í"); mappingWithAccents.put("Ϊ", "Ï"); mappingWithAccents.put("ί", "í"); mappingWithAccents.put("ϊ", "ï"); mappingWithAccents.put("ΐ", "ḯ"); mappingWithAccents.put("Ό", "Ó"); mappingWithAccents.put("ό", "ó"); mappingWithAccents.put("Ύ", "Ý"); mappingWithAccents.put("Ϋ", "Ÿ"); mappingWithAccents.put("ύ", "ý"); mappingWithAccents.put("ϋ", "ÿ"); mappingWithAccents.put("ΰ", "ÿ́"); mappingWithAccents.put("Ω", "Ō"); mappingWithAccents.put("Ώ", "Ṓ"); mappingWithAccents.put("ω", "ō"); mappingWithAccents.put("ώ", "ṓ"); // e.g. av "before vowels or voiced consonants" and af "before voiceless consonants and word-finally" exceptionsNotes_1_2.put("ΑΥ", new String [] {"AV", "AF"}); exceptionsNotes_1_2.put("Αυ", new String [] {"Av", "Af"}); exceptionsNotes_1_2.put("αυ", new String [] {"av", "af"}); exceptionsNotes_1_2.put("ΑΎ", new String [] {"AV", "AF"}); exceptionsNotes_1_2.put("Αύ", new String [] {"Av", "Af"}); exceptionsNotes_1_2.put("αύ", new String [] {"av", "af"}); exceptionsNotes_1_2.put("ΕΥ", new String [] {"EV", "EF"}); exceptionsNotes_1_2.put("Ευ", new String [] {"Ev", "Ef"}); exceptionsNotes_1_2.put("ευ", new String [] {"ev", "ef"}); exceptionsNotes_1_2.put("ΕΎ", new String [] {"EV", "EF"}); exceptionsNotes_1_2.put("Εύ", new String [] {"Ev", "Ef"}); exceptionsNotes_1_2.put("εύ", new String [] {"ev", "ef"}); exceptions.put("ΟΥ", "OU"); exceptions.put("Ου", "Ou"); exceptions.put("ου", "ou"); exceptions.put("ΟΎ", "OU"); exceptions.put("Ού", "Ou"); exceptions.put("ού", "ou"); exceptions.put("ΓΓ", "NG"); exceptions.put("Γγ", "Ng"); exceptions.put("γγ", "ng"); exceptions.put("ΓΚ", "GK"); exceptions.put("Γκ", "Gk"); exceptions.put("γκ", "gk"); exceptions.put("ΓΞ", "NX"); exceptions.put("Γξ", "Nx"); exceptions.put("γξ", "nx"); exceptions.put("ΓΧ", "NCH"); exceptions.put("Γχ", "Nch"); exceptions.put("γχ", "nch"); exceptions.put("ΝΤ", "NT"); exceptions.put("Ντ", "Nt"); exceptions.put("ντ", "nt"); // e.g. áv "before vowels or voiced consonants" and áf "before voiceless consonants and word-finally" exceptionsWithAccentsNotes_1_2.put("ΑΎ", new String [] {"ÁV", "ÁF"}); exceptionsWithAccentsNotes_1_2.put("Αύ", new String [] {"Áv", "Áf"}); exceptionsWithAccentsNotes_1_2.put("αύ", new String [] {"áv", "áf"}); exceptionsWithAccentsNotes_1_2.put("ΕΎ", new String [] {"ÉV", "ÉF"}); exceptionsWithAccentsNotes_1_2.put("Εύ", new String [] {"Év", "Éf"}); exceptionsWithAccentsNotes_1_2.put("εύ", new String [] {"év", "éf"}); exceptionsWithAccents.put("ΟΎ", "OÚ"); exceptionsWithAccents.put("Ού", "Oú"); exceptionsWithAccents.put("ού", "oú"); exceptionsAllCaps.put("Θ", "TH"); exceptionsAllCaps.put("Χ", "CH"); exceptionsAllCaps.put("Ψ", "PS"); } private static final String ALL_GREEK_UPPERCASE_LETTERS = "ΑΆΒΓΔΕΈΖΗΉΘΙΊΪΚΛΜΝΞΟΌΠΡΣΤΥΎΫΦΧΨΩΏ"; private static final String ALL_GREEK_LOWERCASE_LETTERS = "αάβγδεέζηήθιίϊΐκλμνξοόπρσςτυύϋΰφχψωώ"; private static final String ALL_GREEK_LETTERS = ALL_GREEK_UPPERCASE_LETTERS + ALL_GREEK_LOWERCASE_LETTERS; private static final String ALL_GREEK_VOWELS = "ΑαΆάΕεΈέΗηΉήΙιΊίΪϊΐΟοΌόΥυΎύΫϋΰΩωΏώ"; private static final String NOTE_1_GREEK_CONSONANTS = "ΒβΓγΔδΖζΛλΜμΝνΡρ"; private static final String NOTE_2_GREEK_CONSONANTS = "ΘθΚκΞξΠπΣσΤτΦφΧχΨψ"; private static boolean checkNote1(final char c) { return ALL_GREEK_VOWELS.indexOf(c) != -1 || NOTE_1_GREEK_CONSONANTS.indexOf(c) != -1; } /** * Converts a text given in Greek into Greeklish (i.e. the equivalent text expressed in the Latin character set). * It ignores accents, i.e. "Κόσμος" is converted to "Kosmos". * * @param greek the original text, expressed in the Greek character set * @return the converted text, expressed in the Latin character set * @see #toGreeklish(String, boolean) */ public static String toGreeklish(final String greek) { return toGreeklish(greek, false); } /** * Converts a text given in Greek into Greeklish (i.e. the equivalent text expressed in the Latin character set). * If withAccents is set to true, it converts accents as well, i.e. "Κόσμος" is converted to "Kósmos". * * @see #toGreeklish(String) * * @param greek the original text, expressed in the Greek character set * @param withAccents indicates whether the resulting text will have accents * @return the converted text, expressed in the Latin character set */ public static String toGreeklish(final String greek, final boolean withAccents) { final StringBuilder stringBuilder = new StringBuilder(); final StringTokenizer stringTokenizer = new StringTokenizer(greek, " "); while(stringTokenizer.hasMoreTokens()) { final String word = stringTokenizer.nextToken(); stringBuilder.append(toGreeklishWord(word, withAccents)).append(" "); } return stringBuilder.toString().trim(); } /** * Converts a word given in Greek into Greeklish (i.e. the equivalent word expressed in the Latin character set). * If withAccents is set to true, it converts accents as well, i.e. "Κόσμος" is converted to "Kósmos". * * @see #toGreeklish(String) * * @param greekWord the original word, expressed in the Greek character set * @param withAccents indicates whether the resulting text will have accents * @return the converted text, expressed in the Latin character set */ public static String toGreeklishWord(final String greekWord, final boolean withAccents) { // handle words that match any of the exceptions if(withAccents && exceptionsWithAccentsNotes_1_2.containsKey(greekWord)) return exceptionsWithAccentsNotes_1_2.get(greekWord)[0]; if(exceptionsNotes_1_2.containsKey(greekWord)) return exceptionsNotes_1_2.get(greekWord)[0]; String greeklishWord = greekWord; // handle words starting with ΜΠ, Μπ, μπ { if(greeklishWord.startsWith("ΜΠ")) greeklishWord = greeklishWord.replace("ΜΠ", "B"); else if(greeklishWord.startsWith("Μπ")) greeklishWord = greeklishWord.replace("Μπ", "B"); else if(greeklishWord.startsWith("μπ")) greeklishWord = greeklishWord.replace("μπ", "b"); } // handle exceptional cases under notes 1, 2 - with accents ... if(withAccents) { final Set<String> exceptionKeys = exceptionsWithAccentsNotes_1_2.keySet(); for(final String exceptionKey : exceptionKeys) { final String [] exceptionValues = exceptionsWithAccentsNotes_1_2.get(exceptionKey); assert exceptionValues != null; int index; while((index = greeklishWord.indexOf(exceptionKey)) != -1) { final boolean endOfWord = index == greeklishWord.length() - exceptionKey.length() - 1; final boolean note1 = !endOfWord && checkNote1(greeklishWord.charAt(index + exceptionKey.length())); greeklishWord = greeklishWord.replaceAll(exceptionKey, note1 ? exceptionValues[0] : exceptionValues[1]); } } } // ... and then handle base cases { final Set<String> exceptionKeys = exceptionsNotes_1_2.keySet(); for(final String exceptionKey : exceptionKeys) { final String [] exceptionValues = exceptionsNotes_1_2.get(exceptionKey); assert exceptionValues != null; int index; while((index = greeklishWord.indexOf(exceptionKey)) != -1) { final boolean endOfWord = greeklishWord.length() == exceptionKey.length() || index == greeklishWord.length() - exceptionKey.length() - 1; final boolean note1 = !endOfWord && checkNote1(greeklishWord.charAt(index + exceptionKey.length())); greeklishWord = greeklishWord.replaceAll(exceptionKey, note1 ? exceptionValues[0] : exceptionValues[1]); } } } // next handle exceptional cases - with accents ... if(withAccents) { final Set<String> exceptionKeys = exceptionsWithAccents.keySet(); for(final String exceptionKey : exceptionKeys) { final String exceptionValue = exceptionsWithAccents.get(exceptionKey); assert exceptionValue != null; greeklishWord = greeklishWord.replaceAll(exceptionKey, exceptionValue); } } // ... and then handle base cases { final Set<String> exceptionKeys = exceptions.keySet(); for(final String exceptionKey : exceptionKeys) { final String exceptionValue = exceptions.get(exceptionKey); assert exceptionValue != null; greeklishWord = greeklishWord.replaceAll(exceptionKey, exceptionValue); } } // next handle special letters if all caps final boolean isAllCaps = isGreekWordInAllCaps(greekWord); if(isAllCaps) { final Set<String> exceptionAllCapsKeys = exceptionsAllCaps.keySet(); for(final String exceptionKey : exceptionAllCapsKeys) { final String exceptionValue = exceptionsAllCaps.get(exceptionKey); assert exceptionValue != null; greeklishWord = greeklishWord.replaceAll(exceptionKey, exceptionValue); } } // finally handle all other letters - with accents ... if(withAccents) { final Set<String> mappingKeys = mappingWithAccents.keySet(); for(final String mappingKey : mappingKeys) { final String mappingValue = mappingWithAccents.get(mappingKey); assert mappingValue != null; greeklishWord = greeklishWord.replaceAll(mappingKey, mappingValue); } } // ... and then all base cases { final Set<String> mappingKeys = mappingBase.keySet(); for(final String mappingKey : mappingKeys) { final String mappingValue = mappingBase.get(mappingKey); assert mappingValue != null; greeklishWord = greeklishWord.replaceAll(mappingKey, mappingValue); } } return greeklishWord; } /** * Checks if a given Greek word is in all-capital letters. * * @param greekWord must be a Greek word * @return true if and only if a given Greek word is in all-capital letters */ public static boolean isGreekWordInAllCaps(final String greekWord) { final char [] characters = greekWord.toCharArray(); for(final char c : characters) { if(ALL_GREEK_LOWERCASE_LETTERS.indexOf(c) != -1) return false; } return true; } private static final Map<Character,Character> ACCENTS_TO_PLAIN_GREEK_LOWERCASE = new HashMap<>(); static { ACCENTS_TO_PLAIN_GREEK_LOWERCASE.put('ά', 'α'); ACCENTS_TO_PLAIN_GREEK_LOWERCASE.put('έ', 'ε'); ACCENTS_TO_PLAIN_GREEK_LOWERCASE.put('ή', 'η'); ACCENTS_TO_PLAIN_GREEK_LOWERCASE.put('ί', 'ι'); ACCENTS_TO_PLAIN_GREEK_LOWERCASE.put('ϊ', 'ι'); ACCENTS_TO_PLAIN_GREEK_LOWERCASE.put('ΐ', 'ι'); ACCENTS_TO_PLAIN_GREEK_LOWERCASE.put('ό', 'ο'); ACCENTS_TO_PLAIN_GREEK_LOWERCASE.put('ύ', 'υ'); ACCENTS_TO_PLAIN_GREEK_LOWERCASE.put('ϋ', 'υ'); ACCENTS_TO_PLAIN_GREEK_LOWERCASE.put('ΰ', 'υ'); ACCENTS_TO_PLAIN_GREEK_LOWERCASE.put('ώ', 'ω'); } private static final Map<Character,Character> ACCENTS_TO_PLAIN_GREEK_UPPERCASE = new HashMap<>(); static { ACCENTS_TO_PLAIN_GREEK_UPPERCASE.put('Ά', 'Α'); ACCENTS_TO_PLAIN_GREEK_UPPERCASE.put('Έ', 'Ε'); ACCENTS_TO_PLAIN_GREEK_UPPERCASE.put('Ή', 'Η'); ACCENTS_TO_PLAIN_GREEK_UPPERCASE.put('Ί', 'Ι'); ACCENTS_TO_PLAIN_GREEK_UPPERCASE.put('Ϊ', 'Ι'); ACCENTS_TO_PLAIN_GREEK_UPPERCASE.put('Ό', 'Ο'); ACCENTS_TO_PLAIN_GREEK_UPPERCASE.put('Ύ', 'Υ'); ACCENTS_TO_PLAIN_GREEK_UPPERCASE.put('Ϋ', 'Υ'); ACCENTS_TO_PLAIN_GREEK_UPPERCASE.put('Ώ', 'Ω'); } private static final Map<Character,Character> ACCENTS_TO_PLAIN_GREEK = new HashMap<>(); static { ACCENTS_TO_PLAIN_GREEK.putAll(ACCENTS_TO_PLAIN_GREEK_LOWERCASE); ACCENTS_TO_PLAIN_GREEK.putAll(ACCENTS_TO_PLAIN_GREEK_UPPERCASE); } /** * Converts a given lower-case text in Greek, into the equivalent, simplified version where accents are removed. * For example, "κόσμος" is converted to "κοσμος". * * This can be useful when you are searching in text. * * @param greekLowercaseTextWithAccents the lower-case text in Greek, which includes accents * @return the equivalent text in Greek, without accents */ public static String removeAccentsLowercase(final String greekLowercaseTextWithAccents) { final StringBuilder greekLowercaseTextWithoutAccents = new StringBuilder(); for(final char c : greekLowercaseTextWithAccents.toCharArray()) { final Character cWithoutAccent = ACCENTS_TO_PLAIN_GREEK_LOWERCASE.get(c); greekLowercaseTextWithoutAccents.append(cWithoutAccent == null ? c : cWithoutAccent); } return greekLowercaseTextWithoutAccents.toString(); } /** * Converts a given upper-case text in Greek, into the equivalent, simplified version where accents are removed. * For example, "ΈΝΑΣ ΚΌΣΜΟΣ" is converted to "ΕΝΑΣ ΚΟΣΜΟΣ". * * This can be useful when you are searching in text. * * @param greekUppercaseTextWithAccents the upper-case text in Greek, which includes accents * @return the equivalent text in Greek, without accents */ public static String removeAccentsUppercase(final String greekUppercaseTextWithAccents) { final StringBuilder greekUppercaseTextWithoutAccents = new StringBuilder(); for(final char c : greekUppercaseTextWithAccents.toCharArray()) { final Character cWithoutAccent = ACCENTS_TO_PLAIN_GREEK_UPPERCASE.get(c); greekUppercaseTextWithoutAccents.append(cWithoutAccent == null ? c : cWithoutAccent); } return greekUppercaseTextWithoutAccents.toString(); } /** * Converts a given any-case text in Greek, into the equivalent, simplified version where accents are removed. * For example, "Ένας Κόσμος" is converted to "Ενας Κοσμος". * * This can be useful when you are searching in text. * * @param greekTextWithAccents the any-case text in Greek, which includes accents * @return the equivalent text in Greek, without accents */ public static String removeAccents(final String greekTextWithAccents) { final StringBuilder greekTextWithoutAccents = new StringBuilder(); for(final char c : greekTextWithAccents.toCharArray()) { final Character cWithoutAccent = ACCENTS_TO_PLAIN_GREEK.get(c); greekTextWithoutAccents.append(cWithoutAccent == null ? c : cWithoutAccent); } return greekTextWithoutAccents.toString(); } /** * Simply checks if the given text contains at least one character from the Greek character set. * * @param text the text to be checked * @return true if and only if the given text contains at least one character from the Greek character set */ public static boolean containsGreek(final String text) { for(final char c : text.toCharArray()) { if(ALL_GREEK_LETTERS.indexOf(c) > -1) return true; } return false; } }
nearchos/GreekTools
src/main/java/com/aspectsense/greektools/Greeklish.java
933
package org.mockserver.integration.server; import com.google.common.base.Charsets; import com.google.common.net.HttpHeaders; import com.google.common.net.MediaType; import com.google.common.util.concurrent.Uninterruptibles; import org.apache.commons.io.IOUtils; import org.junit.Before; import org.junit.Ignore; import org.junit.Test; import org.mockserver.client.netty.NettyHttpClient; import org.mockserver.client.netty.SocketConnectionException; import org.mockserver.client.server.MockServerClient; import org.mockserver.echo.http.EchoServer; import org.mockserver.matchers.MatchType; import org.mockserver.matchers.TimeToLive; import org.mockserver.model.*; import org.mockserver.socket.PortFactory; import org.mockserver.verify.VerificationTimes; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.IOException; import java.util.*; import java.util.concurrent.*; import static org.hamcrest.Matchers.lessThan; import static org.hamcrest.core.Is.is; import static org.hamcrest.core.StringStartsWith.startsWith; import static org.hamcrest.number.OrderingComparison.greaterThan; import static org.junit.Assert.*; import static org.mockserver.matchers.Times.exactly; import static org.mockserver.matchers.Times.once; import static org.mockserver.model.BinaryBody.binary; import static org.mockserver.model.Cookie.cookie; import static org.mockserver.model.Header.header; import static org.mockserver.model.HttpCallback.callback; import static org.mockserver.model.HttpForward.forward; import static org.mockserver.model.HttpRequest.request; import static org.mockserver.model.HttpResponse.notFoundResponse; import static org.mockserver.model.HttpResponse.response; import static org.mockserver.model.JsonBody.json; import static org.mockserver.model.JsonSchemaBody.jsonSchema; import static org.mockserver.model.NottableString.not; import static org.mockserver.model.NottableString.string; import static org.mockserver.model.OutboundHttpRequest.outboundRequest; import static org.mockserver.model.Parameter.param; import static org.mockserver.model.ParameterBody.params; import static org.mockserver.model.StringBody.exact; import static org.mockserver.model.XPathBody.xpath; /** * @author jamesdbloom */ public abstract class AbstractClientServerIntegrationTest { public static final String TEXT_PLAIN = MediaType.create("text", "plain").toString(); protected static MockServerClient mockServerClient; protected static String servletContext = ""; private final Logger logger = LoggerFactory.getLogger(this.getClass()); protected List<String> headersToIgnore = Arrays.asList( "server", "expires", "date", "host", "connection", "user-agent", "content-length", "accept-encoding", "transfer-encoding" ); private NettyHttpClient httpClient = new NettyHttpClient(); public abstract int getMockServerPort(); public abstract int getMockServerSecurePort(); public abstract int getTestServerPort(); protected String calculatePath(String path) { return "/" + path; } @Before public void resetServer() { mockServerClient.reset(); } @Test public void shouldForwardRequestInHTTP() { // when mockServerClient .when( request() .withPath(calculatePath("echo")) ) .forward( forward() .withHost("127.0.0.1") .withPort(getTestServerPort()) ); // then // - in http assertEquals( response() .withStatusCode(HttpStatusCode.OK_200.code()) .withHeaders( header("x-test", "test_headers_and_body"), header(HttpHeaders.CONTENT_TYPE, TEXT_PLAIN) ) .withBody("an_example_body_http"), makeRequest( request() .withPath(calculatePath("echo")) .withMethod("POST") .withHeaders( header("x-test", "test_headers_and_body") ) .withBody("an_example_body_http"), headersToIgnore) ); // - in https assertEquals( response() .withStatusCode(HttpStatusCode.OK_200.code()) .withHeaders( header("x-test", "test_headers_and_body"), header(HttpHeaders.CONTENT_TYPE, TEXT_PLAIN) ) .withBody("an_example_body_https"), makeRequest( request() .setSecure(true) .withPath(calculatePath("echo")) .withMethod("POST") .withHeaders( header("x-test", "test_headers_and_body") ) .withBody("an_example_body_https"), headersToIgnore) ); } @Test public void shouldForwardRequestInHTTPS() { int testServerHttpsPort = PortFactory.findFreePort(); EchoServer secureEchoServer = new EchoServer(testServerHttpsPort, true); try { // when mockServerClient .when( request() .withPath(calculatePath("echo")) ) .forward( forward() .withHost("127.0.0.1") .withPort(testServerHttpsPort) .withScheme(HttpForward.Scheme.HTTPS) ); // then // - in http assertEquals( response() .withStatusCode(HttpStatusCode.OK_200.code()) .withHeaders( header("x-test", "test_headers_and_body"), header(HttpHeaders.CONTENT_TYPE, TEXT_PLAIN) ) .withBody("an_example_body_http"), makeRequest( request() .withPath(calculatePath("echo")) .withMethod("POST") .withHeaders( header("x-test", "test_headers_and_body") ) .withBody("an_example_body_http"), headersToIgnore) ); // - in https assertEquals( response() .withStatusCode(HttpStatusCode.OK_200.code()) .withHeaders( header("x-test", "test_headers_and_body"), header(HttpHeaders.CONTENT_TYPE, TEXT_PLAIN) ) .withBody("an_example_body_https"), makeRequest( request() .setSecure(true) .withPath(calculatePath("echo")) .withMethod("POST") .withHeaders( header("x-test", "test_headers_and_body") ) .withBody("an_example_body_https"), headersToIgnore) ); } finally { secureEchoServer.stop(); } } @Test public void shouldAllowSimultaneousForwardAndResponseExpectations() { // when mockServerClient .when( request() .withPath(calculatePath("echo")), once() ) .forward( forward() .withHost("127.0.0.1") .withPort(getTestServerPort()) ); mockServerClient .when( request() .withPath(calculatePath("test_headers_and_body")), once() ) .respond( response() .withBody("some_body") ); // then // - forward assertEquals( response() .withStatusCode(HttpStatusCode.OK_200.code()) .withHeaders( header("x-test", "test_headers_and_body"), header(HttpHeaders.CONTENT_TYPE, TEXT_PLAIN) ) .withBody("an_example_body"), makeRequest( request() .withPath(calculatePath("echo")) .withMethod("POST") .withHeaders( header("x-test", "test_headers_and_body") ) .withBody("an_example_body"), headersToIgnore) ); // - respond assertEquals( response() .withHeader(HttpHeaders.CONTENT_TYPE, TEXT_PLAIN) .withStatusCode(HttpStatusCode.OK_200.code()) .withBody("some_body"), makeRequest( request() .withPath(calculatePath("test_headers_and_body")), headersToIgnore) ); // - no response or forward assertEquals( response() .withHeader(HttpHeaders.CONTENT_TYPE, TEXT_PLAIN) .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()), makeRequest( request() .withPath(calculatePath("test_headers_and_body")), headersToIgnore) ); } @Test public void shouldCallbackToSpecifiedClassWithPrecannedResponse() { // when mockServerClient .when( request() .withPath(calculatePath("callback")) ) .callback( callback() .withCallbackClass("org.mockserver.integration.callback.PrecannedTestExpectationCallback") ); // then // - in http assertEquals( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withHeaders( header("x-callback", "test_callback_header"), header(HttpHeaders.CONTENT_TYPE, TEXT_PLAIN) ) .withBody("a_callback_response"), makeRequest( request() .withPath(calculatePath("callback")) .withMethod("POST") .withHeaders( header("x-test", "test_headers_and_body") ) .withBody("an_example_body_http"), headersToIgnore ) ); // - in https assertEquals( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withHeaders( header("x-callback", "test_callback_header"), header(HttpHeaders.CONTENT_TYPE, TEXT_PLAIN) ) .withBody("a_callback_response"), makeRequest( request() .setSecure(true) .withPath(calculatePath("callback")) .withMethod("POST") .withHeaders( header("x-test", "test_headers_and_body") ) .withBody("an_example_body_https"), headersToIgnore ) ); } @Test public void shouldReturnResponseWithOnlyBody() { // when mockServerClient.when(request()).respond(response().withBody("some_body")); // then // - in http assertEquals( response() .withHeader(HttpHeaders.CONTENT_TYPE, TEXT_PLAIN) .withStatusCode(HttpStatusCode.OK_200.code()) .withBody("some_body"), makeRequest( request() .withPath(calculatePath("")), headersToIgnore) ); // - in https assertEquals( response() .withHeader(HttpHeaders.CONTENT_TYPE, TEXT_PLAIN) .withStatusCode(HttpStatusCode.OK_200.code()) .withBody("some_body"), makeRequest( request() .setSecure(true) .withPath(calculatePath("")), headersToIgnore) ); } @Test public void shouldReturnMatchRequestWithBodyInUTF16() { // when String body = "我说中国话"; mockServerClient.when(request().withBody(body, Charsets.UTF_16)).respond(response().withBody(body, Charsets.UTF_8)); // then // - in http assertEquals( response() .withHeader(HttpHeaders.CONTENT_TYPE, MediaType.create("text", "plain").withCharset(Charsets.UTF_8).toString()) .withStatusCode(HttpStatusCode.OK_200.code()) .withBody(body), makeRequest( request() .withPath(calculatePath("")) .withBody(body, Charsets.UTF_16), headersToIgnore) ); // - in https assertEquals( response() .withHeader(HttpHeaders.CONTENT_TYPE, MediaType.create("text", "plain").withCharset(Charsets.UTF_8).toString()) .withStatusCode(HttpStatusCode.OK_200.code()) .withBody(body), makeRequest( request() .setSecure(true) .withPath(calculatePath("")) .withBody(body, Charsets.UTF_16), headersToIgnore) ); } @Test public void shouldReturnMatchRequestWithBodyInUTF16WithContentTypeHeader() { // when String body = "我说中国话"; mockServerClient .when( request() .withHeader(HttpHeaders.CONTENT_TYPE, MediaType.create("text", "plain").withCharset(Charsets.UTF_8).toString()) .withBody(body) ) .respond( response() .withBody(body, Charsets.UTF_8) ); // then // - in http assertEquals( response() .withHeader(HttpHeaders.CONTENT_TYPE, MediaType.create("text", "plain").withCharset(Charsets.UTF_8).toString()) .withStatusCode(HttpStatusCode.OK_200.code()) .withBody(body), makeRequest( request() .withHeader(HttpHeaders.CONTENT_TYPE, MediaType.create("text", "plain").withCharset(Charsets.UTF_8).toString()) .withPath(calculatePath("")) .withBody(body), headersToIgnore) ); // - in https assertEquals( response() .withHeader(HttpHeaders.CONTENT_TYPE, MediaType.create("text", "plain").withCharset(Charsets.UTF_8).toString()) .withStatusCode(HttpStatusCode.OK_200.code()) .withBody(body), makeRequest( request() .withHeader(HttpHeaders.CONTENT_TYPE, MediaType.create("text", "plain").withCharset(Charsets.UTF_8).toString()) .setSecure(true) .withPath(calculatePath("")) .withBody(body), headersToIgnore) ); } @Test public void shouldReturnResponseWithBodyInUTF8() { // when String body = "我说中国话"; mockServerClient.when(request()).respond(response().withBody(body, Charsets.UTF_16)); // then // - in http assertEquals( response() .withHeader(HttpHeaders.CONTENT_TYPE, MediaType.create("text", "plain").withCharset(Charsets.UTF_16).toString()) .withStatusCode(HttpStatusCode.OK_200.code()) .withBody(body), makeRequest( request() .withPath(calculatePath("")), headersToIgnore) ); // - in https assertEquals( response() .withHeader(HttpHeaders.CONTENT_TYPE, MediaType.create("text", "plain").withCharset(Charsets.UTF_16).toString()) .withStatusCode(HttpStatusCode.OK_200.code()) .withBody(body), makeRequest( request() .setSecure(true) .withPath(calculatePath("")), headersToIgnore) ); } @Test public void shouldReturnResponseWithBodyInUTF16WithContentTypeHeader() { // when String body = "我说中国话"; mockServerClient .when( request() ) .respond( response() .withHeader(HttpHeaders.CONTENT_TYPE, MediaType.create("text", "plain").withCharset(Charsets.UTF_8).toString()) .withBody(body) ); // then // - in http assertEquals( response() .withHeader(HttpHeaders.CONTENT_TYPE, MediaType.create("text", "plain").withCharset(Charsets.UTF_8).toString()) .withStatusCode(HttpStatusCode.OK_200.code()) .withBody(body), makeRequest( request() .withPath(calculatePath("")), headersToIgnore) ); // - in https assertEquals( response() .withHeader(HttpHeaders.CONTENT_TYPE, MediaType.create("text", "plain").withCharset(Charsets.UTF_8).toString()) .withStatusCode(HttpStatusCode.OK_200.code()) .withBody(body), makeRequest( request() .setSecure(true) .withPath(calculatePath("")), headersToIgnore) ); } @Test public void shouldReturnResponseWithOnlyStatusCode() { // when mockServerClient .when( request() .withMethod("POST") .withPath(calculatePath("some_path")) ) .respond( response() .withStatusCode(200) ); // then // - in http assertEquals( response() .withStatusCode(HttpStatusCode.OK_200.code()), makeRequest( request() .withPath(calculatePath("some_path")) .withMethod("POST"), headersToIgnore) ); // - in https assertEquals( response() .withStatusCode(HttpStatusCode.OK_200.code()), makeRequest( request() .setSecure(true) .withPath(calculatePath("some_path")) .withMethod("POST"), headersToIgnore) ); } @Test public void shouldVerifyReceivedRequests() { // when mockServerClient .when( request() .withPath(calculatePath("some_path")), exactly(2) ) .respond( response() .withBody("some_body") ); // then // - in http assertEquals( response() .withHeader(HttpHeaders.CONTENT_TYPE, TEXT_PLAIN) .withStatusCode(HttpStatusCode.OK_200.code()) .withBody("some_body"), makeRequest( request() .withPath(calculatePath("some_path")), headersToIgnore) ); mockServerClient.verify(request() .withPath(calculatePath("some_path"))); mockServerClient.verify(request() .withPath(calculatePath("some_path")), VerificationTimes.exactly(1)); // - in https assertEquals( response() .withHeader(HttpHeaders.CONTENT_TYPE, TEXT_PLAIN) .withStatusCode(HttpStatusCode.OK_200.code()) .withBody("some_body"), makeRequest( request() .setSecure(true) .withPath(calculatePath("some_path")), headersToIgnore) ); mockServerClient.verify(request().withPath(calculatePath("some_path")), VerificationTimes.atLeast(1)); mockServerClient.verify(request().withPath(calculatePath("some_path")), VerificationTimes.exactly(2)); } @Test public void shouldVerifyReceivedRequestsWithNoBody() { // when mockServerClient.when(request().withPath(calculatePath("some_path")), exactly(2)).respond(response()); // then // - in http assertEquals( response() .withStatusCode(HttpStatusCode.OK_200.code()), makeRequest( request() .withPath(calculatePath("some_path")), headersToIgnore) ); mockServerClient.verify(request() .withPath(calculatePath("some_path"))); mockServerClient.verify(request() .withPath(calculatePath("some_path")), VerificationTimes.exactly(1)); } @Test public void shouldVerifyNotEnoughRequestsReceived() { // when mockServerClient.when(request().withPath(calculatePath("some_path")), exactly(2)).respond(response().withBody("some_body")); // then assertEquals( response() .withHeader(HttpHeaders.CONTENT_TYPE, TEXT_PLAIN) .withStatusCode(HttpStatusCode.OK_200.code()) .withBody("some_body"), makeRequest( request() .withPath(calculatePath("some_path")), headersToIgnore) ); try { mockServerClient.verify(request() .withPath(calculatePath("some_path")), VerificationTimes.atLeast(2)); fail(); } catch (AssertionError ae) { assertThat(ae.getMessage(), startsWith("Request not found at least 2 times, expected:<{" + System.getProperty("line.separator") + " \"path\" : \"" + calculatePath("some_path") + "\"" + System.getProperty("line.separator") + "}> but was:<{" + System.getProperty("line.separator") + " \"method\" : \"GET\"," + System.getProperty("line.separator") + " \"path\" : \"" + calculatePath("some_path") + "\"," + System.getProperty("line.separator"))); } } @Test public void shouldVerifyTooManyRequestsReceived() { // when mockServerClient.when(request().withPath(calculatePath("some_path")), exactly(2)).respond(response().withBody("some_body")); // then assertEquals( response() .withHeader(HttpHeaders.CONTENT_TYPE, TEXT_PLAIN) .withStatusCode(HttpStatusCode.OK_200.code()) .withBody("some_body"), makeRequest( request() .withPath(calculatePath("some_path")), headersToIgnore) ); try { mockServerClient.verify(request() .withPath(calculatePath("some_path")), VerificationTimes.exactly(0)); fail(); } catch (AssertionError ae) { assertThat(ae.getMessage(), startsWith("Request not found exactly 0 times, expected:<{" + System.getProperty("line.separator") + " \"path\" : \"" + calculatePath("some_path") + "\"" + System.getProperty("line.separator") + "}> but was:<{" + System.getProperty("line.separator") + " \"method\" : \"GET\"," + System.getProperty("line.separator") + " \"path\" : \"" + calculatePath("some_path") + "\"," + System.getProperty("line.separator"))); } } @Test public void shouldVerifyNoMatchingRequestsReceived() { // when mockServerClient.when(request().withPath(calculatePath("some_path")), exactly(2)).respond(response().withBody("some_body")); // then assertEquals( response() .withHeader(HttpHeaders.CONTENT_TYPE, TEXT_PLAIN) .withStatusCode(HttpStatusCode.OK_200.code()) .withBody("some_body"), makeRequest( request() .withPath(calculatePath("some_path")), headersToIgnore) ); try { mockServerClient.verify(request() .withPath(calculatePath("some_other_path")), VerificationTimes.exactly(2)); fail(); } catch (AssertionError ae) { assertThat(ae.getMessage(), startsWith("Request not found exactly 2 times, expected:<{" + System.getProperty("line.separator") + " \"path\" : \"" + calculatePath("some_other_path") + "\"" + System.getProperty("line.separator") + "}> but was:<{" + System.getProperty("line.separator") + " \"method\" : \"GET\"," + System.getProperty("line.separator") + " \"path\" : \"" + calculatePath("some_path") + "\"," + System.getProperty("line.separator"))); } } @Test public void shouldVerifySequenceOfRequestsReceived() { // when mockServerClient.when(request().withPath(calculatePath("some_path.*")), exactly(6)).respond(response().withBody("some_body")); // then // - in http assertEquals( response("some_body").withHeader(HttpHeaders.CONTENT_TYPE, TEXT_PLAIN), makeRequest( request().withPath(calculatePath("some_path_one")), headersToIgnore) ); assertEquals( response("some_body").withHeader(HttpHeaders.CONTENT_TYPE, TEXT_PLAIN), makeRequest( request().withPath(calculatePath("some_path_two")), headersToIgnore) ); assertEquals( response("some_body").withHeader(HttpHeaders.CONTENT_TYPE, TEXT_PLAIN), makeRequest( request().withPath(calculatePath("some_path_three")), headersToIgnore) ); mockServerClient.verify(request(calculatePath("some_path_one")), request(calculatePath("some_path_three"))); mockServerClient.verify(request(calculatePath("some_path_one")), request(calculatePath("some_path_two"))); mockServerClient.verify(request(calculatePath("some_path_one")), request(calculatePath("some_path_two")), request(calculatePath("some_path_three"))); // - in https assertEquals( response("some_body").withHeader(HttpHeaders.CONTENT_TYPE, TEXT_PLAIN), makeRequest( request().setSecure(true) .withPath(calculatePath("some_path_one")), headersToIgnore) ); assertEquals( response("some_body").withHeader(HttpHeaders.CONTENT_TYPE, TEXT_PLAIN), makeRequest( request().setSecure(true) .withPath(calculatePath("some_path_two")), headersToIgnore) ); assertEquals( response("some_body").withHeader(HttpHeaders.CONTENT_TYPE, TEXT_PLAIN), makeRequest( request().setSecure(true) .withPath(calculatePath("some_path_three")), headersToIgnore) ); mockServerClient.verify(request(calculatePath("some_path_one")), request(calculatePath("some_path_three"))); mockServerClient.verify(request(calculatePath("some_path_one")), request(calculatePath("some_path_two"))); mockServerClient.verify(request(calculatePath("some_path_one")), request(calculatePath("some_path_two")), request(calculatePath("some_path_three"))); } @Test public void shouldVerifySequenceOfRequestsReceivedIncludingThoseNotMatchingAnException() { // when mockServerClient.when(request().withPath(calculatePath("some_path.*")), exactly(4)).respond(response().withBody("some_body")); // then // - in http assertEquals( response("some_body").withHeader(HttpHeaders.CONTENT_TYPE, TEXT_PLAIN), makeRequest( request().withPath(calculatePath("some_path_one")), headersToIgnore) ); assertEquals( notFoundResponse().withHeader(HttpHeaders.CONTENT_TYPE, TEXT_PLAIN), makeRequest( request().withPath(calculatePath("not_found")), headersToIgnore) ); assertEquals( response("some_body").withHeader(HttpHeaders.CONTENT_TYPE, TEXT_PLAIN), makeRequest( request().withPath(calculatePath("some_path_three")), headersToIgnore) ); mockServerClient.verify(request(calculatePath("some_path_one")), request(calculatePath("some_path_three"))); mockServerClient.verify(request(calculatePath("some_path_one")), request(calculatePath("not_found"))); mockServerClient.verify(request(calculatePath("some_path_one")), request(calculatePath("not_found")), request(calculatePath("some_path_three"))); // - in https assertEquals( response("some_body").withHeader(HttpHeaders.CONTENT_TYPE, TEXT_PLAIN), makeRequest( request().setSecure(true) .withPath(calculatePath("some_path_one")), headersToIgnore) ); assertEquals( notFoundResponse().withHeader(HttpHeaders.CONTENT_TYPE, TEXT_PLAIN), makeRequest( request().setSecure(true) .withPath(calculatePath("not_found")), headersToIgnore) ); assertEquals( response("some_body").withHeader(HttpHeaders.CONTENT_TYPE, TEXT_PLAIN), makeRequest( request().setSecure(true) .withPath(calculatePath("some_path_three")), headersToIgnore) ); mockServerClient.verify(request(calculatePath("some_path_one")), request(calculatePath("some_path_three"))); mockServerClient.verify(request(calculatePath("some_path_one")), request(calculatePath("not_found"))); mockServerClient.verify(request(calculatePath("some_path_one")), request(calculatePath("not_found")), request(calculatePath("some_path_three"))); } @Test public void shouldVerifySequenceOfRequestsNotReceived() { // when mockServerClient.when(request().withPath(calculatePath("some_path.*")), exactly(6)).respond(response().withBody("some_body")); // then // - in http assertEquals( response("some_body").withHeader(HttpHeaders.CONTENT_TYPE, TEXT_PLAIN), makeRequest( request().withPath(calculatePath("some_path_one")), headersToIgnore) ); assertEquals( response("some_body").withHeader(HttpHeaders.CONTENT_TYPE, TEXT_PLAIN), makeRequest( request().withPath(calculatePath("some_path_two")), headersToIgnore) ); assertEquals( response("some_body").withHeader(HttpHeaders.CONTENT_TYPE, TEXT_PLAIN), makeRequest( request().withPath(calculatePath("some_path_three")), headersToIgnore) ); try { mockServerClient.verify(request(calculatePath("some_path_two")), request(calculatePath("some_path_one"))); fail(); } catch (AssertionError ae) { assertThat(ae.getMessage(), startsWith("Request sequence not found, expected:<[ {" + System.getProperty("line.separator") + " \"path\" : \"" + calculatePath("some_path_two") + "\"" + System.getProperty("line.separator") + "}, {" + System.getProperty("line.separator") + " \"path\" : \"" + calculatePath("some_path_one") + "\"" + System.getProperty("line.separator") + "} ]> but was:<[ {" + System.getProperty("line.separator") + " \"method\" : \"GET\"," + System.getProperty("line.separator") + " \"path\" : \"" + calculatePath("some_path_one") + "\"," + System.getProperty("line.separator"))); } try { mockServerClient.verify(request(calculatePath("some_path_three")), request(calculatePath("some_path_two"))); fail(); } catch (AssertionError ae) { assertThat(ae.getMessage(), startsWith("Request sequence not found, expected:<[ {" + System.getProperty("line.separator") + " \"path\" : \"" + calculatePath("some_path_three") + "\"" + System.getProperty("line.separator") + "}, {" + System.getProperty("line.separator") + " \"path\" : \"" + calculatePath("some_path_two") + "\"" + System.getProperty("line.separator") + "} ]> but was:<[ {" + System.getProperty("line.separator") + " \"method\" : \"GET\"," + System.getProperty("line.separator") + " \"path\" : \"" + calculatePath("some_path_one") + "\"," + System.getProperty("line.separator"))); } try { mockServerClient.verify(request(calculatePath("some_path_four"))); fail(); } catch (AssertionError ae) { assertThat(ae.getMessage(), startsWith("Request sequence not found, expected:<[ {" + System.getProperty("line.separator") + " \"path\" : \"" + calculatePath("some_path_four") + "\"" + System.getProperty("line.separator") + "} ]> but was:<[ {" + System.getProperty("line.separator") + " \"method\" : \"GET\"," + System.getProperty("line.separator") + " \"path\" : \"" + calculatePath("some_path_one") + "\"," + System.getProperty("line.separator"))); } } @Test public void shouldReturnResponseByMatchingPath() { // when mockServerClient .when( request() .withPath(calculatePath("some_path1")) ) .respond( response() .withBody("some_body1") ); mockServerClient .when( request() .withPath(calculatePath("some_path2")) ) .respond( response() .withBody("some_body2") ); // then // - in http assertEquals( response() .withHeader(HttpHeaders.CONTENT_TYPE, TEXT_PLAIN) .withStatusCode(HttpStatusCode.OK_200.code()) .withBody("some_body2"), makeRequest( request() .withPath(calculatePath("some_path2")), headersToIgnore) ); assertEquals( response() .withHeader(HttpHeaders.CONTENT_TYPE, TEXT_PLAIN) .withStatusCode(HttpStatusCode.OK_200.code()) .withBody("some_body1"), makeRequest( request() .withPath(calculatePath("some_path1")), headersToIgnore) ); // - in https assertEquals( response() .withHeader(HttpHeaders.CONTENT_TYPE, TEXT_PLAIN) .withStatusCode(HttpStatusCode.OK_200.code()) .withBody("some_body2"), makeRequest( request() .setSecure(true) .withPath(calculatePath("some_path2")), headersToIgnore) ); assertEquals( response() .withHeader(HttpHeaders.CONTENT_TYPE, TEXT_PLAIN) .withStatusCode(HttpStatusCode.OK_200.code()) .withBody("some_body1"), makeRequest( request() .setSecure(true) .withPath(calculatePath("some_path1")), headersToIgnore) ); } @Test public void shouldReturnResponseByMatchingPathExactTimes() { // when mockServerClient .when( request() .withPath(calculatePath("some_path")), exactly(2) ) .respond( response() .withBody("some_body") ); // then // - in http assertEquals( response() .withHeader(HttpHeaders.CONTENT_TYPE, TEXT_PLAIN) .withStatusCode(HttpStatusCode.OK_200.code()) .withBody("some_body"), makeRequest( request() .withPath(calculatePath("some_path")), headersToIgnore) ); // - in https assertEquals( response() .withHeader(HttpHeaders.CONTENT_TYPE, TEXT_PLAIN) .withStatusCode(HttpStatusCode.OK_200.code()) .withBody("some_body"), makeRequest( request() .setSecure(true) .withPath(calculatePath("some_path")), headersToIgnore) ); // - in http assertEquals( response() .withHeader(HttpHeaders.CONTENT_TYPE, TEXT_PLAIN) .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()), makeRequest( request() .withPath(calculatePath("some_path")), headersToIgnore) ); // - in https assertEquals( response() .withHeader(HttpHeaders.CONTENT_TYPE, TEXT_PLAIN) .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()), makeRequest( request() .setSecure(true) .withPath(calculatePath("some_path")), headersToIgnore) ); } @Test public void shouldReturnResponseWhenTimeToLiveHasNotExpired() { // when mockServerClient .when( request().withPath(calculatePath("some_path")), exactly(2), TimeToLive.exactly(TimeUnit.HOURS, 1L) ) .respond( response().withBody("some_body") ); // then // - in http assertEquals( response() .withHeader(HttpHeaders.CONTENT_TYPE, TEXT_PLAIN) .withStatusCode(HttpStatusCode.OK_200.code()) .withBody("some_body"), makeRequest( request() .withPath(calculatePath("some_path")), headersToIgnore) ); // - in https assertEquals( response() .withHeader(HttpHeaders.CONTENT_TYPE, TEXT_PLAIN) .withStatusCode(HttpStatusCode.OK_200.code()) .withBody("some_body"), makeRequest( request() .setSecure(true) .withPath(calculatePath("some_path")), headersToIgnore) ); // - in http assertEquals( response() .withHeader(HttpHeaders.CONTENT_TYPE, TEXT_PLAIN) .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()), makeRequest( request() .withPath(calculatePath("some_path")), headersToIgnore) ); // - in https assertEquals( response() .withHeader(HttpHeaders.CONTENT_TYPE, TEXT_PLAIN) .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()), makeRequest( request() .setSecure(true) .withPath(calculatePath("some_path")), headersToIgnore) ); } @Test public void shouldReturnResponseByMatchingBodyWithXPath() { // when mockServerClient.when(request().withBody(xpath("/bookstore/book[price>30]/price")), exactly(2)).respond(response().withBody("some_body")); // then // - in http assertEquals( response() .withHeader(HttpHeaders.CONTENT_TYPE, TEXT_PLAIN) .withStatusCode(HttpStatusCode.OK_200.code()) .withBody("some_body"), makeRequest( request() .withPath(calculatePath("some_path")) .withMethod("POST") .withBody(new StringBody("" + "<?xml version=\"1.0\" encoding=\"ISO-8859-1\"?>" + System.getProperty("line.separator") + "<bookstore>" + System.getProperty("line.separator") + " <book category=\"COOKING\">" + System.getProperty("line.separator") + " <title lang=\"en\">Everyday Italian</title>" + System.getProperty("line.separator") + " <author>Giada De Laurentiis</author>" + System.getProperty("line.separator") + " <year>2005</year>" + System.getProperty("line.separator") + " <price>30.00</price>" + System.getProperty("line.separator") + " </book>" + System.getProperty("line.separator") + " <book category=\"CHILDREN\">" + System.getProperty("line.separator") + " <title lang=\"en\">Harry Potter</title>" + System.getProperty("line.separator") + " <author>J K. Rowling</author>" + System.getProperty("line.separator") + " <year>2005</year>" + System.getProperty("line.separator") + " <price>29.99</price>" + System.getProperty("line.separator") + " </book>" + System.getProperty("line.separator") + " <book category=\"WEB\">" + System.getProperty("line.separator") + " <title lang=\"en\">Learning XML</title>" + System.getProperty("line.separator") + " <author>Erik T. Ray</author>" + System.getProperty("line.separator") + " <year>2003</year>" + System.getProperty("line.separator") + " <price>31.95</price>" + System.getProperty("line.separator") + " </book>" + System.getProperty("line.separator") + "</bookstore>")), headersToIgnore) ); // - in https assertEquals( response() .withHeader(HttpHeaders.CONTENT_TYPE, TEXT_PLAIN) .withStatusCode(HttpStatusCode.OK_200.code()) .withBody("some_body"), makeRequest( request() .setSecure(true) .withPath(calculatePath("some_path")) .withMethod("POST") .withBody(new StringBody("" + "<?xml version=\"1.0\" encoding=\"ISO-8859-1\"?>" + System.getProperty("line.separator") + "<bookstore>" + System.getProperty("line.separator") + " <book category=\"COOKING\">" + System.getProperty("line.separator") + " <title lang=\"en\">Everyday Italian</title>" + System.getProperty("line.separator") + " <author>Giada De Laurentiis</author>" + System.getProperty("line.separator") + " <year>2005</year>" + System.getProperty("line.separator") + " <price>30.00</price>" + System.getProperty("line.separator") + " </book>" + System.getProperty("line.separator") + " <book category=\"CHILDREN\">" + System.getProperty("line.separator") + " <title lang=\"en\">Harry Potter</title>" + System.getProperty("line.separator") + " <author>J K. Rowling</author>" + System.getProperty("line.separator") + " <year>2005</year>" + System.getProperty("line.separator") + " <price>29.99</price>" + System.getProperty("line.separator") + " </book>" + System.getProperty("line.separator") + " <book category=\"WEB\">" + System.getProperty("line.separator") + " <title lang=\"en\">Learning XML</title>" + System.getProperty("line.separator") + " <author>Erik T. Ray</author>" + System.getProperty("line.separator") + " <year>2003</year>" + System.getProperty("line.separator") + " <price>31.95</price>" + System.getProperty("line.separator") + " </book>" + System.getProperty("line.separator") + "</bookstore>")), headersToIgnore) ); } @Test public void shouldReturnResponseByMatchingBodyWithJson() { // when mockServerClient .when( request() .withBody(json("{" + System.getProperty("line.separator") + " \"id\": 1," + System.getProperty("line.separator") + " \"name\": \"A green door\"," + System.getProperty("line.separator") + " \"price\": 12.50," + System.getProperty("line.separator") + " \"tags\": [\"home\", \"green\"]" + System.getProperty("line.separator") + "}")), exactly(2) ) .respond( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body") ); // then // - in http assertEquals( response() .withHeader(HttpHeaders.CONTENT_TYPE, TEXT_PLAIN) .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body"), makeRequest( request() .withPath(calculatePath("some_path")) .withMethod("POST") .withBody("{" + System.getProperty("line.separator") + " \"id\": 1," + System.getProperty("line.separator") + " \"extra ignored field\": \"some value\"," + System.getProperty("line.separator") + " \"name\": \"A green door\"," + System.getProperty("line.separator") + " \"price\": 12.50," + System.getProperty("line.separator") + " \"tags\": [\"home\", \"green\"]" + System.getProperty("line.separator") + "}"), headersToIgnore) ); // - in https assertEquals( response() .withHeader(HttpHeaders.CONTENT_TYPE, TEXT_PLAIN) .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body"), makeRequest( request() .setSecure(true) .withPath(calculatePath("some_path")) .withMethod("POST") .withBody("{" + System.getProperty("line.separator") + " \"id\": 1," + System.getProperty("line.separator") + " \"extra ignored array\": [\"one\", \"two\"]," + System.getProperty("line.separator") + " \"name\": \"A green door\"," + System.getProperty("line.separator") + " \"price\": 12.50," + System.getProperty("line.separator") + " \"tags\": [\"home\", \"green\"]" + System.getProperty("line.separator") + "}"), headersToIgnore) ); } @Test public void shouldReturnResponseByMatchingBodyWithJsonWithCharsetUTF8() { // when mockServerClient .when( request() .withBody(json("{" + System.getProperty("line.separator") + " \"ταυτότητα\": 1," + System.getProperty("line.separator") + " \"όνομα\": \"μια πράσινη πόρτα\"," + System.getProperty("line.separator") + " \"τιμή\": 12.50," + System.getProperty("line.separator") + " \"ετικέτες\": [\"σπίτι\", \"πράσινος\"]" + System.getProperty("line.separator") + "}", Charsets.UTF_16, MatchType.ONLY_MATCHING_FIELDS)), exactly(2) ) .respond( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body") ); // then // - in http assertEquals( response() .withHeader(HttpHeaders.CONTENT_TYPE, TEXT_PLAIN) .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body"), makeRequest( request() .withPath(calculatePath("some_path")) .withMethod("POST") .withBody(json("{" + System.getProperty("line.separator") + " \"ταυτότητα\": 1," + System.getProperty("line.separator") + " \"επιπλέον αγνοούνται τομέα\": \"κάποια αξία\"," + System.getProperty("line.separator") + " \"όνομα\": \"μια πράσινη πόρτα\"," + System.getProperty("line.separator") + " \"τιμή\": 12.50," + System.getProperty("line.separator") + " \"ετικέτες\": [\"σπίτι\", \"πράσινος\"]" + System.getProperty("line.separator") + "}", Charsets.UTF_16, MatchType.ONLY_MATCHING_FIELDS)), headersToIgnore) ); // - in https assertEquals( response() .withHeader(HttpHeaders.CONTENT_TYPE, TEXT_PLAIN) .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body"), makeRequest( request() .setSecure(true) .withPath(calculatePath("some_path")) .withMethod("POST") .withBody(json("{" + System.getProperty("line.separator") + " \"ταυτότητα\": 1," + System.getProperty("line.separator") + " \"επιπλέον αγνοούνται σειρά\": [\"ένας\", \"δυο\"]," + System.getProperty("line.separator") + " \"όνομα\": \"μια πράσινη πόρτα\"," + System.getProperty("line.separator") + " \"τιμή\": 12.50," + System.getProperty("line.separator") + " \"ετικέτες\": [\"σπίτι\", \"πράσινος\"]" + System.getProperty("line.separator") + "}", Charsets.UTF_16, MatchType.ONLY_MATCHING_FIELDS)), headersToIgnore) ); } @Test public void shouldReturnResponseByMatchingBodyWithJsonWithContentTypeHeader() { // when mockServerClient .when( request() .withBody(json("{" + System.getProperty("line.separator") + " \"ταυτότητα\": 1," + System.getProperty("line.separator") + " \"όνομα\": \"μια πράσινη πόρτα\"," + System.getProperty("line.separator") + " \"τιμή\": 12.50," + System.getProperty("line.separator") + " \"ετικέτες\": [\"σπίτι\", \"πράσινος\"]" + System.getProperty("line.separator") + "}", Charsets.UTF_16, MatchType.ONLY_MATCHING_FIELDS)), exactly(2) ) .respond( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body") ); // then // - in http assertEquals( response() .withHeader(HttpHeaders.CONTENT_TYPE, TEXT_PLAIN) .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body"), makeRequest( request() .withHeader(HttpHeaders.CONTENT_TYPE, MediaType.create("text", "plain").withCharset(Charsets.UTF_16).toString()) .withPath(calculatePath("some_path")) .withMethod("POST") .withBody(json("{" + System.getProperty("line.separator") + " \"ταυτότητα\": 1," + System.getProperty("line.separator") + " \"επιπλέον αγνοούνται τομέα\": \"κάποια αξία\"," + System.getProperty("line.separator") + " \"όνομα\": \"μια πράσινη πόρτα\"," + System.getProperty("line.separator") + " \"τιμή\": 12.50," + System.getProperty("line.separator") + " \"ετικέτες\": [\"σπίτι\", \"πράσινος\"]" + System.getProperty("line.separator") + "}")), headersToIgnore) ); // - in https assertEquals( response() .withHeader(HttpHeaders.CONTENT_TYPE, TEXT_PLAIN) .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body"), makeRequest( request() .setSecure(true) .withHeader(HttpHeaders.CONTENT_TYPE, MediaType.create("text", "plain").withCharset(Charsets.UTF_16).toString()) .withPath(calculatePath("some_path")) .withMethod("POST") .withBody(json("{" + System.getProperty("line.separator") + " \"ταυτότητα\": 1," + System.getProperty("line.separator") + " \"επιπλέον αγνοούνται σειρά\": [\"ένας\", \"δυο\"]," + System.getProperty("line.separator") + " \"όνομα\": \"μια πράσινη πόρτα\"," + System.getProperty("line.separator") + " \"τιμή\": 12.50," + System.getProperty("line.separator") + " \"ετικέτες\": [\"σπίτι\", \"πράσινος\"]" + System.getProperty("line.separator") + "}")), headersToIgnore) ); } @Test public void shouldReturnResponseByMatchingBodyWithJsonWithMatchType() { // when mockServerClient .when( request() .withBody(json("{" + System.getProperty("line.separator") + " \"id\": 1," + System.getProperty("line.separator") + " \"name\": \"A green door\"," + System.getProperty("line.separator") + " \"price\": 12.50," + System.getProperty("line.separator") + " \"tags\": [\"home\", \"green\"]" + System.getProperty("line.separator") + "}", MatchType.ONLY_MATCHING_FIELDS)), exactly(2) ) .respond( response() .withBody("some_body") ); // then // - in http assertEquals( response() .withBody("some_body").withHeader(HttpHeaders.CONTENT_TYPE, TEXT_PLAIN), makeRequest( request() .withPath(calculatePath("some_path")) .withMethod("POST") .withBody("{" + System.getProperty("line.separator") + " \"id\": 1," + System.getProperty("line.separator") + " \"extra field\": \"some value\"," + System.getProperty("line.separator") + " \"name\": \"A green door\"," + System.getProperty("line.separator") + " \"price\": 12.50," + System.getProperty("line.separator") + " \"tags\": [\"home\", \"green\"]" + System.getProperty("line.separator") + "}"), headersToIgnore) ); // - in https assertEquals( response() .withBody("some_body").withHeader(HttpHeaders.CONTENT_TYPE, TEXT_PLAIN), makeRequest( request() .setSecure(true) .withPath(calculatePath("some_path")) .withMethod("POST") .withBody("{" + System.getProperty("line.separator") + " \"id\": 1," + System.getProperty("line.separator") + " \"extra field\": \"some value\"," + System.getProperty("line.separator") + " \"name\": \"A green door\"," + System.getProperty("line.separator") + " \"price\": 12.50," + System.getProperty("line.separator") + " \"tags\": [\"home\", \"green\"]" + System.getProperty("line.separator") + "}"), headersToIgnore) ); } @Test public void shouldReturnResponseByMatchingBodyWithJsonSchema() { // when mockServerClient.when(request().withBody(jsonSchema("{" + System.getProperty("line.separator") + " \"$schema\": \"http://json-schema.org/draft-04/schema#\"," + System.getProperty("line.separator") + " \"title\": \"Product\"," + System.getProperty("line.separator") + " \"description\": \"A product from Acme's catalog\"," + System.getProperty("line.separator") + " \"type\": \"object\"," + System.getProperty("line.separator") + " \"properties\": {" + System.getProperty("line.separator") + " \"id\": {" + System.getProperty("line.separator") + " \"description\": \"The unique identifier for a product\"," + System.getProperty("line.separator") + " \"type\": \"integer\"" + System.getProperty("line.separator") + " }," + System.getProperty("line.separator") + " \"name\": {" + System.getProperty("line.separator") + " \"description\": \"Name of the product\"," + System.getProperty("line.separator") + " \"type\": \"string\"" + System.getProperty("line.separator") + " }," + System.getProperty("line.separator") + " \"price\": {" + System.getProperty("line.separator") + " \"type\": \"number\"," + System.getProperty("line.separator") + " \"minimum\": 0," + System.getProperty("line.separator") + " \"exclusiveMinimum\": true" + System.getProperty("line.separator") + " }," + System.getProperty("line.separator") + " \"tags\": {" + System.getProperty("line.separator") + " \"type\": \"array\"," + System.getProperty("line.separator") + " \"items\": {" + System.getProperty("line.separator") + " \"type\": \"string\"" + System.getProperty("line.separator") + " }," + System.getProperty("line.separator") + " \"minItems\": 1," + System.getProperty("line.separator") + " \"uniqueItems\": true" + System.getProperty("line.separator") + " }" + System.getProperty("line.separator") + " }," + System.getProperty("line.separator") + " \"required\": [\"id\", \"name\", \"price\"]" + System.getProperty("line.separator") + "}")), exactly(2)).respond(response().withBody("some_body")); // then // - in http assertEquals( response() .withHeader(HttpHeaders.CONTENT_TYPE, TEXT_PLAIN) .withStatusCode(HttpStatusCode.OK_200.code()) .withBody("some_body"), makeRequest( request() .withPath(calculatePath("some_path")) .withMethod("POST") .withBody("{" + System.getProperty("line.separator") + " \"id\": 1," + System.getProperty("line.separator") + " \"name\": \"A green door\"," + System.getProperty("line.separator") + " \"price\": 12.50," + System.getProperty("line.separator") + " \"tags\": [\"home\", \"green\"]" + System.getProperty("line.separator") + "}"), headersToIgnore) ); // - in https assertEquals( response() .withHeader(HttpHeaders.CONTENT_TYPE, TEXT_PLAIN) .withStatusCode(HttpStatusCode.OK_200.code()) .withBody("some_body"), makeRequest( request() .setSecure(true) .withPath(calculatePath("some_path")) .withMethod("POST") .withBody("{" + System.getProperty("line.separator") + " \"id\": 1," + System.getProperty("line.separator") + " \"name\": \"A green door\"," + System.getProperty("line.separator") + " \"price\": 12.50," + System.getProperty("line.separator") + " \"tags\": [\"home\", \"green\"]" + System.getProperty("line.separator") + "}"), headersToIgnore) ); } @Test public void shouldReturnPDFResponseByMatchingPath() throws IOException { // when byte[] pdfBytes = IOUtils.toByteArray(getClass().getClassLoader().getResourceAsStream("test.pdf")); mockServerClient .when( request() .withPath(calculatePath("ws/rest/user/[0-9]+/document/[0-9]+\\.pdf")) ) .respond( response() .withStatusCode(HttpStatusCode.OK_200.code()) .withHeaders( header(HttpHeaders.CONTENT_TYPE, MediaType.PDF.toString()), header(HttpHeaders.CONTENT_DISPOSITION, "form-data; name=\"test.pdf\"; filename=\"test.pdf\""), header(HttpHeaders.CACHE_CONTROL, "must-revalidate, post-check=0, pre-check=0") ) .withBody(binary(pdfBytes)) ); // then // - in http assertEquals( response() .withStatusCode(HttpStatusCode.OK_200.code()) .withHeaders( header(HttpHeaders.CONTENT_DISPOSITION, "form-data; name=\"test.pdf\"; filename=\"test.pdf\""), header(HttpHeaders.CACHE_CONTROL, "must-revalidate, post-check=0, pre-check=0"), header(HttpHeaders.CONTENT_TYPE, MediaType.PDF.toString()) ) .withBody(binary(pdfBytes)), makeRequest( request() .withPath(calculatePath("ws/rest/user/1/document/2.pdf")) .withMethod("GET"), headersToIgnore) ); // - in https assertEquals( response() .withStatusCode(HttpStatusCode.OK_200.code()) .withHeaders( header(HttpHeaders.CONTENT_DISPOSITION, "form-data; name=\"test.pdf\"; filename=\"test.pdf\""), header(HttpHeaders.CACHE_CONTROL, "must-revalidate, post-check=0, pre-check=0"), header(HttpHeaders.CONTENT_TYPE, MediaType.PDF.toString()) ) .withBody(binary(pdfBytes)), makeRequest( request() .setSecure(true) .withPath(calculatePath("ws/rest/user/1/document/2.pdf")) .withMethod("GET"), headersToIgnore) ); } @Test public void shouldReturnPNGResponseByMatchingPath() throws IOException { // when byte[] pngBytes = IOUtils.toByteArray(getClass().getClassLoader().getResourceAsStream("test.png")); mockServerClient .when( request() .withPath(calculatePath("ws/rest/user/[0-9]+/icon/[0-9]+\\.png")) ) .respond( response() .withStatusCode(HttpStatusCode.OK_200.code()) .withHeaders( header(HttpHeaders.CONTENT_TYPE, MediaType.PNG.toString()), header(HttpHeaders.CONTENT_DISPOSITION, "form-data; name=\"test.png\"; filename=\"test.png\"") ) .withBody(binary(pngBytes)) ); // then // - in http assertEquals( response() .withStatusCode(HttpStatusCode.OK_200.code()) .withHeaders( header(HttpHeaders.CONTENT_DISPOSITION, "form-data; name=\"test.png\"; filename=\"test.png\""), header(HttpHeaders.CONTENT_TYPE, MediaType.PNG.toString()) ) .withBody(binary(pngBytes)), makeRequest( request() .withPath(calculatePath("ws/rest/user/1/icon/1.png")) .withMethod("GET"), headersToIgnore) ); // - in https assertEquals( response() .withStatusCode(HttpStatusCode.OK_200.code()) .withHeaders( header(HttpHeaders.CONTENT_DISPOSITION, "form-data; name=\"test.png\"; filename=\"test.png\""), header(HttpHeaders.CONTENT_TYPE, MediaType.PNG.toString()) ) .withBody(binary(pngBytes)), makeRequest( request() .setSecure(true) .withPath(calculatePath("ws/rest/user/1/icon/1.png")) .withMethod("GET"), headersToIgnore) ); } @Test public void shouldReturnPDFResponseByMatchingBinaryPDFBody() throws IOException { // when byte[] pdfBytes = IOUtils.toByteArray(getClass().getClassLoader().getResourceAsStream("test.pdf")); mockServerClient .when( request().withBody(binary(pdfBytes)) ) .respond( response() .withStatusCode(HttpStatusCode.OK_200.code()) .withHeaders( header(HttpHeaders.CONTENT_TYPE, MediaType.PDF.toString()), header(HttpHeaders.CONTENT_DISPOSITION, "form-data; name=\"test.pdf\"; filename=\"test.pdf\""), header(HttpHeaders.CACHE_CONTROL, "must-revalidate, post-check=0, pre-check=0") ) .withBody(binary(pdfBytes)) ); // then // - in http assertEquals( response() .withStatusCode(HttpStatusCode.OK_200.code()) .withHeaders( header(HttpHeaders.CONTENT_DISPOSITION, "form-data; name=\"test.pdf\"; filename=\"test.pdf\""), header(HttpHeaders.CACHE_CONTROL, "must-revalidate, post-check=0, pre-check=0"), header(HttpHeaders.CONTENT_TYPE, MediaType.PDF.toString()) ) .withBody(binary(pdfBytes)), makeRequest( request() .withPath(calculatePath("ws/rest/user/1/document/2.pdf")) .withBody(binary(pdfBytes)) .withMethod("POST"), headersToIgnore) ); // - in https assertEquals( response() .withStatusCode(HttpStatusCode.OK_200.code()) .withHeaders( header(HttpHeaders.CONTENT_DISPOSITION, "form-data; name=\"test.pdf\"; filename=\"test.pdf\""), header(HttpHeaders.CACHE_CONTROL, "must-revalidate, post-check=0, pre-check=0"), header(HttpHeaders.CONTENT_TYPE, MediaType.PDF.toString()) ) .withBody(binary(pdfBytes)), makeRequest( request() .setSecure(true) .withPath(calculatePath("ws/rest/user/1/document/2.pdf")) .withBody(binary(pdfBytes)) .withMethod("POST"), headersToIgnore) ); } @Test public void shouldReturnPNGResponseByMatchingBinaryPNGBody() throws IOException { // when byte[] pngBytes = IOUtils.toByteArray(getClass().getClassLoader().getResourceAsStream("test.png")); mockServerClient .when( request().withBody(binary(pngBytes)) ) .respond( response() .withStatusCode(HttpStatusCode.OK_200.code()) .withHeaders( header(HttpHeaders.CONTENT_TYPE, MediaType.PNG.toString()), header(HttpHeaders.CONTENT_DISPOSITION, "form-data; name=\"test.png\"; filename=\"test.png\"") ) .withBody(binary(pngBytes)) ); // then // - in http assertEquals( response() .withStatusCode(HttpStatusCode.OK_200.code()) .withHeaders( header(HttpHeaders.CONTENT_DISPOSITION, "form-data; name=\"test.png\"; filename=\"test.png\""), header(HttpHeaders.CONTENT_TYPE, MediaType.PNG.toString()) ) .withBody(binary(pngBytes)), makeRequest( request() .withPath(calculatePath("ws/rest/user/1/icon/1.png")) .withBody(binary(pngBytes)) .withMethod("POST"), headersToIgnore) ); // - in https assertEquals( response() .withStatusCode(HttpStatusCode.OK_200.code()) .withHeaders( header(HttpHeaders.CONTENT_DISPOSITION, "form-data; name=\"test.png\"; filename=\"test.png\""), header(HttpHeaders.CONTENT_TYPE, MediaType.PNG.toString()) ) .withBody(binary(pngBytes)), makeRequest( request() .setSecure(true) .withPath(calculatePath("ws/rest/user/1/icon/1.png")) .withBody(binary(pngBytes)) .withMethod("POST"), headersToIgnore) ); } @Test public void shouldReturnResponseForExpectationWithDelay() { // when mockServerClient .when( request() .withPath(calculatePath("some_path1")) ) .respond( response() .withBody("some_body1") .withDelay(new Delay(TimeUnit.MILLISECONDS, 10)) ); mockServerClient .when( request() .withPath(calculatePath("some_path2")) ) .respond( response() .withBody("some_body2") .withDelay(new Delay(TimeUnit.MILLISECONDS, 20)) ); // then // - in http assertEquals( response() .withHeader(HttpHeaders.CONTENT_TYPE, TEXT_PLAIN) .withStatusCode(HttpStatusCode.OK_200.code()) .withBody("some_body2"), makeRequest( request() .withPath(calculatePath("some_path2")), headersToIgnore) ); assertEquals( response() .withHeader(HttpHeaders.CONTENT_TYPE, TEXT_PLAIN) .withStatusCode(HttpStatusCode.OK_200.code()) .withBody("some_body1"), makeRequest( request() .withPath(calculatePath("some_path1")), headersToIgnore) ); // - in https assertEquals( response() .withHeader(HttpHeaders.CONTENT_TYPE, TEXT_PLAIN) .withStatusCode(HttpStatusCode.OK_200.code()) .withBody("some_body2"), makeRequest( request() .setSecure(true) .withPath(calculatePath("some_path2")), headersToIgnore) ); assertEquals( response() .withHeader(HttpHeaders.CONTENT_TYPE, TEXT_PLAIN) .withStatusCode(HttpStatusCode.OK_200.code()) .withBody("some_body1"), makeRequest( request() .setSecure(true) .withPath(calculatePath("some_path1")), headersToIgnore) ); } @Test public void shouldReturnResponseByMatchingPathAndMethod() { // when mockServerClient .when( request() .withMethod("GET") .withPath(calculatePath("some_pathRequest")) ) .respond( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body_response") ); // then // - in http assertEquals( response() .withHeader(HttpHeaders.CONTENT_TYPE, TEXT_PLAIN) .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body_response"), makeRequest( request() .withMethod("GET") .withPath(calculatePath("some_pathRequest")) .withQueryStringParameters( param("queryStringParameterOneName", "queryStringParameterOneValue"), param("queryStringParameterTwoName", "queryStringParameterTwoValue") ) .withHeaders(header("headerNameRequest", "headerValueRequest")) .withCookies(cookie("cookieNameRequest", "cookieValueRequest")), headersToIgnore) ); // - in https assertEquals( response() .withHeader(HttpHeaders.CONTENT_TYPE, TEXT_PLAIN) .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body_response"), makeRequest( request() .withMethod("GET") .setSecure(true) .withPath(calculatePath("some_pathRequest")) .withQueryStringParameters( param("queryStringParameterOneName", "queryStringParameterOneValue"), param("queryStringParameterTwoName", "queryStringParameterTwoValue") ) .withHeaders(header("headerNameRequest", "headerValueRequest")) .withCookies(cookie("cookieNameRequest", "cookieValueRequest")), headersToIgnore) ); } @Test public void shouldReturnResponseByNotMatchingPathWithNotOperator() { // when mockServerClient .when( request() .withPath(not(calculatePath("some_path"))) ) .respond( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body_response") ); // then // - in http assertEquals( response() .withHeader(HttpHeaders.CONTENT_TYPE, TEXT_PLAIN) .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body_response"), makeRequest( request() .withPath(calculatePath("some_other_path")), headersToIgnore) ); // - in https assertEquals( response() .withHeader(HttpHeaders.CONTENT_TYPE, TEXT_PLAIN) .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body_response"), makeRequest( request() .withPath(calculatePath("some_other_path")), headersToIgnore) ); } @Test public void shouldReturnResponseByNotMatchingMethodWithNotOperator() { // when mockServerClient .when( request() .withMethod(not("GET")) ) .respond( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body_response") ); // then // - in http assertEquals( response() .withHeader(HttpHeaders.CONTENT_TYPE, TEXT_PLAIN) .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body_response"), makeRequest( request() .withMethod("POST"), headersToIgnore) ); // - in https assertEquals( response() .withHeader(HttpHeaders.CONTENT_TYPE, TEXT_PLAIN) .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body_response"), makeRequest( request() .withMethod("POST"), headersToIgnore) ); } @Test public void shouldReturnResponseByMatchingPathAndMethodAndBody() { // when mockServerClient .when( request() .withMethod("POST") .withPath(calculatePath("some_pathRequest")) .withBody("some_bodyRequest") ) .respond( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body_response") .withHeaders(header("headerNameResponse", "headerValueResponse")) ); // then // - in http assertEquals( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body_response") .withHeaders( header("headerNameResponse", "headerValueResponse"), header(HttpHeaders.CONTENT_TYPE, TEXT_PLAIN) ), makeRequest( request() .withMethod("POST") .withPath(calculatePath("some_pathRequest")) .withQueryStringParameters( param("queryStringParameterOneName", "queryStringParameterOneValue"), param("queryStringParameterTwoName", "queryStringParameterTwoValue") ) .withBody("some_bodyRequest") .withHeaders(header("headerNameRequest", "headerValueRequest")) .withCookies(cookie("cookieNameRequest", "cookieValueRequest")), headersToIgnore) ); // - in https assertEquals( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body_response") .withHeaders( header("headerNameResponse", "headerValueResponse"), header(HttpHeaders.CONTENT_TYPE, TEXT_PLAIN) ), makeRequest( request() .withMethod("POST") .setSecure(true) .withPath(calculatePath("some_pathRequest")) .withQueryStringParameters( param("queryStringParameterOneName", "queryStringParameterOneValue"), param("queryStringParameterTwoName", "queryStringParameterTwoValue") ) .withBody("some_bodyRequest") .withHeaders(header("headerNameRequest", "headerValueRequest")) .withCookies(cookie("cookieNameRequest", "cookieValueRequest")), headersToIgnore) ); } @Test public void shouldReturnResponseByMatchingPathAndMethodAndQueryStringParameters() { // when mockServerClient .when( request() .withMethod("GET") .withPath(calculatePath("some_pathRequest")) .withQueryStringParameters( param("queryStringParameterOneName", "queryStringParameterOneValue"), param("queryStringParameterTwoName", "queryStringParameterTwoValue") ) ) .respond( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body_response") .withCookies(cookie("cookieNameResponse", "cookieValueResponse")) ); // then // - in http assertEquals( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body_response") .withCookies(cookie("cookieNameResponse", "cookieValueResponse")) .withHeaders( header("Set-Cookie", "cookieNameResponse=cookieValueResponse"), header(HttpHeaders.CONTENT_TYPE, TEXT_PLAIN) ), makeRequest( request() .withMethod("GET") .withPath(calculatePath("some_pathRequest")) .withQueryStringParameters( param("queryStringParameterOneName", "queryStringParameterOneValue"), param("queryStringParameterTwoName", "queryStringParameterTwoValue") ) .withHeaders(header("headerNameRequest", "headerValueRequest")) .withCookies(cookie("cookieNameRequest", "cookieValueRequest")), headersToIgnore) ); // - in https assertEquals( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body_response") .withCookies(cookie("cookieNameResponse", "cookieValueResponse")) .withHeaders( header("Set-Cookie", "cookieNameResponse=cookieValueResponse"), header(HttpHeaders.CONTENT_TYPE, TEXT_PLAIN) ), makeRequest( request() .withMethod("GET") .setSecure(true) .withPath(calculatePath("some_pathRequest")) .withQueryStringParameters( param("queryStringParameterOneName", "queryStringParameterOneValue"), param("queryStringParameterTwoName", "queryStringParameterTwoValue") ) .withHeaders(header("headerNameRequest", "headerValueRequest")) .withCookies(cookie("cookieNameRequest", "cookieValueRequest")), headersToIgnore) ); } @Test public void shouldReturnResponseByMatchingPathAndMethodAndHeaders() { // when mockServerClient .when( request() .withMethod("GET") .withPath(calculatePath("some_pathRequest")) .withHeaders( header("requestHeaderNameOne", "requestHeaderValueOne_One", "requestHeaderValueOne_Two"), header("requestHeaderNameTwo", "requestHeaderValueTwo") ) ) .respond( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body_response") .withCookies(cookie("cookieNameResponse", "cookieValueResponse")) ); // then // - in http assertEquals( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body_response") .withCookies(cookie("cookieNameResponse", "cookieValueResponse")) .withHeaders( header("Set-Cookie", "cookieNameResponse=cookieValueResponse"), header(HttpHeaders.CONTENT_TYPE, TEXT_PLAIN) ), makeRequest( request() .withMethod("GET") .withPath(calculatePath("some_pathRequest")) .withHeaders( header("requestHeaderNameOne", "requestHeaderValueOne_One", "requestHeaderValueOne_Two"), header("requestHeaderNameTwo", "requestHeaderValueTwo") ) .withCookies(cookie("cookieNameRequest", "cookieValueRequest")), headersToIgnore) ); // - in https assertEquals( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body_response") .withCookies(cookie("cookieNameResponse", "cookieValueResponse")) .withHeaders( header("Set-Cookie", "cookieNameResponse=cookieValueResponse"), header(HttpHeaders.CONTENT_TYPE, TEXT_PLAIN) ), makeRequest( request() .withMethod("GET") .setSecure(true) .withPath(calculatePath("some_pathRequest")) .withHeaders( header("requestHeaderNameOne", "requestHeaderValueOne_One", "requestHeaderValueOne_Two"), header("requestHeaderNameTwo", "requestHeaderValueTwo") ) .withCookies(cookie("cookieNameRequest", "cookieValueRequest")), headersToIgnore) ); } @Test public void shouldReturnResponseByMatchingPathAndMethodAndCookies() { // when mockServerClient .when( request() .withMethod("GET") .withPath(calculatePath("some_pathRequest")) .withCookies( cookie("requestCookieNameOne", "requestCookieValueOne"), cookie("requestCookieNameTwo", "requestCookieValueTwo") ) ) .respond( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body_response") .withCookies( cookie("responseCookieNameOne", "responseCookieValueOne"), cookie("responseCookieNameTwo", "responseCookieValueTwo") ) ); // then // - in http - cookie objects assertEquals( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body_response") .withCookies( cookie("responseCookieNameOne", "responseCookieValueOne"), cookie("responseCookieNameTwo", "responseCookieValueTwo") ) .withHeaders( header("Set-Cookie", "responseCookieNameOne=responseCookieValueOne", "responseCookieNameTwo=responseCookieValueTwo"), header(HttpHeaders.CONTENT_TYPE, TEXT_PLAIN) ), makeRequest( request() .withMethod("GET") .withPath(calculatePath("some_pathRequest")) .withHeaders( header("headerNameRequest", "headerValueRequest"), header(HttpHeaders.CONTENT_TYPE, TEXT_PLAIN) ) .withCookies( cookie("requestCookieNameOne", "requestCookieValueOne"), cookie("requestCookieNameTwo", "requestCookieValueTwo") ), headersToIgnore) ); // - in http - cookie header assertEquals( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body_response") .withCookies( cookie("responseCookieNameOne", "responseCookieValueOne"), cookie("responseCookieNameTwo", "responseCookieValueTwo") ) .withHeaders( header("Set-Cookie", "responseCookieNameOne=responseCookieValueOne", "responseCookieNameTwo=responseCookieValueTwo"), header(HttpHeaders.CONTENT_TYPE, TEXT_PLAIN) ), makeRequest( request() .withMethod("GET") .withPath(calculatePath("some_pathRequest")) .withHeaders( header("headerNameRequest", "headerValueRequest"), header("Cookie", "requestCookieNameOne=requestCookieValueOne; requestCookieNameTwo=requestCookieValueTwo") ), headersToIgnore) ); // - in https - cookie objects assertEquals( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body_response") .withCookies( cookie("responseCookieNameOne", "responseCookieValueOne"), cookie("responseCookieNameTwo", "responseCookieValueTwo") ) .withHeaders( header("Set-Cookie", "responseCookieNameOne=responseCookieValueOne", "responseCookieNameTwo=responseCookieValueTwo"), header(HttpHeaders.CONTENT_TYPE, TEXT_PLAIN) ), makeRequest( request() .withMethod("GET") .setSecure(true) .withPath(calculatePath("some_pathRequest")) .withHeaders( header("headerNameRequest", "headerValueRequest") ) .withCookies( cookie("requestCookieNameOne", "requestCookieValueOne"), cookie("requestCookieNameTwo", "requestCookieValueTwo") ), headersToIgnore) ); // - in https - cookie header assertEquals( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body_response") .withCookies( cookie("responseCookieNameOne", "responseCookieValueOne"), cookie("responseCookieNameTwo", "responseCookieValueTwo") ) .withHeaders( header("Set-Cookie", "responseCookieNameOne=responseCookieValueOne", "responseCookieNameTwo=responseCookieValueTwo"), header(HttpHeaders.CONTENT_TYPE, TEXT_PLAIN) ), makeRequest( request() .withMethod("GET") .setSecure(true) .withPath(calculatePath("some_pathRequest")) .withHeaders( header("headerNameRequest", "headerValueRequest"), header("Cookie", "requestCookieNameOne=requestCookieValueOne; requestCookieNameTwo=requestCookieValueTwo") ), headersToIgnore) ); } @Test public void shouldReturnResponseByMatchingPathAndMethodAndQueryStringParametersAndBodyParameters() { // when mockServerClient .when( request() .withMethod("POST") .withPath(calculatePath("some_pathRequest")) .withQueryStringParameters( param("queryStringParameterOneName", "queryStringParameterOneValueOne", "queryStringParameterOneValueTwo"), param("queryStringParameterTwoName", "queryStringParameterTwoValue") ) .withBody(params(param("bodyParameterName", "bodyParameterValue"))) ) .respond( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body") ); // then // - in http - url query string assertEquals( response() .withHeader(HttpHeaders.CONTENT_TYPE, TEXT_PLAIN) .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body"), makeRequest( request() .withMethod("POST") .withPath(calculatePath("some_pathRequest")) .withQueryStringParameters( param("queryStringParameterOneName", "queryStringParameterOneValueOne", "queryStringParameterOneValueTwo"), param("queryStringParameterTwoName", "queryStringParameterTwoValue") ) .withBody(params(param("bodyParameterName", "bodyParameterValue"))), headersToIgnore) ); // - in https - query string parameter objects assertEquals( response() .withHeader(HttpHeaders.CONTENT_TYPE, TEXT_PLAIN) .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body"), makeRequest( request() .setSecure(true) .withMethod("POST") .withPath(calculatePath("some_pathRequest")) .withQueryStringParameters( param("queryStringParameterOneName", "queryStringParameterOneValueOne", "queryStringParameterOneValueTwo"), param("queryStringParameterTwoName", "queryStringParameterTwoValue") ) .withBody(params(param("bodyParameterName", "bodyParameterValue"))), headersToIgnore) ); } @Test public void shouldReturnResponseByMatchingPathAndMethodAndQueryStringParametersAndBody() { // when mockServerClient .when( request() .withMethod("POST") .withPath(calculatePath("some_pathRequest")) .withQueryStringParameters( param("queryStringParameterOneName", "queryStringParameterOneValueOne", "queryStringParameterOneValueTwo"), param("queryStringParameterTwoName", "queryStringParameterTwoValue") ) .withBody("some_bodyRequest") ) .respond( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body_response") .withHeaders(header("headerNameResponse", "headerValueResponse")) .withCookies(cookie("cookieNameResponse", "cookieValueResponse")) ); // then // - in http - url query string assertEquals( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body_response") .withCookies(cookie("cookieNameResponse", "cookieValueResponse")) .withHeaders( header("headerNameResponse", "headerValueResponse"), header("Set-Cookie", "cookieNameResponse=cookieValueResponse"), header(HttpHeaders.CONTENT_TYPE, TEXT_PLAIN) ), makeRequest( request() .withMethod("POST") .withPath(calculatePath("some_pathRequest")) .withQueryStringParameters( param("queryStringParameterOneName", "queryStringParameterOneValueOne", "queryStringParameterOneValueTwo"), param("queryStringParameterTwoName", "queryStringParameterTwoValue") ) .withBody("some_bodyRequest") .withHeaders(header("headerNameRequest", "headerValueRequest")) .withCookies(cookie("cookieNameRequest", "cookieValueRequest")), headersToIgnore) ); // - in http - query string parameter objects assertEquals( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body_response") .withCookies(cookie("cookieNameResponse", "cookieValueResponse")) .withHeaders( header("headerNameResponse", "headerValueResponse"), header("Set-Cookie", "cookieNameResponse=cookieValueResponse"), header(HttpHeaders.CONTENT_TYPE, TEXT_PLAIN) ), makeRequest( request() .withMethod("POST") .withPath(calculatePath("some_pathRequest")) .withQueryStringParameters( param("queryStringParameterOneName", "queryStringParameterOneValueOne", "queryStringParameterOneValueTwo"), param("queryStringParameterTwoName", "queryStringParameterTwoValue") ) .withBody("some_bodyRequest") .withHeaders(header("headerNameRequest", "headerValueRequest")) .withCookies(cookie("cookieNameRequest", "cookieValueRequest")), headersToIgnore) ); // - in https - url string and query string parameter objects assertEquals( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body_response") .withCookies(cookie("cookieNameResponse", "cookieValueResponse")) .withHeaders( header("headerNameResponse", "headerValueResponse"), header("Set-Cookie", "cookieNameResponse=cookieValueResponse"), header(HttpHeaders.CONTENT_TYPE, TEXT_PLAIN) ), makeRequest( request() .withMethod("POST") .withPath(calculatePath("some_pathRequest")) .withQueryStringParameters( param("queryStringParameterOneName", "queryStringParameterOneValueOne", "queryStringParameterOneValueTwo"), param("queryStringParameterTwoName", "queryStringParameterTwoValue") ) .withBody("some_bodyRequest") .withHeaders(header("headerNameRequest", "headerValueRequest")) .withCookies(cookie("cookieNameRequest", "cookieValueRequest")), headersToIgnore) ); } @Test public void shouldReturnResponseByMatchingPathAndMethodAndBodyParameters() { // when mockServerClient .when( request() .withMethod("POST") .withPath(calculatePath("some_pathRequest")) .withBody(params( param("bodyParameterOneName", "Parameter One Value One", "Parameter One Value Two"), param("bodyParameterTwoName", "Parameter Two") )) ) .respond( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body_response") .withHeaders(header("headerNameResponse", "headerValueResponse")) .withCookies(cookie("cookieNameResponse", "cookieValueResponse")) ); // then // - in http - body string assertEquals( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body_response") .withCookies(cookie("cookieNameResponse", "cookieValueResponse")) .withHeaders( header("headerNameResponse", "headerValueResponse"), header("Set-Cookie", "cookieNameResponse=cookieValueResponse"), header(HttpHeaders.CONTENT_TYPE, TEXT_PLAIN) ), makeRequest( request() .withMethod("POST") .withPath(calculatePath("some_pathRequest")) .withBody(new StringBody("bodyParameterOneName=Parameter+One+Value+One" + "&bodyParameterOneName=Parameter+One+Value+Two" + "&bodyParameterTwoName=Parameter+Two")) .withHeaders(header("headerNameRequest", "headerValueRequest")) .withCookies(cookie("cookieNameRequest", "cookieValueRequest")), headersToIgnore) ); // - in http - body parameter objects assertEquals( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body_response") .withCookies(cookie("cookieNameResponse", "cookieValueResponse")) .withHeaders( header("headerNameResponse", "headerValueResponse"), header("Set-Cookie", "cookieNameResponse=cookieValueResponse"), header(HttpHeaders.CONTENT_TYPE, TEXT_PLAIN) ), makeRequest( request() .withMethod("POST") .withPath(calculatePath("some_pathRequest")) .withBody(params( param("bodyParameterOneName", "Parameter One Value One", "Parameter One Value Two"), param("bodyParameterTwoName", "Parameter Two") )) .withHeaders(header("headerNameRequest", "headerValueRequest")) .withCookies(cookie("cookieNameRequest", "cookieValueRequest")), headersToIgnore) ); // - in https - url string and query string parameter objects assertEquals( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body_response") .withCookies(cookie("cookieNameResponse", "cookieValueResponse")) .withHeaders( header("headerNameResponse", "headerValueResponse"), header("Set-Cookie", "cookieNameResponse=cookieValueResponse"), header(HttpHeaders.CONTENT_TYPE, TEXT_PLAIN) ), makeRequest( request() .withMethod("POST") .withPath(calculatePath("some_pathRequest")) .withBody(params( param("bodyParameterOneName", "Parameter One Value One", "Parameter One Value Two"), param("bodyParameterTwoName", "Parameter Two") )) .withHeaders(header("headerNameRequest", "headerValueRequest")) .withCookies(cookie("cookieNameRequest", "cookieValueRequest")), headersToIgnore) ); } @Test public void shouldReturnResponseByMatchingPathAndMethodAndParametersAndHeadersAndCookies() { // when mockServerClient .when( request() .withMethod("PUT") .withPath(calculatePath("some_pathRequest")) .withBody(new StringBody("bodyParameterOneName=Parameter+One+Value+One" + "&bodyParameterOneName=Parameter+One+Value+Two" + "&bodyParameterTwoName=Parameter+Two")) .withHeaders(header("headerNameRequest", "headerValueRequest")) .withCookies(cookie("cookieNameRequest", "cookieValueRequest")) ) .respond( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body_response") .withHeaders(header("headerNameResponse", "headerValueResponse")) .withCookies(cookie("cookieNameResponse", "cookieValueResponse")) ); // then // - in http - body string assertEquals( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body_response") .withCookies(cookie("cookieNameResponse", "cookieValueResponse")) .withHeaders( header("headerNameResponse", "headerValueResponse"), header("Set-Cookie", "cookieNameResponse=cookieValueResponse"), header(HttpHeaders.CONTENT_TYPE, TEXT_PLAIN) ), makeRequest( request() .withMethod("PUT") .withPath(calculatePath("some_pathRequest")) .withBody(new StringBody("bodyParameterOneName=Parameter+One+Value+One" + "&bodyParameterOneName=Parameter+One+Value+Two" + "&bodyParameterTwoName=Parameter+Two")) .withHeaders( header("headerNameRequest", "headerValueRequest"), header("Cookie", "cookieNameRequest=cookieValueRequest") ), headersToIgnore) ); // - in http - body parameter objects assertEquals( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body_response") .withCookies(cookie("cookieNameResponse", "cookieValueResponse")) .withHeaders( header("headerNameResponse", "headerValueResponse"), header("Set-Cookie", "cookieNameResponse=cookieValueResponse"), header(HttpHeaders.CONTENT_TYPE, TEXT_PLAIN) ), makeRequest( request() .withMethod("PUT") .withPath(calculatePath("some_pathRequest")) .withBody(params( param("bodyParameterOneName", "Parameter One Value One", "Parameter One Value Two"), param("bodyParameterTwoName", "Parameter Two") )) .withHeaders(header("headerNameRequest", "headerValueRequest")) .withCookies(cookie("cookieNameRequest", "cookieValueRequest")), headersToIgnore) ); } @Test public void shouldReturnResponseByNotMatchingBodyParameterWithNotOperatorForNameAndValue() { // when mockServerClient .when( request() .withMethod("POST") .withPath(calculatePath("some_pathRequest")) .withBody(params( param(not("bodyParameterOneName"), not("Parameter One Value One"), not("Parameter One Value Two")), param("bodyParameterTwoName", "Parameter Two") )) ) .respond( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body_response") ); // then // wrong query string parameter name assertEquals( response() .withHeader(HttpHeaders.CONTENT_TYPE, TEXT_PLAIN) .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body_response"), makeRequest( request() .withMethod("POST") .withPath(calculatePath("some_pathRequest")) .withBody(params( param("OTHERBodyParameterOneName", "Parameter One Value One", "Parameter One Value Two"), param("bodyParameterTwoName", "Parameter Two") )) .withHeaders(header("headerNameRequest", "headerValueRequest")) .withCookies(cookie("cookieNameRequest", "cookieValueRequest")), headersToIgnore) ); // wrong query string parameter name assertEquals( response() .withHeader(HttpHeaders.CONTENT_TYPE, TEXT_PLAIN) .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body_response"), makeRequest( request() .withMethod("POST") .withPath(calculatePath("some_pathRequest")) .withBody(new StringBody("OTHERBodyParameterOneName=Parameter+One+Value+One" + "&OTHERBodyParameterOneName=Parameter+One+Value+Two" + "&bodyParameterTwoName=Parameter+Two")) .withHeaders(header("headerNameRequest", "headerValueRequest")) .withCookies(cookie("cookieNameRequest", "cookieValueRequest")), headersToIgnore) ); // wrong query string parameter value assertEquals( response() .withHeader(HttpHeaders.CONTENT_TYPE, TEXT_PLAIN) .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body_response"), makeRequest( request() .withMethod("POST") .withPath(calculatePath("some_pathRequest")) .withBody(params( param("bodyParameterOneName", "OTHER Parameter One Value One", "OTHER Parameter One Value Two"), param("bodyParameterTwoName", "Parameter Two") )) .withHeaders(header("headerNameRequest", "headerValueRequest")) .withCookies(cookie("cookieNameRequest", "cookieValueRequest")), headersToIgnore) ); // wrong query string parameter value assertEquals( response() .withHeader(HttpHeaders.CONTENT_TYPE, TEXT_PLAIN) .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body_response"), makeRequest( request() .withMethod("POST") .withPath(calculatePath("some_pathRequest")) .withBody(new StringBody("bodyParameterOneName=OTHER Parameter+One+Value+One" + "&bodyParameterOneName=OTHER Parameter+One+Value+Two" + "&bodyParameterTwoName=Parameter+Two")) .withHeaders(header("headerNameRequest", "headerValueRequest")) .withCookies(cookie("cookieNameRequest", "cookieValueRequest")), headersToIgnore) ); } @Test public void shouldReturnResponseByNotMatchingBodyParameterWithNotOperatorForName() { // when mockServerClient .when( request() .withMethod("POST") .withPath(calculatePath("some_pathRequest")) .withBody(params( param(not("bodyParameterOneName"), string("Parameter One Value One"), string("Parameter One Value Two")), param("bodyParameterTwoName", "Parameter Two") )) ) .respond( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body_response") ); // then // wrong query string parameter name assertEquals( response() .withHeader(HttpHeaders.CONTENT_TYPE, TEXT_PLAIN) .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body_response"), makeRequest( request() .withMethod("POST") .withPath(calculatePath("some_pathRequest")) .withBody(params( param("OTHERBodyParameterOneName", "Parameter One Value One", "Parameter One Value Two"), param("bodyParameterTwoName", "Parameter Two") )) .withHeaders(header("headerNameRequest", "headerValueRequest")) .withCookies(cookie("cookieNameRequest", "cookieValueRequest")), headersToIgnore) ); // wrong query string parameter name assertEquals( response() .withHeader(HttpHeaders.CONTENT_TYPE, TEXT_PLAIN) .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body_response"), makeRequest( request() .withMethod("POST") .withPath(calculatePath("some_pathRequest")) .withBody(new StringBody("OTHERBodyParameterOneName=Parameter+One+Value+One" + "&OTHERBodyParameterOneName=Parameter+One+Value+Two" + "&bodyParameterTwoName=Parameter+Two")) .withHeaders(header("headerNameRequest", "headerValueRequest")) .withCookies(cookie("cookieNameRequest", "cookieValueRequest")), headersToIgnore) ); } @Test public void shouldReturnResponseByNotMatchingBodyParameterWithNotOperatorForValue() { // when mockServerClient .when( request() .withMethod("POST") .withPath(calculatePath("some_pathRequest")) .withBody(params( param(string("bodyParameterOneName"), not("Parameter One Value One"), not("Parameter One Value Two")), param("bodyParameterTwoName", "Parameter Two") )) ) .respond( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body_response") ); // then // wrong query string parameter value assertEquals( response() .withHeader(HttpHeaders.CONTENT_TYPE, TEXT_PLAIN) .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body_response"), makeRequest( request() .withMethod("POST") .withPath(calculatePath("some_pathRequest")) .withBody(params( param("bodyParameterOneName", "OTHER Parameter One Value One", "OTHER Parameter One Value Two"), param("bodyParameterTwoName", "Parameter Two") )) .withHeaders(header("headerNameRequest", "headerValueRequest")) .withCookies(cookie("cookieNameRequest", "cookieValueRequest")), headersToIgnore) ); // wrong query string parameter value assertEquals( response() .withHeader(HttpHeaders.CONTENT_TYPE, TEXT_PLAIN) .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body_response"), makeRequest( request() .withMethod("POST") .withPath(calculatePath("some_pathRequest")) .withBody(new StringBody("bodyParameterOneName=OTHER Parameter+One+Value+One" + "&bodyParameterOneName=OTHER Parameter+One+Value+Two" + "&bodyParameterTwoName=Parameter+Two")) .withHeaders(header("headerNameRequest", "headerValueRequest")) .withCookies(cookie("cookieNameRequest", "cookieValueRequest")), headersToIgnore) ); } @Test public void shouldReturnResponseByNotMatchingQueryStringParameterWithNotOperatorForNameAndValue() { // when mockServerClient .when( request() .withMethod("POST") .withPath(calculatePath("some_pathRequest")) .withQueryStringParameters( param(not("queryStringParameterOneName"), not("Parameter One Value One"), not("Parameter One Value Two")), param("queryStringParameterTwoName", "Parameter Two") ) ) .respond( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body_response") ); // then // wrong query string parameter name assertEquals( response() .withHeader(HttpHeaders.CONTENT_TYPE, TEXT_PLAIN) .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body_response"), makeRequest( request() .withMethod("POST") .withPath(calculatePath("some_pathRequest")) .withQueryStringParameters( param("OTHERQueryStringParameterOneName", "Parameter One Value One", "Parameter One Value Two"), param("queryStringParameterTwoName", "Parameter Two") ), headersToIgnore) ); // wrong query string parameter value assertEquals( response() .withHeader(HttpHeaders.CONTENT_TYPE, TEXT_PLAIN) .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body_response"), makeRequest( request() .withMethod("POST") .withPath(calculatePath("some_pathRequest")) .withQueryStringParameters( param("queryStringParameterOneName", "OTHER Parameter One Value One", "OTHER Parameter One Value Two"), param("queryStringParameterTwoName", "Parameter Two") ), headersToIgnore) ); } @Test public void shouldReturnResponseByNotMatchingQueryStringParameterWithNotOperatorForName() { // when mockServerClient .when( request() .withMethod("POST") .withPath(calculatePath("some_pathRequest")) .withQueryStringParameters( param(not("queryStringParameterOneName"), string("Parameter One Value One"), string("Parameter One Value Two")), param("queryStringParameterTwoName", "Parameter Two") ) ) .respond( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body_response") ); // then // wrong query string parameter name assertEquals( response() .withHeader(HttpHeaders.CONTENT_TYPE, TEXT_PLAIN) .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body_response"), makeRequest( request() .withMethod("POST") .withPath(calculatePath("some_pathRequest")) .withQueryStringParameters( param("OTHERQueryStringParameterOneName", "Parameter One Value One", "Parameter One Value Two"), param("queryStringParameterTwoName", "Parameter Two") ), headersToIgnore) ); } @Test public void shouldReturnResponseByNotMatchingQueryStringParameterWithNotOperatorForValue() { // when mockServerClient .when( request() .withMethod("POST") .withPath(calculatePath("some_pathRequest")) .withQueryStringParameters( param(string("queryStringParameterOneName"), not("Parameter One Value One"), not("Parameter One Value Two")), param("queryStringParameterTwoName", "Parameter Two") ) ) .respond( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body_response") ); // then // wrong query string parameter value assertEquals( response() .withHeader(HttpHeaders.CONTENT_TYPE, TEXT_PLAIN) .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body_response"), makeRequest( request() .withMethod("POST") .withPath(calculatePath("some_pathRequest")) .withQueryStringParameters( param("queryStringParameterOneName", "OTHER Parameter One Value One", "OTHER Parameter One Value Two"), param("queryStringParameterTwoName", "Parameter Two") ), headersToIgnore) ); } @Test public void shouldReturnResponseByNotMatchingCookieWithNotOperatorForNameAndValue() { // when mockServerClient .when( request() .withMethod("GET") .withPath(calculatePath("some_pathRequest")) .withCookies( cookie(not("requestCookieNameOne"), not("requestCookieValueOne")), cookie("requestCookieNameTwo", "requestCookieValueTwo") ) ) .respond( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body_response") ); // then // wrong query string cookie name assertEquals( response() .withHeader(HttpHeaders.CONTENT_TYPE, TEXT_PLAIN) .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body_response"), makeRequest( request() .withMethod("GET") .withPath(calculatePath("some_pathRequest")) .withCookies( cookie("OTHERrequestCookieNameOne", "requestCookieValueOne"), cookie("requestCookieNameTwo", "requestCookieValueTwo") ), headersToIgnore) ); // wrong query string cookie value assertEquals( response() .withHeader(HttpHeaders.CONTENT_TYPE, TEXT_PLAIN) .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body_response"), makeRequest( request() .withMethod("GET") .withPath(calculatePath("some_pathRequest")) .withCookies( cookie("requestCookieNameOne", "OTHERrequestCookieValueOne"), cookie("requestCookieNameTwo", "requestCookieValueTwo") ), headersToIgnore) ); } @Test public void shouldReturnResponseByNotMatchingCookieWithNotOperatorForName() { // when mockServerClient .when( request() .withMethod("GET") .withPath(calculatePath("some_pathRequest")) .withCookies( cookie(not("requestCookieNameOne"), string("requestCookieValueOne")), cookie("requestCookieNameTwo", "requestCookieValueTwo") ) ) .respond( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body_response") ); // then // wrong query string cookie name assertEquals( response() .withHeader(HttpHeaders.CONTENT_TYPE, TEXT_PLAIN) .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body_response"), makeRequest( request() .withMethod("GET") .withPath(calculatePath("some_pathRequest")) .withCookies( cookie("OTHERrequestCookieNameOne", "requestCookieValueOne"), cookie("requestCookieNameTwo", "requestCookieValueTwo") ), headersToIgnore) ); } @Test public void shouldReturnResponseByNotMatchingCookieWithNotOperatorForValue() { // when mockServerClient .when( request() .withMethod("GET") .withPath(calculatePath("some_pathRequest")) .withCookies( cookie(string("requestCookieNameOne"), not("requestCookieValueOne")), cookie("requestCookieNameTwo", "requestCookieValueTwo") ) ) .respond( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body_response") ); // then // wrong query string cookie value assertEquals( response() .withHeader(HttpHeaders.CONTENT_TYPE, TEXT_PLAIN) .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body_response"), makeRequest( request() .withMethod("GET") .withPath(calculatePath("some_pathRequest")) .withCookies( cookie("requestCookieNameOne", "OTHERrequestCookieValueOne"), cookie("requestCookieNameTwo", "requestCookieValueTwo") ), headersToIgnore) ); } @Test public void shouldReturnResponseByNotMatchingHeaderWithNotOperatorForNameAndValue() { // when mockServerClient .when( request() .withMethod("GET") .withPath(calculatePath("some_pathRequest")) .withHeaders( header(not("requestHeaderNameOne"), not("requestHeaderValueOne")), header("requestHeaderNameTwo", "requestHeaderValueTwo") ) ) .respond( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body_response") ); // then // wrong query string header name assertEquals( response() .withHeader(HttpHeaders.CONTENT_TYPE, TEXT_PLAIN) .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body_response"), makeRequest( request() .withMethod("GET") .withPath(calculatePath("some_pathRequest")) .withHeaders( header("OTHERrequestHeaderNameOne", "requestHeaderValueOne"), header("requestHeaderNameTwo", "requestHeaderValueTwo") ), headersToIgnore) ); // wrong query string header value assertEquals( response() .withHeader(HttpHeaders.CONTENT_TYPE, TEXT_PLAIN) .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body_response"), makeRequest( request() .withMethod("GET") .withPath(calculatePath("some_pathRequest")) .withHeaders( header("requestHeaderNameOne", "OTHERrequestHeaderValueOne"), header("requestHeaderNameTwo", "requestHeaderValueTwo") ), headersToIgnore) ); } @Test public void shouldReturnResponseByNotMatchingHeaderWithNotOperatorForName() { // when mockServerClient .when( request() .withMethod("GET") .withPath(calculatePath("some_pathRequest")) .withHeaders( header(not("requestHeaderNameOne"), string("requestHeaderValueOne")), header("requestHeaderNameTwo", "requestHeaderValueTwo") ) ) .respond( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body_response") ); // then // wrong query string header name assertEquals( response() .withHeader(HttpHeaders.CONTENT_TYPE, TEXT_PLAIN) .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body_response"), makeRequest( request() .withMethod("GET") .withPath(calculatePath("some_pathRequest")) .withHeaders( header("OTHERrequestHeaderNameOne", "requestHeaderValueOne"), header("requestHeaderNameTwo", "requestHeaderValueTwo") ), headersToIgnore) ); } @Test public void shouldReturnResponseByNotMatchingHeaderWithNotOperatorForValue() { // when mockServerClient .when( request() .withMethod("GET") .withPath(calculatePath("some_pathRequest")) .withHeaders( header(string("requestHeaderNameOne"), not("requestHeaderValueOne")), header("requestHeaderNameTwo", "requestHeaderValueTwo") ) ) .respond( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body_response") ); // then // wrong query string header value assertEquals( response() .withHeader(HttpHeaders.CONTENT_TYPE, TEXT_PLAIN) .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body_response"), makeRequest( request() .withMethod("GET") .withPath(calculatePath("some_pathRequest")) .withHeaders( header("requestHeaderNameOne", "OTHERrequestHeaderValueOne"), header("requestHeaderNameTwo", "requestHeaderValueTwo") ), headersToIgnore) ); } @Test public void shouldNotReturnResponseForWhenTimeToLiveExpired() { // when mockServerClient .when( request().withPath(calculatePath("some_path")), exactly(2), TimeToLive.exactly(TimeUnit.SECONDS, 5L) ) .respond( response().withBody("some_body").withDelay(TimeUnit.SECONDS, 5L) ); // then assertEquals( response() .withHeader(HttpHeaders.CONTENT_TYPE, TEXT_PLAIN) .withStatusCode(HttpStatusCode.OK_200.code()) .withBody("some_body"), makeRequest( request() .withPath(calculatePath("some_path")), headersToIgnore) ); // - in http assertEquals( response() .withHeader(HttpHeaders.CONTENT_TYPE, TEXT_PLAIN) .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()), makeRequest( request() .withPath(calculatePath("some_path")), headersToIgnore) ); // - in https assertEquals( response() .withHeader(HttpHeaders.CONTENT_TYPE, TEXT_PLAIN) .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()), makeRequest( request() .setSecure(true) .withPath(calculatePath("some_path")), headersToIgnore) ); } @Test public void shouldNotReturnResponseForNonMatchingBody() { // when mockServerClient .when( request() .withMethod("GET") .withPath(calculatePath("some_path")) .withQueryStringParameters( param("queryStringParameterOneName", "queryStringParameterOneValue"), param("queryStringParameterTwoName", "queryStringParameterTwoValue") ) .withBody(exact("some_body")) .withHeaders(header("headerName", "headerValue")) .withCookies(cookie("cookieName", "cookieValue")) ) .respond( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body") .withHeaders(header("headerName", "headerValue")) .withCookies(cookie("cookieName", "cookieValue")) ); // then // - in http assertEquals( response() .withHeader(HttpHeaders.CONTENT_TYPE, TEXT_PLAIN) .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()), makeRequest( request() .withMethod("GET") .withPath(calculatePath("some_path")) .withQueryStringParameters( param("queryStringParameterOneName", "queryStringParameterOneValue"), param("queryStringParameterTwoName", "queryStringParameterTwoValue") ) .withBody(exact("some_other_body")) .withHeaders(header("headerName", "headerValue")) .withCookies(cookie("cookieName", "cookieValue")), headersToIgnore) ); // - in https assertEquals( response() .withHeader(HttpHeaders.CONTENT_TYPE, TEXT_PLAIN) .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()), makeRequest( request() .withMethod("GET") .setSecure(true) .withPath(calculatePath("some_path")) .withQueryStringParameters( param("queryStringParameterOneName", "queryStringParameterOneValue"), param("queryStringParameterTwoName", "queryStringParameterTwoValue") ) .withBody(exact("some_other_body")) .withHeaders(header("headerName", "headerValue")) .withCookies(cookie("cookieName", "cookieValue")), headersToIgnore) ); } @Test public void shouldNotReturnResponseForMatchingBodyWithNotOperator() { // when mockServerClient .when( request() .withBody(Not.not(json("{" + System.getProperty("line.separator") + " \"id\": 1," + System.getProperty("line.separator") + " \"name\": \"A green door\"," + System.getProperty("line.separator") + " \"price\": 12.50," + System.getProperty("line.separator") + " \"tags\": [\"home\", \"green\"]" + System.getProperty("line.separator") + "}"))), exactly(2) ) .respond( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body") ); // then // - in http assertEquals( response() .withHeader(HttpHeaders.CONTENT_TYPE, TEXT_PLAIN) .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()), makeRequest( request() .withPath(calculatePath("some_path")) .withMethod("POST") .withBody("{" + System.getProperty("line.separator") + " \"id\": 1," + System.getProperty("line.separator") + " \"extra_ignored_field\": \"some value\"," + System.getProperty("line.separator") + " \"name\": \"A green door\"," + System.getProperty("line.separator") + " \"price\": 12.50," + System.getProperty("line.separator") + " \"tags\": [\"home\", \"green\"]" + System.getProperty("line.separator") + "}"), headersToIgnore) ); // - in https assertEquals( response() .withHeader(HttpHeaders.CONTENT_TYPE, TEXT_PLAIN) .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()), makeRequest( request() .setSecure(true) .withPath(calculatePath("some_path")) .withMethod("POST") .withBody("{" + System.getProperty("line.separator") + " \"id\": 1," + System.getProperty("line.separator") + " \"extra_ignored_array\": [\"one\", \"two\"]," + System.getProperty("line.separator") + " \"name\": \"A green door\"," + System.getProperty("line.separator") + " \"price\": 12.50," + System.getProperty("line.separator") + " \"tags\": [\"home\", \"green\"]" + System.getProperty("line.separator") + "}"), headersToIgnore) ); } @Test public void shouldNotReturnResponseForNonMatchingXPathBody() { // when mockServerClient.when(request().withBody(new XPathBody("/bookstore/book[price>35]/price")), exactly(2)).respond(response().withBody("some_body")); // then // - in http assertEquals( response() .withHeader(HttpHeaders.CONTENT_TYPE, TEXT_PLAIN) .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()), makeRequest( request() .setSecure(true) .withPath(calculatePath("some_path")) .withMethod("POST") .withBody(new StringBody("" + "<?xml version=\"1.0\" encoding=\"ISO-8859-1\"?>" + System.getProperty("line.separator") + "<bookstore>" + System.getProperty("line.separator") + " <book category=\"COOKING\">" + System.getProperty("line.separator") + " <title lang=\"en\">Everyday Italian</title>" + System.getProperty("line.separator") + " <author>Giada De Laurentiis</author>" + System.getProperty("line.separator") + " <year>2005</year>" + System.getProperty("line.separator") + " <price>30.00</price>" + System.getProperty("line.separator") + " </book>" + System.getProperty("line.separator") + " <book category=\"CHILDREN\">" + System.getProperty("line.separator") + " <title lang=\"en\">Harry Potter</title>" + System.getProperty("line.separator") + " <author>J K. Rowling</author>" + System.getProperty("line.separator") + " <year>2005</year>" + System.getProperty("line.separator") + " <price>29.99</price>" + System.getProperty("line.separator") + " </book>" + System.getProperty("line.separator") + " <book category=\"WEB\">" + System.getProperty("line.separator") + " <title lang=\"en\">Learning XML</title>" + System.getProperty("line.separator") + " <author>Erik T. Ray</author>" + System.getProperty("line.separator") + " <year>2003</year>" + System.getProperty("line.separator") + " <price>31.95</price>" + System.getProperty("line.separator") + " </book>" + System.getProperty("line.separator") + "</bookstore>")), headersToIgnore) ); // - in https assertEquals( response() .withHeader(HttpHeaders.CONTENT_TYPE, TEXT_PLAIN) .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()), makeRequest( request() .setSecure(true) .withPath(calculatePath("some_path")) .withMethod("POST") .withBody(new StringBody("" + "<?xml version=\"1.0\" encoding=\"ISO-8859-1\"?>" + System.getProperty("line.separator") + "<bookstore>" + System.getProperty("line.separator") + " <book category=\"COOKING\">" + System.getProperty("line.separator") + " <title lang=\"en\">Everyday Italian</title>" + System.getProperty("line.separator") + " <author>Giada De Laurentiis</author>" + System.getProperty("line.separator") + " <year>2005</year>" + System.getProperty("line.separator") + " <price>30.00</price>" + System.getProperty("line.separator") + " </book>" + System.getProperty("line.separator") + " <book category=\"CHILDREN\">" + System.getProperty("line.separator") + " <title lang=\"en\">Harry Potter</title>" + System.getProperty("line.separator") + " <author>J K. Rowling</author>" + System.getProperty("line.separator") + " <year>2005</year>" + System.getProperty("line.separator") + " <price>29.99</price>" + System.getProperty("line.separator") + " </book>" + System.getProperty("line.separator") + " <book category=\"WEB\">" + System.getProperty("line.separator") + " <title lang=\"en\">Learning XML</title>" + System.getProperty("line.separator") + " <author>Erik T. Ray</author>" + System.getProperty("line.separator") + " <year>2003</year>" + System.getProperty("line.separator") + " <price>31.95</price>" + System.getProperty("line.separator") + " </book>" + System.getProperty("line.separator") + "</bookstore>")), headersToIgnore) ); } @Test public void shouldNotReturnResponseForNonMatchingJsonBody() { // when mockServerClient.when(request().withBody(json("{" + System.getProperty("line.separator") + " \"id\": 1," + System.getProperty("line.separator") + " \"name\": \"A green door\"," + System.getProperty("line.separator") + " \"price\": 12.50," + System.getProperty("line.separator") + " \"tags\": [\"home\", \"green\"]" + System.getProperty("line.separator") + "}")), exactly(2)).respond(response().withBody("some_body")); // then // - in http assertEquals( response() .withHeader(HttpHeaders.CONTENT_TYPE, TEXT_PLAIN) .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()), makeRequest( request() .withPath(calculatePath("some_path")) .withMethod("POST") .withBody("{" + System.getProperty("line.separator") + " \"id\": 1," + System.getProperty("line.separator") + " \"name\": \"---- XXXX WRONG VALUE XXXX ----\"," + System.getProperty("line.separator") + " \"price\": 12.50," + System.getProperty("line.separator") + " \"tags\": [\"home\", \"green\"]" + System.getProperty("line.separator") + "}"), headersToIgnore) ); // - in https assertEquals( response() .withHeader(HttpHeaders.CONTENT_TYPE, TEXT_PLAIN) .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()), makeRequest( request() .setSecure(true) .withPath(calculatePath("some_path")) .withMethod("POST") .withBody("{" + System.getProperty("line.separator") + " \"id\": 1," + System.getProperty("line.separator") + " \"name\": \"---- XXXX WRONG VALUE XXXX ----\"," + System.getProperty("line.separator") + " \"price\": 12.50," + System.getProperty("line.separator") + " \"tags\": [\"home\", \"green\"]" + System.getProperty("line.separator") + "}"), headersToIgnore) ); } @Test public void shouldNotReturnResponseForNonMatchingJsonBodyWithMatchType() { // when mockServerClient .when( request() .withBody(json("{" + System.getProperty("line.separator") + " \"id\": 1," + System.getProperty("line.separator") + " \"name\": \"A green door\"," + System.getProperty("line.separator") + " \"price\": 12.50," + System.getProperty("line.separator") + " \"tags\": [\"home\", \"green\"]" + System.getProperty("line.separator") + "}", MatchType.STRICT)), exactly(2)) .respond( response() .withBody("some_body") ); // then // - in http assertEquals( response() .withHeader(HttpHeaders.CONTENT_TYPE, TEXT_PLAIN) .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()), makeRequest( request() .withPath(calculatePath("some_path")) .withMethod("POST") .withBody("{" + System.getProperty("line.separator") + " \"id\": 1," + System.getProperty("line.separator") + " \"extra field\": \"some value\"," + System.getProperty("line.separator") + " \"name\": \"A green door\"," + System.getProperty("line.separator") + " \"price\": 12.50," + System.getProperty("line.separator") + " \"tags\": [\"home\", \"green\"]" + System.getProperty("line.separator") + "}"), headersToIgnore) ); // - in https assertEquals( response() .withHeader(HttpHeaders.CONTENT_TYPE, TEXT_PLAIN) .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()), makeRequest( request() .setSecure(true) .withPath(calculatePath("some_path")) .withMethod("POST") .withBody("{" + System.getProperty("line.separator") + " \"id\": 1," + System.getProperty("line.separator") + " \"extra field\": \"some value\"," + System.getProperty("line.separator") + " \"name\": \"A green door\"," + System.getProperty("line.separator") + " \"price\": 12.50," + System.getProperty("line.separator") + " \"tags\": [\"home\", \"green\"]" + System.getProperty("line.separator") + "}"), headersToIgnore) ); } @Test public void shouldNotReturnResponseForNonMatchingJsonSchema() { // when mockServerClient.when(request().withBody(jsonSchema("{" + System.getProperty("line.separator") + " \"$schema\": \"http://json-schema.org/draft-04/schema#\"," + System.getProperty("line.separator") + " \"title\": \"Product\"," + System.getProperty("line.separator") + " \"description\": \"A product from Acme's catalog\"," + System.getProperty("line.separator") + " \"type\": \"object\"," + System.getProperty("line.separator") + " \"properties\": {" + System.getProperty("line.separator") + " \"id\": {" + System.getProperty("line.separator") + " \"description\": \"The unique identifier for a product\"," + System.getProperty("line.separator") + " \"type\": \"integer\"" + System.getProperty("line.separator") + " }," + System.getProperty("line.separator") + " \"name\": {" + System.getProperty("line.separator") + " \"description\": \"Name of the product\"," + System.getProperty("line.separator") + " \"type\": \"string\"" + System.getProperty("line.separator") + " }," + System.getProperty("line.separator") + " \"price\": {" + System.getProperty("line.separator") + " \"type\": \"number\"," + System.getProperty("line.separator") + " \"minimum\": 0," + System.getProperty("line.separator") + " \"exclusiveMinimum\": true" + System.getProperty("line.separator") + " }," + System.getProperty("line.separator") + " \"tags\": {" + System.getProperty("line.separator") + " \"type\": \"array\"," + System.getProperty("line.separator") + " \"items\": {" + System.getProperty("line.separator") + " \"type\": \"string\"" + System.getProperty("line.separator") + " }," + System.getProperty("line.separator") + " \"minItems\": 1," + System.getProperty("line.separator") + " \"uniqueItems\": true" + System.getProperty("line.separator") + " }" + System.getProperty("line.separator") + " }," + System.getProperty("line.separator") + " \"required\": [\"id\", \"name\", \"price\"]" + System.getProperty("line.separator") + "}")), exactly(2)).respond(response().withBody("some_body")); // then // - in http assertEquals( response() .withHeader(HttpHeaders.CONTENT_TYPE, TEXT_PLAIN) .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()), makeRequest( request() .withPath(calculatePath("some_path")) .withMethod("POST") .withBody("{" + System.getProperty("line.separator") + " \"id\": 1," + System.getProperty("line.separator") + " \"wrong field name\": \"A green door\"," + System.getProperty("line.separator") + " \"price\": 12.50," + System.getProperty("line.separator") + " \"tags\": [\"home\", \"green\"]" + System.getProperty("line.separator") + "}"), headersToIgnore) ); // - in https assertEquals( response() .withHeader(HttpHeaders.CONTENT_TYPE, TEXT_PLAIN) .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()), makeRequest( request() .setSecure(true) .withPath(calculatePath("some_path")) .withMethod("POST") .withBody("{" + System.getProperty("line.separator") + " \"id\": 1," + System.getProperty("line.separator") + " \"name\": \"A green door\"," + System.getProperty("line.separator") + " \"wrong field name\": 12.50," + System.getProperty("line.separator") + " \"tags\": [\"home\", \"green\"]" + System.getProperty("line.separator") + "}"), headersToIgnore) ); } @Test public void shouldNotReturnResponseForNonMatchingPath() { // when mockServerClient .when( request() .withMethod("GET") .withPath(calculatePath("some_path")) .withQueryStringParameters( param("queryStringParameterOneName", "queryStringParameterOneValue"), param("queryStringParameterTwoName", "queryStringParameterTwoValue") ) .withBody(exact("some_body")) .withHeaders(header("headerName", "headerValue")) .withCookies(cookie("cookieName", "cookieValue")) ) .respond( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body") .withHeaders(header("headerName", "headerValue")) .withCookies(cookie("cookieName", "cookieValue")) ); // then // - in http assertEquals( response() .withHeader(HttpHeaders.CONTENT_TYPE, TEXT_PLAIN) .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()), makeRequest( request() .withMethod("GET") .withPath(calculatePath("some_other_path")) .withQueryStringParameters( param("queryStringParameterOneName", "queryStringParameterOneValue"), param("queryStringParameterTwoName", "queryStringParameterTwoValue") ) .withBody(exact("some_body")) .withHeaders(header("headerName", "headerValue")) .withCookies(cookie("cookieName", "cookieValue")), headersToIgnore) ); // - in https assertEquals( response() .withHeader(HttpHeaders.CONTENT_TYPE, TEXT_PLAIN) .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()), makeRequest( request() .withMethod("GET") .setSecure(true) .withPath(calculatePath("some_other_path")) .withQueryStringParameters( param("queryStringParameterOneName", "queryStringParameterOneValue"), param("queryStringParameterTwoName", "queryStringParameterTwoValue") ) .withBody(exact("some_body")) .withHeaders(header("headerName", "headerValue")) .withCookies(cookie("cookieName", "cookieValue")), headersToIgnore) ); } @Test public void shouldNotReturnResponseForMatchingPathWithNotOperator() { // when mockServerClient .when( request() .withPath(not(calculatePath("some_path"))) ) .respond( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body_response") ); // then // - in http assertEquals( response() .withHeader(HttpHeaders.CONTENT_TYPE, TEXT_PLAIN) .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()), makeRequest( request() .withPath(calculatePath("some_path")), headersToIgnore) ); // - in https assertEquals( response() .withHeader(HttpHeaders.CONTENT_TYPE, TEXT_PLAIN) .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()), makeRequest( request() .withPath(calculatePath("some_path")), headersToIgnore) ); } @Test public void shouldNotReturnResponseForMatchingMethodWithNotOperator() { // when mockServerClient .when( request() .withMethod(not("GET")) ) .respond( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body_response") ); // then // - in http assertEquals( response() .withHeader(HttpHeaders.CONTENT_TYPE, TEXT_PLAIN) .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()), makeRequest( request() .withMethod("GET"), headersToIgnore) ); // - in https assertEquals( response() .withHeader(HttpHeaders.CONTENT_TYPE, TEXT_PLAIN) .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()), makeRequest( request() .withMethod("GET"), headersToIgnore) ); } @Test public void shouldNotReturnResponseForNonMatchingBodyParameterName() { // when mockServerClient .when( request() .withMethod("POST") .withPath(calculatePath("some_pathRequest")) .withBody(params( param("bodyParameterOneName", "Parameter One Value One", "Parameter One Value Two"), param("bodyParameterTwoName", "Parameter Two") )) ) .respond( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body_response") .withHeaders(header("headerNameResponse", "headerValueResponse")) .withCookies(cookie("cookieNameResponse", "cookieValueResponse")) ); // then // wrong query string parameter name assertEquals( response() .withHeader(HttpHeaders.CONTENT_TYPE, TEXT_PLAIN) .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()), makeRequest( request() .withMethod("POST") .withPath(calculatePath("some_pathRequest")) .withBody(params( param("OTHERBodyParameterOneName", "Parameter One Value One", "Parameter One Value Two"), param("bodyParameterTwoName", "Parameter Two") )) .withHeaders(header("headerNameRequest", "headerValueRequest")) .withCookies(cookie("cookieNameRequest", "cookieValueRequest")), headersToIgnore) ); // wrong query string parameter name assertEquals( response() .withHeader(HttpHeaders.CONTENT_TYPE, TEXT_PLAIN) .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()), makeRequest( request() .withMethod("POST") .withPath(calculatePath("some_pathRequest")) .withBody(new StringBody("OTHERBodyParameterOneName=Parameter+One+Value+One" + "&bodyParameterOneName=Parameter+One+Value+Two" + "&bodyParameterTwoName=Parameter+Two")) .withHeaders(header("headerNameRequest", "headerValueRequest")) .withCookies(cookie("cookieNameRequest", "cookieValueRequest")), headersToIgnore) ); } @Test public void shouldNotReturnResponseForMatchingBodyParameterWithNotOperator() { // when mockServerClient .when( request() .withMethod("POST") .withPath(calculatePath("some_pathRequest")) .withBody(params( param(not("bodyParameterOneName"), not("Parameter One Value One"), not("Parameter One Value Two")), param("bodyParameterTwoName", "Parameter Two") )) ) .respond( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body_response") ); // then // wrong query string parameter name assertEquals( response() .withHeader(HttpHeaders.CONTENT_TYPE, TEXT_PLAIN) .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()), makeRequest( request() .withMethod("POST") .withPath(calculatePath("some_pathRequest")) .withBody(params( param("bodyParameterOneName", "Parameter One Value One", "Parameter One Value Two"), param("bodyParameterTwoName", "Parameter Two") )) .withHeaders(header("headerNameRequest", "headerValueRequest")) .withCookies(cookie("cookieNameRequest", "cookieValueRequest")), headersToIgnore) ); // wrong query string parameter name assertEquals( response() .withHeader(HttpHeaders.CONTENT_TYPE, TEXT_PLAIN) .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()), makeRequest( request() .withMethod("POST") .withPath(calculatePath("some_pathRequest")) .withBody(new StringBody("bodyParameterOneName=Other Parameter+One+Value+One" + "&bodyParameterOneName=Parameter+One+Value+Two" + "&bodyParameterTwoName=Parameter+Two")) .withHeaders(header("headerNameRequest", "headerValueRequest")) .withCookies(cookie("cookieNameRequest", "cookieValueRequest")), headersToIgnore) ); } @Test public void shouldNotReturnResponseForNonMatchingBodyParameterValue() { // when mockServerClient .when( request() .withMethod("POST") .withPath(calculatePath("some_pathRequest")) .withBody(params( param("bodyParameterOneName", "Parameter One Value One", "Parameter One Value Two"), param("bodyParameterTwoName", "Parameter Two") )) ) .respond( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body_response") .withHeaders(header("headerNameResponse", "headerValueResponse")) .withCookies(cookie("cookieNameResponse", "cookieValueResponse")) ); // then // wrong body parameter value assertEquals( response() .withHeader(HttpHeaders.CONTENT_TYPE, TEXT_PLAIN) .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()), makeRequest( request() .withMethod("POST") .withPath(calculatePath("some_pathRequest")) .withBody(params( param("bodyParameterOneName", "Other Parameter One Value One", "Parameter One Value Two"), param("bodyParameterTwoName", "Parameter Two") )) .withHeaders(header("headerNameRequest", "headerValueRequest")) .withCookies(cookie("cookieNameRequest", "cookieValueRequest")), headersToIgnore) ); // wrong body parameter value assertEquals( response() .withHeader(HttpHeaders.CONTENT_TYPE, TEXT_PLAIN) .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()), makeRequest( request() .withMethod("POST") .withPath(calculatePath("some_pathRequest")) .withBody(new StringBody("bodyParameterOneName=Other Parameter+One+Value+One" + "&bodyParameterOneName=Parameter+One+Value+Two" + "&bodyParameterTwoName=Parameter+Two")) .withHeaders(header("headerNameRequest", "headerValueRequest")) .withCookies(cookie("cookieNameRequest", "cookieValueRequest")), headersToIgnore) ); } @Test public void shouldNotReturnResponseForNonMatchingQueryStringParameterName() { // when mockServerClient .when( request() .withMethod("POST") .withPath(calculatePath("some_pathRequest")) .withQueryStringParameters( param("queryStringParameterOneName", "queryStringParameterOneValueOne", "queryStringParameterOneValueTwo"), param("queryStringParameterTwoName", "queryStringParameterTwoValue") ) .withBody("some_bodyRequest") ) .respond( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body_response") .withHeaders(header("headerNameResponse", "headerValueResponse")) .withCookies(cookie("cookieNameResponse", "cookieValueResponse")) ); // then // wrong query string parameter name assertEquals( response() .withHeader(HttpHeaders.CONTENT_TYPE, TEXT_PLAIN) .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()), makeRequest( request() .withMethod("POST") .withPath(calculatePath("some_pathRequest")) .withQueryStringParameters( param("OTHERQueryStringParameterOneName", "queryStringParameterOneValueOne", "queryStringParameterOneValueTwo"), param("queryStringParameterTwoName", "queryStringParameterTwoValue") ) .withBody("some_bodyRequest") .withHeaders( header("headerNameRequest", "headerValueRequest") ) .withCookies(cookie("cookieNameRequest", "cookieValueRequest")), headersToIgnore) ); } @Test public void shouldNotReturnResponseForNonMatchingQueryStringParameterValue() { // when mockServerClient .when( request() .withMethod("POST") .withPath(calculatePath("some_pathRequest")) .withQueryStringParameters( param("queryStringParameterOneName", "queryStringParameterOneValueOne", "queryStringParameterOneValueTwo"), param("queryStringParameterTwoName", "queryStringParameterTwoValue") ) .withBody("some_bodyRequest") ) .respond( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body_response") .withHeaders(header("headerNameResponse", "headerValueResponse")) .withCookies(cookie("cookieNameResponse", "cookieValueResponse")) ); // then // wrong query string parameter value assertEquals( response() .withHeader(HttpHeaders.CONTENT_TYPE, TEXT_PLAIN) .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()), makeRequest( request() .withMethod("POST") .withPath(calculatePath("some_pathRequest")) .withQueryStringParameters( param("queryStringParameterOneName", "OTHERqueryStringParameterOneValueOne", "queryStringParameterOneValueTwo"), param("queryStringParameterTwoName", "queryStringParameterTwoValue") ) .withBody("some_bodyRequest") .withHeaders(header("headerNameRequest", "headerValueRequest")) .withCookies(cookie("cookieNameRequest", "cookieValueRequest")), headersToIgnore) ); } @Test public void shouldNotReturnResponseForMatchingQueryStringParameterWithNotOperator() { // when mockServerClient .when( request() .withMethod("POST") .withPath(calculatePath("some_pathRequest")) .withQueryStringParameters( param(not("queryStringParameterOneName"), not("Parameter One Value One"), not("Parameter One Value Two")), param("queryStringParameterTwoName", "Parameter Two") ) ) .respond( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body_response") ); // then // wrong query string parameter name assertEquals( response() .withHeader(HttpHeaders.CONTENT_TYPE, TEXT_PLAIN) .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()), makeRequest( request() .withMethod("POST") .withPath(calculatePath("some_pathRequest")) .withQueryStringParameters( param("queryStringParameterOneName", "Parameter One Value One", "Parameter One Value Two"), param("queryStringParameterTwoName", "Parameter Two") ), headersToIgnore) ); // wrong query string parameter name assertEquals( response() .withHeader(HttpHeaders.CONTENT_TYPE, TEXT_PLAIN) .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()), makeRequest( request() .withMethod("POST") .withPath(calculatePath("some_pathRequest")) .withQueryStringParameters( param("queryStringParameterOneName", "Parameter One Value One", "Parameter One Value Two"), param("queryStringParameterTwoName", "Parameter Two") ), headersToIgnore) ); } @Test public void shouldNotReturnResponseForNonMatchingCookieName() { // when mockServerClient .when( request() .withMethod("GET") .withPath(calculatePath("some_path")) .withQueryStringParameters( param("queryStringParameterOneName", "queryStringParameterOneValue"), param("queryStringParameterTwoName", "queryStringParameterTwoValue") ) .withBody(exact("some_body")) .withHeaders(header("headerName", "headerValue")) .withCookies(cookie("cookieName", "cookieValue")) ) .respond( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body") .withHeaders(header("headerName", "headerValue")) .withCookies(cookie("cookieName", "cookieValue")) ); // then // - in http assertEquals( response() .withHeader(HttpHeaders.CONTENT_TYPE, TEXT_PLAIN) .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()), makeRequest( request() .withMethod("GET") .withPath(calculatePath("some_path")) .withQueryStringParameters( param("queryStringParameterOneName", "queryStringParameterOneValue"), param("queryStringParameterTwoName", "queryStringParameterTwoValue") ) .withBody(exact("some_body")) .withHeaders(header("headerName", "headerValue")) .withCookies(cookie("cookieOtherName", "cookieValue")), headersToIgnore) ); // - in https assertEquals( response() .withHeader(HttpHeaders.CONTENT_TYPE, TEXT_PLAIN) .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()), makeRequest( request() .withMethod("GET") .setSecure(true) .withPath(calculatePath("some_path")) .withQueryStringParameters( param("queryStringParameterOneName", "queryStringParameterOneValue"), param("queryStringParameterTwoName", "queryStringParameterTwoValue") ) .withBody(exact("some_body")) .withHeaders(header("headerName", "headerValue")) .withCookies(cookie("cookieOtherName", "cookieValue")), headersToIgnore) ); } @Test public void shouldNotReturnResponseForNonMatchingCookieValue() { // when mockServerClient .when( request() .withMethod("GET") .withPath(calculatePath("some_path")) .withQueryStringParameters( param("queryStringParameterOneName", "queryStringParameterOneValue"), param("queryStringParameterTwoName", "queryStringParameterTwoValue") ) .withBody(exact("some_body")) .withHeaders(header("headerName", "headerValue")) .withCookies(cookie("cookieName", "cookieValue")) ) .respond( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body") .withHeaders(header("headerName", "headerValue")) .withCookies(cookie("cookieName", "cookieValue")) ); // then // - in http assertEquals( response() .withHeader(HttpHeaders.CONTENT_TYPE, TEXT_PLAIN) .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()), makeRequest( request() .withMethod("GET") .withPath(calculatePath("some_path")) .withQueryStringParameters( param("queryStringParameterOneName", "queryStringParameterOneValue"), param("queryStringParameterTwoName", "queryStringParameterTwoValue") ) .withBody(exact("some_body")) .withHeaders(header("headerName", "headerValue")) .withCookies(cookie("cookieName", "cookieOtherValue")), headersToIgnore) ); // - in https assertEquals( response() .withHeader(HttpHeaders.CONTENT_TYPE, TEXT_PLAIN) .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()), makeRequest( request() .withMethod("GET") .setSecure(true) .withPath(calculatePath("some_path")) .withQueryStringParameters( param("queryStringParameterOneName", "queryStringParameterOneValue"), param("queryStringParameterTwoName", "queryStringParameterTwoValue") ) .withBody(exact("some_body")) .withHeaders(header("headerName", "headerValue")) .withCookies(cookie("cookieName", "cookieOtherValue")), headersToIgnore) ); } @Test public void shouldNotReturnResponseForMatchingCookieWithNotOperator() { // when mockServerClient .when( request() .withMethod("GET") .withPath(calculatePath("some_pathRequest")) .withCookies( cookie(not("requestCookieNameOne"), not("requestCookieValueOne")), cookie("requestCookieNameTwo", "requestCookieValueTwo") ) ) .respond( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body_response") ); // then // wrong query string parameter name assertEquals( response() .withHeader(HttpHeaders.CONTENT_TYPE, TEXT_PLAIN) .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()), makeRequest( request() .withMethod("GET") .withPath(calculatePath("some_pathRequest")) .withCookies( cookie("requestCookieNameOne", "requestCookieValueOne"), cookie("requestCookieNameTwo", "requestCookieValueTwo") ), headersToIgnore) ); // wrong query string parameter name assertEquals( response() .withHeader(HttpHeaders.CONTENT_TYPE, TEXT_PLAIN) .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()), makeRequest( request() .withMethod("GET") .withPath(calculatePath("some_pathRequest")) .withCookies( cookie("requestCookieNameOne", "requestCookieValueOne"), cookie("requestCookieNameTwo", "requestCookieValueTwo") ), headersToIgnore) ); } @Test public void shouldNotReturnResponseForNonMatchingHeaderName() { // when mockServerClient .when( request() .withMethod("GET") .withPath(calculatePath("some_path")) .withQueryStringParameters( param("queryStringParameterOneName", "queryStringParameterOneValue"), param("queryStringParameterTwoName", "queryStringParameterTwoValue") ) .withBody(exact("some_body")) .withHeaders(header("headerName", "headerValue")) .withCookies(cookie("cookieName", "cookieValue")) ) .respond( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body") .withHeaders(header("headerName", "headerValue")) .withCookies(cookie("cookieName", "cookieValue")) ); // then // - in http assertEquals( response() .withHeader(HttpHeaders.CONTENT_TYPE, TEXT_PLAIN) .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()), makeRequest( request() .withMethod("GET") .withPath(calculatePath("some_path")) .withQueryStringParameters( param("queryStringParameterOneName", "queryStringParameterOneValue"), param("queryStringParameterTwoName", "queryStringParameterTwoValue") ) .withBody(exact("some_body")) .withHeaders(header("headerOtherName", "headerValue")) .withCookies(cookie("cookieName", "cookieValue")), headersToIgnore) ); // - in https assertEquals( response() .withHeader(HttpHeaders.CONTENT_TYPE, TEXT_PLAIN) .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()), makeRequest( request() .withMethod("GET") .setSecure(true) .withPath(calculatePath("some_path")) .withQueryStringParameters( param("queryStringParameterOneName", "queryStringParameterOneValue"), param("queryStringParameterTwoName", "queryStringParameterTwoValue") ) .withBody(exact("some_body")) .withHeaders(header("headerOtherName", "headerValue")) .withCookies(cookie("cookieName", "cookieValue")), headersToIgnore) ); } @Test public void shouldNotReturnResponseForNonMatchingHeaderValue() { // when mockServerClient .when( request() .withMethod("GET") .withPath(calculatePath("some_path")) .withQueryStringParameters( param("queryStringParameterOneName", "queryStringParameterOneValue"), param("queryStringParameterTwoName", "queryStringParameterTwoValue") ) .withBody(exact("some_body")) .withHeaders(header("headerName", "headerValue")) .withCookies(cookie("cookieName", "cookieValue")) ) .respond( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body") .withHeaders(header("headerName", "headerValue")) .withCookies(cookie("cookieName", "cookieValue")) ); // then // - in http assertEquals( response() .withHeader(HttpHeaders.CONTENT_TYPE, TEXT_PLAIN) .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()), makeRequest( request() .withMethod("GET") .withPath(calculatePath("some_path")) .withQueryStringParameters( param("queryStringParameterOneName", "queryStringParameterOneValue"), param("queryStringParameterTwoName", "queryStringParameterTwoValue") ) .withBody(exact("some_body")) .withHeaders(header("headerName", "headerOtherValue")) .withCookies(cookie("cookieName", "cookieValue")), headersToIgnore) ); // - in https assertEquals( response() .withHeader(HttpHeaders.CONTENT_TYPE, TEXT_PLAIN) .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()), makeRequest( request() .withMethod("GET") .setSecure(true) .withPath(calculatePath("some_path")) .withQueryStringParameters( param("queryStringParameterOneName", "queryStringParameterOneValue"), param("queryStringParameterTwoName", "queryStringParameterTwoValue") ) .withBody(exact("some_body")) .withHeaders(header("headerName", "headerOtherValue")) .withCookies(cookie("cookieName", "cookieValue")), headersToIgnore) ); } @Test public void shouldNotReturnResponseForMatchingHeaderWithNotOperator() { // when mockServerClient .when( request() .withMethod("GET") .withPath(calculatePath("some_pathRequest")) .withHeaders( header(not("requestHeaderNameOne"), not("requestHeaderValueOne")), header("requestHeaderNameTwo", "requestHeaderValueTwo") ) ) .respond( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withBody("some_body_response") ); // then // wrong query string parameter name assertEquals( response() .withHeader(HttpHeaders.CONTENT_TYPE, TEXT_PLAIN) .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()), makeRequest( request() .withMethod("GET") .withPath(calculatePath("some_pathRequest")) .withHeaders( header("requestHeaderNameOne", "requestHeaderValueOne"), header("requestHeaderNameTwo", "requestHeaderValueTwo") ), headersToIgnore) ); // wrong query string parameter name assertEquals( response() .withHeader(HttpHeaders.CONTENT_TYPE, TEXT_PLAIN) .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()), makeRequest( request() .withMethod("GET") .withPath(calculatePath("some_pathRequest")) .withHeaders( header("requestHeaderNameOne", "requestHeaderValueOne"), header("requestHeaderNameTwo", "requestHeaderValueTwo") ), headersToIgnore) ); } @Test public void shouldClearExpectations() { // given mockServerClient .when( request() .withPath(calculatePath("some_path1")) ) .respond( response() .withBody("some_body1") ); mockServerClient .when( request() .withPath(calculatePath("some_path2")) ) .respond( response() .withBody("some_body2") ); // when mockServerClient .clear( request() .withPath(calculatePath("some_path1")) ); // then // - in http assertEquals( response() .withHeader(HttpHeaders.CONTENT_TYPE, TEXT_PLAIN) .withStatusCode(HttpStatusCode.OK_200.code()) .withBody("some_body2"), makeRequest( request() .withPath(calculatePath("some_path2")), headersToIgnore) ); assertEquals( response() .withHeader(HttpHeaders.CONTENT_TYPE, TEXT_PLAIN) .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()), makeRequest( request() .withPath(calculatePath("some_path1")), headersToIgnore) ); // - in https assertEquals( response() .withHeader(HttpHeaders.CONTENT_TYPE, TEXT_PLAIN) .withStatusCode(HttpStatusCode.OK_200.code()) .withBody("some_body2"), makeRequest( request() .setSecure(true) .withPath(calculatePath("some_path2")), headersToIgnore) ); assertEquals( response() .withHeader(HttpHeaders.CONTENT_TYPE, TEXT_PLAIN) .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()), makeRequest( request() .setSecure(true) .withPath(calculatePath("some_path1")), headersToIgnore) ); } @Test public void shouldReset() { // given mockServerClient .when( request() .withPath(calculatePath("some_path1")) ) .respond( response() .withBody("some_body1") ); mockServerClient .when( request() .withPath(calculatePath("some_path2")) ) .respond( response() .withBody("some_body2") ); // when mockServerClient.reset(); // then // - in http assertEquals( response() .withHeader(HttpHeaders.CONTENT_TYPE, TEXT_PLAIN) .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()), makeRequest( request() .withPath(calculatePath("some_path1")), headersToIgnore) ); assertEquals( response() .withHeader(HttpHeaders.CONTENT_TYPE, TEXT_PLAIN) .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()), makeRequest( request() .withPath(calculatePath("some_path2")), headersToIgnore) ); // - in https assertEquals( response() .withHeader(HttpHeaders.CONTENT_TYPE, TEXT_PLAIN) .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()), makeRequest( request() .setSecure(true) .withPath(calculatePath("some_path1")), headersToIgnore) ); assertEquals( response() .withHeader(HttpHeaders.CONTENT_TYPE, TEXT_PLAIN) .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()), makeRequest( request() .setSecure(true) .withPath(calculatePath("some_path2")), headersToIgnore) ); } @Test public void shouldEnsureThatRequestDelaysDoNotAffectOtherRequests() throws Exception { mockServerClient .when( request("/slow") ) .respond( response("super slow") .withDelay(new Delay(TimeUnit.SECONDS, 8)) ); mockServerClient .when( request("/fast") ) .respond( response("quite fast") ); ExecutorService executorService = Executors.newFixedThreadPool(2); Future<Long> slowFuture = executorService.submit(new Callable<Long>() { @Override public Long call() throws Exception { long start = System.currentTimeMillis(); makeRequest(request("/slow")); return System.currentTimeMillis() - start; } }); // Let fast request come to the server slightly after slow request Uninterruptibles.sleepUninterruptibly(1, TimeUnit.SECONDS); Future<Long> fastFuture = executorService.submit(new Callable<Long>() { @Override public Long call() throws Exception { long start = System.currentTimeMillis(); makeRequest(request("/fast")); return System.currentTimeMillis() - start; } }); Long slowRequestElapsedMillis = slowFuture.get(); Long fastRequestElapsedMillis = fastFuture.get(); assertThat("Slow request takes less than expected", slowRequestElapsedMillis, is(greaterThan(7 * 1000L))); assertThat("Fast request takes longer than expected", fastRequestElapsedMillis, is(lessThan(3 * 1000L))); } protected HttpResponse makeRequest(HttpRequest httpRequest) { return makeRequest(httpRequest, Collections.<String>emptySet()); } protected HttpResponse makeRequest(HttpRequest httpRequest, Collection<String> headersToIgnore) { int attemptsRemaining = 10; while (attemptsRemaining > 0) { try { int port = (httpRequest.isSecure() ? getMockServerSecurePort() : getMockServerPort()); HttpResponse httpResponse = httpClient.sendRequest(outboundRequest("localhost", port, servletContext, httpRequest)); List<Header> headers = new ArrayList<Header>(); for (Header header : httpResponse.getHeaders()) { if (!headersToIgnore.contains(header.getName().getValue().toLowerCase())) { if (header.getName().getValue().equalsIgnoreCase(HttpHeaders.CONTENT_TYPE)) { // this fixes Tomcat which removes the space between // media type and charset in the Content-Type header for (NottableString value : new ArrayList<NottableString>(header.getValues())) { header.getValues().clear(); header.addValues(value.getValue().replace(";charset", "; charset")); } } headers.add(header); } } httpResponse.withHeaders(headers); return httpResponse; } catch (SocketConnectionException caught) { attemptsRemaining--; logger.info("Retrying connection to mock server, attempts remaining: " + attemptsRemaining); try { TimeUnit.MILLISECONDS.sleep(500); } catch (InterruptedException e) { // do nothing } } } throw new RuntimeException("Failed to send request:" + System.getProperty("line.separator") + httpRequest); } }
gitter-badger/mockserver
mockserver-integration-testing/src/main/java/org/mockserver/integration/server/AbstractClientServerIntegrationTest.java
934
package org.mockserver.integration.server; import com.google.common.base.Charsets; import com.google.common.net.MediaType; import com.google.common.util.concurrent.Uninterruptibles; import org.apache.commons.io.IOUtils; import org.junit.Test; import org.mockserver.client.serialization.ExpectationSerializer; import org.mockserver.client.serialization.HttpRequestSerializer; import org.mockserver.client.serialization.java.ExpectationToJavaSerializer; import org.mockserver.echo.http.EchoServer; import org.mockserver.logging.MockServerLogger; import org.mockserver.matchers.MatchType; import org.mockserver.matchers.TimeToLive; import org.mockserver.mock.Expectation; import org.mockserver.model.*; import org.mockserver.verify.VerificationTimes; import java.io.IOException; import java.util.Arrays; import java.util.Collections; import java.util.concurrent.*; import static io.netty.handler.codec.http.HttpHeaderNames.*; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.*; import static org.hamcrest.core.Is.is; import static org.hamcrest.core.StringStartsWith.startsWith; import static org.hamcrest.number.OrderingComparison.greaterThan; import static org.junit.Assert.assertEquals; import static org.junit.Assert.fail; import static org.mockserver.character.Character.NEW_LINE; import static org.mockserver.matchers.Times.exactly; import static org.mockserver.model.BinaryBody.binary; import static org.mockserver.model.Cookie.cookie; import static org.mockserver.model.Header.header; import static org.mockserver.model.HttpForward.forward; import static org.mockserver.model.HttpRequest.request; import static org.mockserver.model.HttpResponse.notFoundResponse; import static org.mockserver.model.HttpResponse.response; import static org.mockserver.model.HttpStatusCode.NOT_FOUND_404; import static org.mockserver.model.HttpStatusCode.OK_200; import static org.mockserver.model.JsonBody.json; import static org.mockserver.model.JsonSchemaBody.jsonSchema; import static org.mockserver.model.NottableString.not; import static org.mockserver.model.NottableString.string; import static org.mockserver.model.Parameter.param; import static org.mockserver.model.ParameterBody.params; import static org.mockserver.model.RegexBody.regex; import static org.mockserver.model.StringBody.exact; import static org.mockserver.model.StringBody.subString; import static org.mockserver.model.XPathBody.xpath; import static org.mockserver.model.XmlBody.xml; import static org.mockserver.model.XmlSchemaBody.xmlSchema; import static org.mockserver.model.XmlSchemaBody.xmlSchemaFromResource; /** * @author jamesdbloom */ public abstract class AbstractExtendedMockingIntegrationTest extends AbstractBasicMockingIntegrationTest { @Test public void shouldReturnResponseForRequestInSsl() { // when mockServerClient.when(request().withSecure(true)).respond(response().withBody("some_body")); // then // - in http assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()) .withReasonPhrase(HttpStatusCode.NOT_FOUND_404.reasonPhrase()), makeRequest( request() .withPath(calculatePath("")), headersToIgnore) ); // - in https assertEquals( response() .withStatusCode(OK_200.code()) .withReasonPhrase(OK_200.reasonPhrase()) .withBody("some_body"), makeRequest( request() .withSecure(true) .withPath(calculatePath("")), headersToIgnore) ); } @Test public void shouldReturnResponseForRequestNotInSsl() { // when mockServerClient.when(request().withSecure(false)).respond(response().withBody("some_body")); // then // - in http assertEquals( response() .withStatusCode(OK_200.code()) .withReasonPhrase(OK_200.reasonPhrase()) .withBody("some_body"), makeRequest( request() .withPath(calculatePath("")), headersToIgnore) ); // - in https assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()) .withReasonPhrase(HttpStatusCode.NOT_FOUND_404.reasonPhrase()), makeRequest( request() .withSecure(true) .withPath(calculatePath("")), headersToIgnore) ); } @Test public void shouldReturnResponseByMatchingPath() { // when mockServerClient .when( request() .withPath(calculatePath("some_path1")) ) .respond( response() .withBody("some_body1") ); mockServerClient .when( request() .withPath(calculatePath("some_path2")) ) .respond( response() .withBody("some_body2") ); // then // - in http assertEquals( response() .withStatusCode(OK_200.code()) .withReasonPhrase(OK_200.reasonPhrase()) .withBody("some_body2"), makeRequest( request() .withPath(calculatePath("some_path2")), headersToIgnore) ); assertEquals( response() .withStatusCode(OK_200.code()) .withReasonPhrase(OK_200.reasonPhrase()) .withBody("some_body1"), makeRequest( request() .withPath(calculatePath("some_path1")), headersToIgnore) ); // - in https assertEquals( response() .withStatusCode(OK_200.code()) .withReasonPhrase(OK_200.reasonPhrase()) .withBody("some_body2"), makeRequest( request() .withSecure(true) .withPath(calculatePath("some_path2")), headersToIgnore) ); assertEquals( response() .withStatusCode(OK_200.code()) .withReasonPhrase(OK_200.reasonPhrase()) .withBody("some_body1"), makeRequest( request() .withSecure(true) .withPath(calculatePath("some_path1")), headersToIgnore) ); } @Test public void shouldReturnResponseByMatchingPathExactTimes() { // when mockServerClient .when( request() .withPath(calculatePath("some_path")), exactly(2) ) .respond( response() .withBody("some_body") ); // then // - in http assertEquals( response() .withStatusCode(OK_200.code()) .withReasonPhrase(OK_200.reasonPhrase()) .withBody("some_body"), makeRequest( request() .withPath(calculatePath("some_path")), headersToIgnore) ); // - in https assertEquals( response() .withStatusCode(OK_200.code()) .withReasonPhrase(OK_200.reasonPhrase()) .withBody("some_body"), makeRequest( request() .withSecure(true) .withPath(calculatePath("some_path")), headersToIgnore) ); // - in http assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()) .withReasonPhrase(HttpStatusCode.NOT_FOUND_404.reasonPhrase()), makeRequest( request() .withPath(calculatePath("some_path")), headersToIgnore) ); // - in https assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()) .withReasonPhrase(HttpStatusCode.NOT_FOUND_404.reasonPhrase()), makeRequest( request() .withSecure(true) .withPath(calculatePath("some_path")), headersToIgnore) ); } @Test public void shouldReturnResponseWhenTimeToLiveHasNotExpired() { // when mockServerClient .when( request().withPath(calculatePath("some_path")), exactly(2), TimeToLive.exactly(TimeUnit.HOURS, 1L) ) .respond( response().withBody("some_body") ); // then // - in http assertEquals( response() .withStatusCode(OK_200.code()) .withReasonPhrase(OK_200.reasonPhrase()) .withBody("some_body"), makeRequest( request() .withPath(calculatePath("some_path")), headersToIgnore) ); // - in https assertEquals( response() .withStatusCode(OK_200.code()) .withReasonPhrase(OK_200.reasonPhrase()) .withBody("some_body"), makeRequest( request() .withSecure(true) .withPath(calculatePath("some_path")), headersToIgnore) ); // - in http assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()) .withReasonPhrase(HttpStatusCode.NOT_FOUND_404.reasonPhrase()), makeRequest( request() .withPath(calculatePath("some_path")), headersToIgnore) ); // - in https assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()) .withReasonPhrase(HttpStatusCode.NOT_FOUND_404.reasonPhrase()), makeRequest( request() .withSecure(true) .withPath(calculatePath("some_path")), headersToIgnore) ); } @Test public void shouldReturnMatchRequestWithBodyInUTF16() { // when String body = "我说中国话"; mockServerClient.when(request().withBody(body, Charsets.UTF_16)).respond(response().withBody(body, Charsets.UTF_8)); // then // - in http assertEquals( response() .withHeader(CONTENT_TYPE.toString(), MediaType.create("text", "plain").withCharset(Charsets.UTF_8).toString()) .withStatusCode(OK_200.code()) .withReasonPhrase(OK_200.reasonPhrase()) .withBody(body), makeRequest( request() .withPath(calculatePath("")) .withBody(body, Charsets.UTF_16), headersToIgnore) ); // - in https assertEquals( response() .withHeader(CONTENT_TYPE.toString(), MediaType.create("text", "plain").withCharset(Charsets.UTF_8).toString()) .withStatusCode(OK_200.code()) .withReasonPhrase(OK_200.reasonPhrase()) .withBody(body), makeRequest( request() .withSecure(true) .withPath(calculatePath("")) .withBody(body, Charsets.UTF_16), headersToIgnore) ); } @Test public void shouldReturnMatchRequestWithBodyInUTF8WithContentTypeHeader() { // when String body = "我说中国话"; mockServerClient .when( request() .withHeader(CONTENT_TYPE.toString(), MediaType.create("text", "plain").withCharset(Charsets.UTF_8).toString()) .withBody(body) ) .respond( response() .withBody(body, Charsets.UTF_8) ); // then // - in http assertEquals( response() .withHeader(CONTENT_TYPE.toString(), MediaType.create("text", "plain").withCharset(Charsets.UTF_8).toString()) .withStatusCode(OK_200.code()) .withReasonPhrase(OK_200.reasonPhrase()) .withBody(body), makeRequest( request() .withHeader(CONTENT_TYPE.toString(), MediaType.create("text", "plain").withCharset(Charsets.UTF_8).toString()) .withPath(calculatePath("")) .withBody(body), headersToIgnore) ); // - in https assertEquals( response() .withHeader(CONTENT_TYPE.toString(), MediaType.create("text", "plain").withCharset(Charsets.UTF_8).toString()) .withStatusCode(OK_200.code()) .withReasonPhrase(OK_200.reasonPhrase()) .withBody(body), makeRequest( request() .withHeader(CONTENT_TYPE.toString(), MediaType.create("text", "plain").withCharset(Charsets.UTF_8).toString()) .withSecure(true) .withPath(calculatePath("")) .withBody(body), headersToIgnore) ); } @Test public void shouldReturnResponseWithBodyInUTF16() { // when String body = "我说中国话"; mockServerClient.when(request()).respond(response().withBody(body, Charsets.UTF_16)); // then // - in http assertEquals( response() .withHeader(CONTENT_TYPE.toString(), MediaType.create("text", "plain").withCharset(Charsets.UTF_16).toString()) .withStatusCode(OK_200.code()) .withReasonPhrase(OK_200.reasonPhrase()) .withBody(body), makeRequest( request() .withPath(calculatePath("")), headersToIgnore) ); // - in https assertEquals( response() .withHeader(CONTENT_TYPE.toString(), MediaType.create("text", "plain").withCharset(Charsets.UTF_16).toString()) .withStatusCode(OK_200.code()) .withReasonPhrase(OK_200.reasonPhrase()) .withBody(body), makeRequest( request() .withSecure(true) .withPath(calculatePath("")), headersToIgnore) ); } @Test public void shouldReturnResponseWithBodyInUTF8WithContentTypeHeader() { // when String body = "我说中国话"; mockServerClient .when( request() ) .respond( response() .withHeader(CONTENT_TYPE.toString(), MediaType.create("text", "plain").withCharset(Charsets.UTF_8).toString()) .withBody(body) ); // then // - in http assertEquals( response() .withHeader(CONTENT_TYPE.toString(), MediaType.create("text", "plain").withCharset(Charsets.UTF_8).toString()) .withStatusCode(OK_200.code()) .withReasonPhrase(OK_200.reasonPhrase()) .withBody(body), makeRequest( request() .withPath(calculatePath("")), headersToIgnore) ); // - in https assertEquals( response() .withHeader(CONTENT_TYPE.toString(), MediaType.create("text", "plain").withCharset(Charsets.UTF_8).toString()) .withStatusCode(OK_200.code()) .withReasonPhrase(OK_200.reasonPhrase()) .withBody(body), makeRequest( request() .withSecure(true) .withPath(calculatePath("")), headersToIgnore) ); } @Test public void shouldReturnResponseByMatchingSubStringBody() { // when mockServerClient .when( request() .withBody( subString("random") ), exactly(2) ) .respond( response() .withBody("some_sub_string_body_response") ); // then // - in http assertEquals( response() .withStatusCode(OK_200.code()) .withReasonPhrase(OK_200.reasonPhrase()) .withBody("some_sub_string_body_response"), makeRequest( request() .withMethod("POST") .withPath(calculatePath("some_path")) .withBody("some_random_body"), headersToIgnore) ); // - in https assertEquals( response() .withStatusCode(OK_200.code()) .withReasonPhrase(OK_200.reasonPhrase()) .withBody("some_sub_string_body_response"), makeRequest( request() .withSecure(true) .withMethod("POST") .withPath(calculatePath("some_path")) .withBody("some_random_body"), headersToIgnore) ); } @Test public void shouldReturnResponseByMatchingBodyWithXPath() { // when mockServerClient.when(request().withBody(xpath("/bookstore/book[price>30]/price")), exactly(2)).respond(response().withBody("some_body")); // then // - in http assertEquals( response() .withStatusCode(OK_200.code()) .withReasonPhrase(OK_200.reasonPhrase()) .withBody("some_body"), makeRequest( request() .withPath(calculatePath("some_path")) .withMethod("POST") .withBody(new StringBody("" + "<?xml version=\"1.0\" encoding=\"ISO-8859-1\"?>" + NEW_LINE + "<bookstore>" + NEW_LINE + " <book category=\"COOKING\">" + NEW_LINE + " <title lang=\"en\">Everyday Italian</title>" + NEW_LINE + " <author>Giada De Laurentiis</author>" + NEW_LINE + " <year>2005</year>" + NEW_LINE + " <price>30.00</price>" + NEW_LINE + " </book>" + NEW_LINE + " <book category=\"CHILDREN\">" + NEW_LINE + " <title lang=\"en\">Harry Potter</title>" + NEW_LINE + " <author>J K. Rowling</author>" + NEW_LINE + " <year>2005</year>" + NEW_LINE + " <price>29.99</price>" + NEW_LINE + " </book>" + NEW_LINE + " <book category=\"WEB\">" + NEW_LINE + " <title lang=\"en\">Learning XML</title>" + NEW_LINE + " <author>Erik T. Ray</author>" + NEW_LINE + " <year>2003</year>" + NEW_LINE + " <price>31.95</price>" + NEW_LINE + " </book>" + NEW_LINE + "</bookstore>")), headersToIgnore) ); // - in https assertEquals( response() .withStatusCode(OK_200.code()) .withReasonPhrase(OK_200.reasonPhrase()) .withBody("some_body"), makeRequest( request() .withSecure(true) .withPath(calculatePath("some_path")) .withMethod("POST") .withBody(new StringBody("" + "<?xml version=\"1.0\" encoding=\"ISO-8859-1\"?>" + NEW_LINE + "<bookstore>" + NEW_LINE + " <book category=\"COOKING\">" + NEW_LINE + " <title lang=\"en\">Everyday Italian</title>" + NEW_LINE + " <author>Giada De Laurentiis</author>" + NEW_LINE + " <year>2005</year>" + NEW_LINE + " <price>30.00</price>" + NEW_LINE + " </book>" + NEW_LINE + " <book category=\"CHILDREN\">" + NEW_LINE + " <title lang=\"en\">Harry Potter</title>" + NEW_LINE + " <author>J K. Rowling</author>" + NEW_LINE + " <year>2005</year>" + NEW_LINE + " <price>29.99</price>" + NEW_LINE + " </book>" + NEW_LINE + " <book category=\"WEB\">" + NEW_LINE + " <title lang=\"en\">Learning XML</title>" + NEW_LINE + " <author>Erik T. Ray</author>" + NEW_LINE + " <year>2003</year>" + NEW_LINE + " <price>31.95</price>" + NEW_LINE + " </book>" + NEW_LINE + "</bookstore>")), headersToIgnore) ); } @Test public void shouldReturnResponseByMatchingBodyWithXml() { // when mockServerClient.when(request().withBody(xml("" + "<bookstore>" + NEW_LINE + " <book nationality=\"ITALIAN\" category=\"COOKING\"><title lang=\"en\">Everyday Italian</title><author>Giada De Laurentiis</author><year>2005</year><price>30.00</price></book>" + NEW_LINE + "</bookstore>")), exactly(2)).respond(response().withBody("some_body")); // then // - in http assertEquals( response() .withStatusCode(OK_200.code()) .withReasonPhrase(OK_200.reasonPhrase()) .withBody("some_body"), makeRequest( request() .withPath(calculatePath("some_path")) .withMethod("POST") .withBody(new StringBody("" + "<?xml version=\"1.0\" encoding=\"ISO-8859-1\"?>" + NEW_LINE + "<bookstore>" + NEW_LINE + " <book category=\"COOKING\" nationality=\"ITALIAN\">" + NEW_LINE + " <title lang=\"en\">Everyday Italian</title>" + NEW_LINE + " <author>Giada De Laurentiis</author>" + NEW_LINE + " <year>2005</year>" + NEW_LINE + " <price>30.00</price>" + NEW_LINE + " </book>" + NEW_LINE + "</bookstore>")), headersToIgnore) ); // - in https assertEquals( response() .withStatusCode(OK_200.code()) .withReasonPhrase(OK_200.reasonPhrase()) .withBody("some_body"), makeRequest( request() .withSecure(true) .withPath(calculatePath("some_path")) .withMethod("POST") .withBody(new StringBody("" + "<?xml version=\"1.0\" encoding=\"ISO-8859-1\"?>" + NEW_LINE + "<bookstore>" + NEW_LINE + " <book category=\"COOKING\" nationality=\"ITALIAN\">" + NEW_LINE + " <title lang=\"en\">Everyday Italian</title>" + NEW_LINE + " <author>Giada De Laurentiis</author>" + NEW_LINE + " <year>2005</year>" + NEW_LINE + " <price>30.00</price>" + NEW_LINE + " </book>" + NEW_LINE + "</bookstore>")), headersToIgnore) ); } @Test public void shouldReturnResponseByMatchingBodyWithJson() { // when mockServerClient .when( request() .withBody(json("{" + NEW_LINE + " \"id\": 1," + NEW_LINE + " \"name\": \"A green door\"," + NEW_LINE + " \"price\": 12.50," + NEW_LINE + " \"tags\": [\"home\", \"green\"]" + NEW_LINE + "}")), exactly(2) ) .respond( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withReasonPhrase(HttpStatusCode.ACCEPTED_202.reasonPhrase()) .withBody("some_body") ); // then // - in http assertEquals( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withReasonPhrase(HttpStatusCode.ACCEPTED_202.reasonPhrase()) .withBody("some_body"), makeRequest( request() .withPath(calculatePath("some_path")) .withMethod("POST") .withBody("{" + NEW_LINE + " \"id\": 1," + NEW_LINE + " \"extra ignored field\": \"some value\"," + NEW_LINE + " \"name\": \"A green door\"," + NEW_LINE + " \"price\": 12.50," + NEW_LINE + " \"tags\": [\"home\", \"green\"]" + NEW_LINE + "}"), headersToIgnore) ); // - in https assertEquals( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withReasonPhrase(HttpStatusCode.ACCEPTED_202.reasonPhrase()) .withBody("some_body"), makeRequest( request() .withSecure(true) .withPath(calculatePath("some_path")) .withMethod("POST") .withBody("{" + NEW_LINE + " \"id\": 1," + NEW_LINE + " \"extra ignored array\": [\"one\", \"two\"]," + NEW_LINE + " \"name\": \"A green door\"," + NEW_LINE + " \"price\": 12.50," + NEW_LINE + " \"tags\": [\"home\", \"green\"]" + NEW_LINE + "}"), headersToIgnore) ); } @Test public void shouldReturnResponseByMatchingBodyWithJsonWithCharsetUTF8() { // when mockServerClient .when( request() .withBody(json("{" + NEW_LINE + " \"ταυτότητα\": 1," + NEW_LINE + " \"όνομα\": \"μια πράσινη πόρτα\"," + NEW_LINE + " \"τιμή\": 12.50," + NEW_LINE + " \"ετικέτες\": [\"σπίτι\", \"πράσινος\"]" + NEW_LINE + "}", Charsets.UTF_16, MatchType.ONLY_MATCHING_FIELDS)), exactly(2) ) .respond( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withReasonPhrase(HttpStatusCode.ACCEPTED_202.reasonPhrase()) .withBody("some_body") ); // then // - in http assertEquals( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withReasonPhrase(HttpStatusCode.ACCEPTED_202.reasonPhrase()) .withBody("some_body"), makeRequest( request() .withPath(calculatePath("some_path")) .withMethod("POST") .withBody(json("{" + NEW_LINE + " \"ταυτότητα\": 1," + NEW_LINE + " \"επιπλέον αγνοούνται τομέα\": \"κάποια αξία\"," + NEW_LINE + " \"όνομα\": \"μια πράσινη πόρτα\"," + NEW_LINE + " \"τιμή\": 12.50," + NEW_LINE + " \"ετικέτες\": [\"σπίτι\", \"πράσινος\"]" + NEW_LINE + "}", Charsets.UTF_16, MatchType.ONLY_MATCHING_FIELDS)), headersToIgnore) ); // - in https assertEquals( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withReasonPhrase(HttpStatusCode.ACCEPTED_202.reasonPhrase()) .withBody("some_body"), makeRequest( request() .withSecure(true) .withPath(calculatePath("some_path")) .withMethod("POST") .withBody(json("{" + NEW_LINE + " \"ταυτότητα\": 1," + NEW_LINE + " \"επιπλέον αγνοούνται σειρά\": [\"ένας\", \"δυο\"]," + NEW_LINE + " \"όνομα\": \"μια πράσινη πόρτα\"," + NEW_LINE + " \"τιμή\": 12.50," + NEW_LINE + " \"ετικέτες\": [\"σπίτι\", \"πράσινος\"]" + NEW_LINE + "}", Charsets.UTF_16, MatchType.ONLY_MATCHING_FIELDS)), headersToIgnore) ); } @Test public void shouldReturnResponseByMatchingBodyWithJsonWithContentTypeHeader() { // when mockServerClient .when( request() .withBody(json("{" + NEW_LINE + " \"ταυτότητα\": 1," + NEW_LINE + " \"όνομα\": \"μια πράσινη πόρτα\"," + NEW_LINE + " \"τιμή\": 12.50," + NEW_LINE + " \"ετικέτες\": [\"σπίτι\", \"πράσινος\"]" + NEW_LINE + "}", Charsets.UTF_16, MatchType.ONLY_MATCHING_FIELDS)), exactly(2) ) .respond( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withReasonPhrase(HttpStatusCode.ACCEPTED_202.reasonPhrase()) .withBody("some_body") ); // then // - in http assertEquals( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withReasonPhrase(HttpStatusCode.ACCEPTED_202.reasonPhrase()) .withBody("some_body"), makeRequest( request() .withHeader(CONTENT_TYPE.toString(), MediaType.create("text", "plain").withCharset(Charsets.UTF_16).toString()) .withPath(calculatePath("some_path")) .withMethod("POST") .withBody(json("{" + NEW_LINE + " \"ταυτότητα\": 1," + NEW_LINE + " \"επιπλέον αγνοούνται τομέα\": \"κάποια αξία\"," + NEW_LINE + " \"όνομα\": \"μια πράσινη πόρτα\"," + NEW_LINE + " \"τιμή\": 12.50," + NEW_LINE + " \"ετικέτες\": [\"σπίτι\", \"πράσινος\"]" + NEW_LINE + "}")), headersToIgnore) ); // - in https assertEquals( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withReasonPhrase(HttpStatusCode.ACCEPTED_202.reasonPhrase()) .withBody("some_body"), makeRequest( request() .withSecure(true) .withHeader(CONTENT_TYPE.toString(), MediaType.create("text", "plain").withCharset(Charsets.UTF_16).toString()) .withPath(calculatePath("some_path")) .withMethod("POST") .withBody(json("{" + NEW_LINE + " \"ταυτότητα\": 1," + NEW_LINE + " \"επιπλέον αγνοούνται σειρά\": [\"ένας\", \"δυο\"]," + NEW_LINE + " \"όνομα\": \"μια πράσινη πόρτα\"," + NEW_LINE + " \"τιμή\": 12.50," + NEW_LINE + " \"ετικέτες\": [\"σπίτι\", \"πράσινος\"]" + NEW_LINE + "}")), headersToIgnore) ); } @Test public void shouldReturnResponseByMatchingBodyWithJsonWithMatchType() { // when mockServerClient .when( request() .withBody(json("{" + NEW_LINE + " \"id\": 1," + NEW_LINE + " \"name\": \"A green door\"," + NEW_LINE + " \"price\": 12.50," + NEW_LINE + " \"tags\": [\"home\", \"green\"]" + NEW_LINE + "}", MatchType.ONLY_MATCHING_FIELDS)), exactly(2) ) .respond( response() .withBody("some_body") ); // then // - in http assertEquals( response("some_body"), makeRequest( request() .withPath(calculatePath("some_path")) .withMethod("POST") .withBody("{" + NEW_LINE + " \"id\": 1," + NEW_LINE + " \"extra field\": \"some value\"," + NEW_LINE + " \"name\": \"A green door\"," + NEW_LINE + " \"price\": 12.50," + NEW_LINE + " \"tags\": [\"home\", \"green\"]" + NEW_LINE + "}"), headersToIgnore) ); // - in https assertEquals( response("some_body"), makeRequest( request() .withSecure(true) .withPath(calculatePath("some_path")) .withMethod("POST") .withBody("{" + NEW_LINE + " \"id\": 1," + NEW_LINE + " \"extra field\": \"some value\"," + NEW_LINE + " \"name\": \"A green door\"," + NEW_LINE + " \"price\": 12.50," + NEW_LINE + " \"tags\": [\"home\", \"green\"]" + NEW_LINE + "}"), headersToIgnore) ); } @Test public void shouldReturnResponseByMatchingBodyWithJsonSchema() { // when mockServerClient.when(request().withBody(jsonSchema("{" + NEW_LINE + " \"$schema\": \"http://json-schema.org/draft-04/schema#\"," + NEW_LINE + " \"title\": \"Product\"," + NEW_LINE + " \"description\": \"A product from Acme's catalog\"," + NEW_LINE + " \"type\": \"object\"," + NEW_LINE + " \"properties\": {" + NEW_LINE + " \"id\": {" + NEW_LINE + " \"description\": \"The unique identifier for a product\"," + NEW_LINE + " \"type\": \"integer\"" + NEW_LINE + " }," + NEW_LINE + " \"name\": {" + NEW_LINE + " \"description\": \"Name of the product\"," + NEW_LINE + " \"type\": \"string\"" + NEW_LINE + " }," + NEW_LINE + " \"price\": {" + NEW_LINE + " \"type\": \"number\"," + NEW_LINE + " \"minimum\": 0," + NEW_LINE + " \"exclusiveMinimum\": true" + NEW_LINE + " }," + NEW_LINE + " \"tags\": {" + NEW_LINE + " \"type\": \"array\"," + NEW_LINE + " \"items\": {" + NEW_LINE + " \"type\": \"string\"" + NEW_LINE + " }," + NEW_LINE + " \"minItems\": 1," + NEW_LINE + " \"uniqueItems\": true" + NEW_LINE + " }" + NEW_LINE + " }," + NEW_LINE + " \"required\": [\"id\", \"name\", \"price\"]" + NEW_LINE + "}")), exactly(2)).respond(response().withBody("some_body")); // then // - in http assertEquals( response() .withStatusCode(OK_200.code()) .withReasonPhrase(OK_200.reasonPhrase()) .withBody("some_body"), makeRequest( request() .withPath(calculatePath("some_path")) .withMethod("POST") .withBody("{" + NEW_LINE + " \"id\": 1," + NEW_LINE + " \"name\": \"A green door\"," + NEW_LINE + " \"price\": 12.50," + NEW_LINE + " \"tags\": [\"home\", \"green\"]" + NEW_LINE + "}"), headersToIgnore) ); // - in https assertEquals( response() .withStatusCode(OK_200.code()) .withReasonPhrase(OK_200.reasonPhrase()) .withBody("some_body"), makeRequest( request() .withSecure(true) .withPath(calculatePath("some_path")) .withMethod("POST") .withBody("{" + NEW_LINE + " \"id\": 1," + NEW_LINE + " \"name\": \"A green door\"," + NEW_LINE + " \"price\": 12.50," + NEW_LINE + " \"tags\": [\"home\", \"green\"]" + NEW_LINE + "}"), headersToIgnore) ); } @Test public void shouldReturnResponseByMatchingBodyWithXmlSchema() { // when mockServerClient.when(request() .withBody( xmlSchema("<?xml version=\"1.0\" encoding=\"UTF-8\"?>" + NEW_LINE + "<xs:schema xmlns:xs=\"http://www.w3.org/2001/XMLSchema\" elementFormDefault=\"qualified\" attributeFormDefault=\"unqualified\">" + NEW_LINE + " <!-- XML Schema Generated from XML Document on Wed Jun 28 2017 21:52:45 GMT+0100 (BST) -->" + NEW_LINE + " <!-- with XmlGrid.net Free Online Service http://xmlgrid.net -->" + NEW_LINE + " <xs:element name=\"notes\">" + NEW_LINE + " <xs:complexType>" + NEW_LINE + " <xs:sequence>" + NEW_LINE + " <xs:element name=\"note\" maxOccurs=\"unbounded\">" + NEW_LINE + " <xs:complexType>" + NEW_LINE + " <xs:sequence>" + NEW_LINE + " <xs:element name=\"to\" minOccurs=\"1\" maxOccurs=\"1\" type=\"xs:string\"></xs:element>" + NEW_LINE + " <xs:element name=\"from\" minOccurs=\"1\" maxOccurs=\"1\" type=\"xs:string\"></xs:element>" + NEW_LINE + " <xs:element name=\"heading\" minOccurs=\"1\" maxOccurs=\"1\" type=\"xs:string\"></xs:element>" + NEW_LINE + " <xs:element name=\"body\" minOccurs=\"1\" maxOccurs=\"1\" type=\"xs:string\"></xs:element>" + NEW_LINE + " </xs:sequence>" + NEW_LINE + " </xs:complexType>" + NEW_LINE + " </xs:element>" + NEW_LINE + " </xs:sequence>" + NEW_LINE + " </xs:complexType>" + NEW_LINE + " </xs:element>" + NEW_LINE + "</xs:schema>")), exactly(2) ) .respond( response() .withBody("some_body") ); // then // - in http assertEquals( response() .withStatusCode(NOT_FOUND_404.code()) .withReasonPhrase(NOT_FOUND_404.reasonPhrase()), makeRequest( request() .withMethod("POST") .withBody("<?xml version=\"1.0\" encoding=\"utf-8\"?>" + NEW_LINE + "<notes>" + NEW_LINE + " <note>" + NEW_LINE + " <to>Bob</to>" + NEW_LINE + " <heading>Reminder</heading>" + NEW_LINE + " <body>Buy Bread</body>" + NEW_LINE + " </note>" + NEW_LINE + " <note>" + NEW_LINE + " <to>Jack</to>" + NEW_LINE + " <from>Jill</from>" + NEW_LINE + " <heading>Reminder</heading>" + NEW_LINE + " <body>Wash Shirts</body>" + NEW_LINE + " </note>" + NEW_LINE + "</notes>"), headersToIgnore) ); assertEquals( response() .withStatusCode(OK_200.code()) .withReasonPhrase(OK_200.reasonPhrase()) .withBody("some_body"), makeRequest( request() .withPath(calculatePath("some_path")) .withMethod("POST") .withBody("<?xml version=\"1.0\" encoding=\"utf-8\"?>" + NEW_LINE + "<notes>" + NEW_LINE + " <note>" + NEW_LINE + " <to>Bob</to>" + NEW_LINE + " <from>Bill</from>" + NEW_LINE + " <heading>Reminder</heading>" + NEW_LINE + " <body>Buy Bread</body>" + NEW_LINE + " </note>" + NEW_LINE + " <note>" + NEW_LINE + " <to>Jack</to>" + NEW_LINE + " <from>Jill</from>" + NEW_LINE + " <heading>Reminder</heading>" + NEW_LINE + " <body>Wash Shirts</body>" + NEW_LINE + " </note>" + NEW_LINE + "</notes>"), headersToIgnore) ); // - in https assertEquals( response() .withStatusCode(OK_200.code()) .withReasonPhrase(OK_200.reasonPhrase()) .withBody("some_body"), makeRequest( request() .withSecure(true) .withPath(calculatePath("some_path")) .withMethod("POST") .withBody("<?xml version=\"1.0\" encoding=\"utf-8\"?>" + NEW_LINE + "<notes>" + NEW_LINE + " <note>" + NEW_LINE + " <to>Bob</to>" + NEW_LINE + " <from>Bill</from>" + NEW_LINE + " <heading>Reminder</heading>" + NEW_LINE + " <body>Buy Bread</body>" + NEW_LINE + " </note>" + NEW_LINE + " <note>" + NEW_LINE + " <to>Jack</to>" + NEW_LINE + " <from>Jill</from>" + NEW_LINE + " <heading>Reminder</heading>" + NEW_LINE + " <body>Wash Shirts</body>" + NEW_LINE + " </note>" + NEW_LINE + "</notes>"), headersToIgnore) ); } @Test public void shouldReturnResponseByMatchingBodyWithXmlSchemaByClasspath() { // when mockServerClient.when(request() .withBody( xmlSchemaFromResource("org/mockserver/model/testXmlSchema.xsd")), exactly(2) ) .respond( response() .withBody("some_body") ); // then // - in http assertEquals( response() .withStatusCode(NOT_FOUND_404.code()) .withReasonPhrase(NOT_FOUND_404.reasonPhrase()), makeRequest( request() .withMethod("POST") .withBody("<?xml version=\"1.0\" encoding=\"utf-8\"?>" + NEW_LINE + "<notes>" + NEW_LINE + " <note>" + NEW_LINE + " <to>Bob</to>" + NEW_LINE + " <heading>Reminder</heading>" + NEW_LINE + " <body>Buy Bread</body>" + NEW_LINE + " </note>" + NEW_LINE + " <note>" + NEW_LINE + " <to>Jack</to>" + NEW_LINE + " <from>Jill</from>" + NEW_LINE + " <heading>Reminder</heading>" + NEW_LINE + " <body>Wash Shirts</body>" + NEW_LINE + " </note>" + NEW_LINE + "</notes>"), headersToIgnore) ); assertEquals( response() .withStatusCode(OK_200.code()) .withReasonPhrase(OK_200.reasonPhrase()) .withBody("some_body"), makeRequest( request() .withPath(calculatePath("some_path")) .withMethod("POST") .withBody("<?xml version=\"1.0\" encoding=\"utf-8\"?>" + NEW_LINE + "<notes>" + NEW_LINE + " <note>" + NEW_LINE + " <to>Bob</to>" + NEW_LINE + " <from>Bill</from>" + NEW_LINE + " <heading>Reminder</heading>" + NEW_LINE + " <body>Buy Bread</body>" + NEW_LINE + " </note>" + NEW_LINE + " <note>" + NEW_LINE + " <to>Jack</to>" + NEW_LINE + " <from>Jill</from>" + NEW_LINE + " <heading>Reminder</heading>" + NEW_LINE + " <body>Wash Shirts</body>" + NEW_LINE + " </note>" + NEW_LINE + "</notes>"), headersToIgnore) ); // - in https assertEquals( response() .withStatusCode(OK_200.code()) .withReasonPhrase(OK_200.reasonPhrase()) .withBody("some_body"), makeRequest( request() .withSecure(true) .withPath(calculatePath("some_path")) .withMethod("POST") .withBody("<?xml version=\"1.0\" encoding=\"utf-8\"?>" + NEW_LINE + "<notes>" + NEW_LINE + " <note>" + NEW_LINE + " <to>Bob</to>" + NEW_LINE + " <from>Bill</from>" + NEW_LINE + " <heading>Reminder</heading>" + NEW_LINE + " <body>Buy Bread</body>" + NEW_LINE + " </note>" + NEW_LINE + " <note>" + NEW_LINE + " <to>Jack</to>" + NEW_LINE + " <from>Jill</from>" + NEW_LINE + " <heading>Reminder</heading>" + NEW_LINE + " <body>Wash Shirts</body>" + NEW_LINE + " </note>" + NEW_LINE + "</notes>"), headersToIgnore) ); } @Test public void shouldReturnPDFResponseByMatchingPath() throws IOException { // when byte[] pdfBytes = IOUtils.toByteArray(getClass().getClassLoader().getResourceAsStream("test.pdf")); mockServerClient .when( request() .withPath(calculatePath("ws/rest/user/[0-9]+/document/[0-9]+\\.pdf")) ) .respond( response() .withStatusCode(OK_200.code()) .withReasonPhrase(OK_200.reasonPhrase()) .withHeaders( header(CONTENT_TYPE.toString(), MediaType.PDF.toString()), header(CONTENT_DISPOSITION.toString(), "form-data; name=\"test.pdf\"; filename=\"test.pdf\""), header(CACHE_CONTROL.toString(), "must-revalidate, post-check=0, pre-check=0") ) .withBody(binary(pdfBytes)) ); // then // - in http assertEquals( response() .withStatusCode(OK_200.code()) .withReasonPhrase(OK_200.reasonPhrase()) .withHeaders( header(CONTENT_DISPOSITION.toString(), "form-data; name=\"test.pdf\"; filename=\"test.pdf\""), header(CACHE_CONTROL.toString(), "must-revalidate, post-check=0, pre-check=0"), header(CONTENT_TYPE.toString(), MediaType.PDF.toString()) ) .withBody(binary(pdfBytes)), makeRequest( request() .withPath(calculatePath("ws/rest/user/1/document/2.pdf")) .withMethod("GET"), headersToIgnore) ); // - in https assertEquals( response() .withStatusCode(OK_200.code()) .withReasonPhrase(OK_200.reasonPhrase()) .withHeaders( header(CONTENT_DISPOSITION.toString(), "form-data; name=\"test.pdf\"; filename=\"test.pdf\""), header(CACHE_CONTROL.toString(), "must-revalidate, post-check=0, pre-check=0"), header(CONTENT_TYPE.toString(), MediaType.PDF.toString()) ) .withBody(binary(pdfBytes)), makeRequest( request() .withSecure(true) .withPath(calculatePath("ws/rest/user/1/document/2.pdf")) .withMethod("GET"), headersToIgnore) ); } @Test public void shouldReturnPNGResponseByMatchingPath() throws IOException { // when byte[] pngBytes = IOUtils.toByteArray(getClass().getClassLoader().getResourceAsStream("test.png")); mockServerClient .when( request() .withPath(calculatePath("ws/rest/user/[0-9]+/icon/[0-9]+\\.png")) ) .respond( response() .withStatusCode(OK_200.code()) .withReasonPhrase(OK_200.reasonPhrase()) .withHeaders( header(CONTENT_TYPE.toString(), MediaType.PNG.toString()), header(CONTENT_DISPOSITION.toString(), "form-data; name=\"test.png\"; filename=\"test.png\"") ) .withBody(binary(pngBytes)) ); // then // - in http assertEquals( response() .withStatusCode(OK_200.code()) .withReasonPhrase(OK_200.reasonPhrase()) .withHeaders( header(CONTENT_DISPOSITION.toString(), "form-data; name=\"test.png\"; filename=\"test.png\""), header(CONTENT_TYPE.toString(), MediaType.PNG.toString()) ) .withBody(binary(pngBytes)), makeRequest( request() .withPath(calculatePath("ws/rest/user/1/icon/1.png")) .withMethod("GET"), headersToIgnore) ); // - in https assertEquals( response() .withStatusCode(OK_200.code()) .withReasonPhrase(OK_200.reasonPhrase()) .withHeaders( header(CONTENT_DISPOSITION.toString(), "form-data; name=\"test.png\"; filename=\"test.png\""), header(CONTENT_TYPE.toString(), MediaType.PNG.toString()) ) .withBody(binary(pngBytes)), makeRequest( request() .withSecure(true) .withPath(calculatePath("ws/rest/user/1/icon/1.png")) .withMethod("GET"), headersToIgnore) ); } @Test public void shouldReturnPDFResponseByMatchingBinaryPDFBody() throws IOException { // when byte[] pdfBytes = IOUtils.toByteArray(getClass().getClassLoader().getResourceAsStream("test.pdf")); mockServerClient .when( request().withBody(binary(pdfBytes)) ) .respond( response() .withStatusCode(OK_200.code()) .withReasonPhrase(OK_200.reasonPhrase()) .withHeaders( header(CONTENT_TYPE.toString(), MediaType.PDF.toString()), header(CONTENT_DISPOSITION.toString(), "form-data; name=\"test.pdf\"; filename=\"test.pdf\""), header(CACHE_CONTROL.toString(), "must-revalidate, post-check=0, pre-check=0") ) .withBody(binary(pdfBytes)) ); // then // - in http assertEquals( response() .withStatusCode(OK_200.code()) .withReasonPhrase(OK_200.reasonPhrase()) .withHeaders( header(CONTENT_DISPOSITION.toString(), "form-data; name=\"test.pdf\"; filename=\"test.pdf\""), header(CACHE_CONTROL.toString(), "must-revalidate, post-check=0, pre-check=0"), header(CONTENT_TYPE.toString(), MediaType.PDF.toString()) ) .withBody(binary(pdfBytes)), makeRequest( request() .withPath(calculatePath("ws/rest/user/1/document/2.pdf")) .withBody(binary(pdfBytes)) .withMethod("POST"), headersToIgnore) ); // - in https assertEquals( response() .withStatusCode(OK_200.code()) .withReasonPhrase(OK_200.reasonPhrase()) .withHeaders( header(CONTENT_DISPOSITION.toString(), "form-data; name=\"test.pdf\"; filename=\"test.pdf\""), header(CACHE_CONTROL.toString(), "must-revalidate, post-check=0, pre-check=0"), header(CONTENT_TYPE.toString(), MediaType.PDF.toString()) ) .withBody(binary(pdfBytes)), makeRequest( request() .withSecure(true) .withPath(calculatePath("ws/rest/user/1/document/2.pdf")) .withBody(binary(pdfBytes)) .withMethod("POST"), headersToIgnore) ); } @Test public void shouldReturnPNGResponseByMatchingBinaryPNGBody() throws IOException { // when byte[] pngBytes = IOUtils.toByteArray(getClass().getClassLoader().getResourceAsStream("test.png")); mockServerClient .when( request().withBody(binary(pngBytes)) ) .respond( response() .withStatusCode(OK_200.code()) .withReasonPhrase(OK_200.reasonPhrase()) .withHeaders( header(CONTENT_TYPE.toString(), MediaType.PNG.toString()), header(CONTENT_DISPOSITION.toString(), "form-data; name=\"test.png\"; filename=\"test.png\"") ) .withBody(binary(pngBytes)) ); // then // - in http assertEquals( response() .withStatusCode(OK_200.code()) .withReasonPhrase(OK_200.reasonPhrase()) .withHeaders( header(CONTENT_DISPOSITION.toString(), "form-data; name=\"test.png\"; filename=\"test.png\""), header(CONTENT_TYPE.toString(), MediaType.PNG.toString()) ) .withBody(binary(pngBytes)), makeRequest( request() .withPath(calculatePath("ws/rest/user/1/icon/1.png")) .withBody(binary(pngBytes)) .withMethod("POST"), headersToIgnore) ); // - in https assertEquals( response() .withStatusCode(OK_200.code()) .withReasonPhrase(OK_200.reasonPhrase()) .withHeaders( header(CONTENT_DISPOSITION.toString(), "form-data; name=\"test.png\"; filename=\"test.png\""), header(CONTENT_TYPE.toString(), MediaType.PNG.toString()) ) .withBody(binary(pngBytes)), makeRequest( request() .withSecure(true) .withPath(calculatePath("ws/rest/user/1/icon/1.png")) .withBody(binary(pngBytes)) .withMethod("POST"), headersToIgnore) ); } @Test public void shouldReturnResponseByNotMatchingPathWithNotOperator() { // when mockServerClient .when( request() .withPath(not(calculatePath("some_path"))) ) .respond( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withReasonPhrase(HttpStatusCode.ACCEPTED_202.reasonPhrase()) .withBody("some_body_response") ); // then // - in http assertEquals( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withReasonPhrase(HttpStatusCode.ACCEPTED_202.reasonPhrase()) .withBody("some_body_response"), makeRequest( request() .withPath(calculatePath("some_other_path")), headersToIgnore) ); // - in https assertEquals( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withReasonPhrase(HttpStatusCode.ACCEPTED_202.reasonPhrase()) .withBody("some_body_response"), makeRequest( request() .withPath(calculatePath("some_other_path")), headersToIgnore) ); } @Test public void shouldReturnResponseByNotMatchingMethodWithNotOperator() { // when mockServerClient .when( request() .withMethod(not("GET")) ) .respond( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withReasonPhrase(HttpStatusCode.ACCEPTED_202.reasonPhrase()) .withBody("some_body_response") ); // then // - in http assertEquals( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withReasonPhrase(HttpStatusCode.ACCEPTED_202.reasonPhrase()) .withBody("some_body_response"), makeRequest( request() .withMethod("POST"), headersToIgnore) ); // - in https assertEquals( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withReasonPhrase(HttpStatusCode.ACCEPTED_202.reasonPhrase()) .withBody("some_body_response"), makeRequest( request() .withMethod("POST"), headersToIgnore) ); } @Test public void shouldReturnResponseByMatchingPathAndMethodAndBody() { // when mockServerClient .when( request() .withMethod("POST") .withPath(calculatePath("some_pathRequest")) .withBody("some_bodyRequest") ) .respond( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withReasonPhrase(HttpStatusCode.ACCEPTED_202.reasonPhrase()) .withBody("some_body_response") .withHeaders(header("headerNameResponse", "headerValueResponse")) ); // then // - in http assertEquals( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withReasonPhrase(HttpStatusCode.ACCEPTED_202.reasonPhrase()) .withBody("some_body_response") .withHeaders( header("headerNameResponse", "headerValueResponse") ), makeRequest( request() .withMethod("POST") .withPath(calculatePath("some_pathRequest")) .withQueryStringParameters( param("queryStringParameterOneName", "queryStringParameterOneValue"), param("queryStringParameterTwoName", "queryStringParameterTwoValue") ) .withBody("some_bodyRequest") .withHeaders(header("headerNameRequest", "headerValueRequest")) .withCookies(cookie("cookieNameRequest", "cookieValueRequest")), headersToIgnore) ); // - in https assertEquals( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withReasonPhrase(HttpStatusCode.ACCEPTED_202.reasonPhrase()) .withBody("some_body_response") .withHeaders( header("headerNameResponse", "headerValueResponse") ), makeRequest( request() .withMethod("POST") .withSecure(true) .withPath(calculatePath("some_pathRequest")) .withQueryStringParameters( param("queryStringParameterOneName", "queryStringParameterOneValue"), param("queryStringParameterTwoName", "queryStringParameterTwoValue") ) .withBody("some_bodyRequest") .withHeaders(header("headerNameRequest", "headerValueRequest")) .withCookies(cookie("cookieNameRequest", "cookieValueRequest")), headersToIgnore) ); } @Test public void shouldReturnResponseByMatchingPathAndMethodAndQueryStringParameters() { // when mockServerClient .when( request() .withMethod("GET") .withPath(calculatePath("some_pathRequest")) .withQueryStringParameters( param("queryStringParameterOneName", "queryStringParameterOneValue"), param("queryStringParameterTwoName", "queryStringParameterTwoValue") ) ) .respond( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withReasonPhrase(HttpStatusCode.ACCEPTED_202.reasonPhrase()) .withBody("some_body_response") .withCookies(cookie("cookieNameResponse", "cookieValueResponse")) ); // then // - in http assertEquals( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withReasonPhrase(HttpStatusCode.ACCEPTED_202.reasonPhrase()) .withBody("some_body_response") .withCookies(cookie("cookieNameResponse", "cookieValueResponse")) .withHeaders( header(SET_COOKIE.toString(), "cookieNameResponse=cookieValueResponse") ), makeRequest( request() .withMethod("GET") .withPath(calculatePath("some_pathRequest")) .withQueryStringParameters( param("queryStringParameterOneName", "queryStringParameterOneValue"), param("queryStringParameterTwoName", "queryStringParameterTwoValue") ) .withHeaders(header("headerNameRequest", "headerValueRequest")) .withCookies(cookie("cookieNameRequest", "cookieValueRequest")), headersToIgnore) ); // - in https assertEquals( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withReasonPhrase(HttpStatusCode.ACCEPTED_202.reasonPhrase()) .withBody("some_body_response") .withCookies(cookie("cookieNameResponse", "cookieValueResponse")) .withHeaders( header(SET_COOKIE.toString(), "cookieNameResponse=cookieValueResponse") ), makeRequest( request() .withMethod("GET") .withSecure(true) .withPath(calculatePath("some_pathRequest")) .withQueryStringParameters( param("queryStringParameterOneName", "queryStringParameterOneValue"), param("queryStringParameterTwoName", "queryStringParameterTwoValue") ) .withHeaders(header("headerNameRequest", "headerValueRequest")) .withCookies(cookie("cookieNameRequest", "cookieValueRequest")), headersToIgnore) ); } @Test public void shouldReturnResponseByMatchingPathAndMethodAndHeaders() { // when mockServerClient .when( request() .withMethod("GET") .withPath(calculatePath("some_pathRequest")) .withHeaders( header("requestHeaderNameOne", "requestHeaderValueOne_One", "requestHeaderValueOne_Two"), header("requestHeaderNameTwo", "requestHeaderValueTwo") ) ) .respond( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withReasonPhrase(HttpStatusCode.ACCEPTED_202.reasonPhrase()) .withBody("some_body_response") .withCookies(cookie("cookieNameResponse", "cookieValueResponse")) ); // then // - in http assertEquals( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withReasonPhrase(HttpStatusCode.ACCEPTED_202.reasonPhrase()) .withBody("some_body_response") .withCookies(cookie("cookieNameResponse", "cookieValueResponse")) .withHeaders( header(SET_COOKIE.toString(), "cookieNameResponse=cookieValueResponse") ), makeRequest( request() .withMethod("GET") .withPath(calculatePath("some_pathRequest")) .withHeaders( header("requestHeaderNameOne", "requestHeaderValueOne_One", "requestHeaderValueOne_Two"), header("requestHeaderNameTwo", "requestHeaderValueTwo") ) .withCookies(cookie("cookieNameRequest", "cookieValueRequest")), headersToIgnore) ); // - in https assertEquals( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withReasonPhrase(HttpStatusCode.ACCEPTED_202.reasonPhrase()) .withBody("some_body_response") .withCookies(cookie("cookieNameResponse", "cookieValueResponse")) .withHeaders( header(SET_COOKIE.toString(), "cookieNameResponse=cookieValueResponse") ), makeRequest( request() .withMethod("GET") .withSecure(true) .withPath(calculatePath("some_pathRequest")) .withHeaders( header("requestHeaderNameOne", "requestHeaderValueOne_One", "requestHeaderValueOne_Two"), header("requestHeaderNameTwo", "requestHeaderValueTwo") ) .withCookies(cookie("cookieNameRequest", "cookieValueRequest")), headersToIgnore) ); } @Test public void shouldReturnResponseByMatchingPathAndMethodAndCookies() { // when mockServerClient .when( request() .withMethod("GET") .withPath(calculatePath("some_pathRequest")) .withCookies( cookie("requestCookieNameOne", "requestCookieValueOne"), cookie("requestCookieNameTwo", "requestCookieValueTwo") ) ) .respond( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withReasonPhrase(HttpStatusCode.ACCEPTED_202.reasonPhrase()) .withBody("some_body_response") .withCookies( cookie("responseCookieNameOne", "responseCookieValueOne"), cookie("responseCookieNameTwo", "responseCookieValueTwo") ) ); // then // - in http - cookie objects assertEquals( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withReasonPhrase(HttpStatusCode.ACCEPTED_202.reasonPhrase()) .withBody("some_body_response") .withCookies( cookie("responseCookieNameOne", "responseCookieValueOne"), cookie("responseCookieNameTwo", "responseCookieValueTwo") ) .withHeaders( header(SET_COOKIE.toString(), "responseCookieNameOne=responseCookieValueOne", "responseCookieNameTwo=responseCookieValueTwo") ), makeRequest( request() .withMethod("GET") .withPath(calculatePath("some_pathRequest")) .withHeaders( header("headerNameRequest", "headerValueRequest"), header(CONTENT_TYPE.toString(), MediaType.create("text", "plain").toString()) ) .withCookies( cookie("requestCookieNameOne", "requestCookieValueOne"), cookie("requestCookieNameTwo", "requestCookieValueTwo") ), headersToIgnore) ); // - in http - cookie header assertEquals( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withReasonPhrase(HttpStatusCode.ACCEPTED_202.reasonPhrase()) .withBody("some_body_response") .withCookies( cookie("responseCookieNameOne", "responseCookieValueOne"), cookie("responseCookieNameTwo", "responseCookieValueTwo") ) .withHeaders( header(SET_COOKIE.toString(), "responseCookieNameOne=responseCookieValueOne", "responseCookieNameTwo=responseCookieValueTwo") ), makeRequest( request() .withMethod("GET") .withPath(calculatePath("some_pathRequest")) .withHeaders( header("headerNameRequest", "headerValueRequest"), header("Cookie", "requestCookieNameOne=requestCookieValueOne; requestCookieNameTwo=requestCookieValueTwo") ), headersToIgnore) ); // - in https - cookie objects assertEquals( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withReasonPhrase(HttpStatusCode.ACCEPTED_202.reasonPhrase()) .withBody("some_body_response") .withCookies( cookie("responseCookieNameOne", "responseCookieValueOne"), cookie("responseCookieNameTwo", "responseCookieValueTwo") ) .withHeaders( header(SET_COOKIE.toString(), "responseCookieNameOne=responseCookieValueOne", "responseCookieNameTwo=responseCookieValueTwo") ), makeRequest( request() .withMethod("GET") .withSecure(true) .withPath(calculatePath("some_pathRequest")) .withHeaders( header("headerNameRequest", "headerValueRequest") ) .withCookies( cookie("requestCookieNameOne", "requestCookieValueOne"), cookie("requestCookieNameTwo", "requestCookieValueTwo") ), headersToIgnore) ); // - in https - cookie header assertEquals( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withReasonPhrase(HttpStatusCode.ACCEPTED_202.reasonPhrase()) .withBody("some_body_response") .withCookies( cookie("responseCookieNameOne", "responseCookieValueOne"), cookie("responseCookieNameTwo", "responseCookieValueTwo") ) .withHeaders( header(SET_COOKIE.toString(), "responseCookieNameOne=responseCookieValueOne", "responseCookieNameTwo=responseCookieValueTwo") ), makeRequest( request() .withMethod("GET") .withSecure(true) .withPath(calculatePath("some_pathRequest")) .withHeaders( header("headerNameRequest", "headerValueRequest"), header("Cookie", "requestCookieNameOne=requestCookieValueOne; requestCookieNameTwo=requestCookieValueTwo") ), headersToIgnore) ); } @Test public void shouldReturnResponseByMatchingPathAndMethodAndQueryStringParametersAndBodyParameters() { // when mockServerClient .when( request() .withMethod("POST") .withPath(calculatePath("some_pathRequest")) .withQueryStringParameters( param("queryStringParameterOneName", "queryStringParameterOneValueOne", "queryStringParameterOneValueTwo"), param("queryStringParameterTwoName", "queryStringParameterTwoValue") ) .withBody(params(param("bodyParameterName", "bodyParameterValue"))) ) .respond( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withReasonPhrase(HttpStatusCode.ACCEPTED_202.reasonPhrase()) .withBody("some_body") ); // then // - in http - url query string assertEquals( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withReasonPhrase(HttpStatusCode.ACCEPTED_202.reasonPhrase()) .withBody("some_body"), makeRequest( request() .withMethod("POST") .withPath(calculatePath("some_pathRequest")) .withQueryStringParameters( param("queryStringParameterOneName", "queryStringParameterOneValueOne", "queryStringParameterOneValueTwo"), param("queryStringParameterTwoName", "queryStringParameterTwoValue") ) .withBody(params(param("bodyParameterName", "bodyParameterValue"))), headersToIgnore) ); // - in https - query string parameter objects assertEquals( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withReasonPhrase(HttpStatusCode.ACCEPTED_202.reasonPhrase()) .withBody("some_body"), makeRequest( request() .withSecure(true) .withMethod("POST") .withPath(calculatePath("some_pathRequest")) .withQueryStringParameters( param("queryStringParameterOneName", "queryStringParameterOneValueOne", "queryStringParameterOneValueTwo"), param("queryStringParameterTwoName", "queryStringParameterTwoValue") ) .withBody(params(param("bodyParameterName", "bodyParameterValue"))), headersToIgnore) ); } @Test public void shouldReturnResponseByMatchingPathAndMethodAndQueryStringParametersAndBody() { // when mockServerClient .when( request() .withMethod("POST") .withPath(calculatePath("some_pathRequest")) .withQueryStringParameters( param("queryStringParameterOneName", "queryStringParameterOneValueOne", "queryStringParameterOneValueTwo"), param("queryStringParameterTwoName", "queryStringParameterTwoValue") ) .withBody("some_bodyRequest") ) .respond( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withReasonPhrase(HttpStatusCode.ACCEPTED_202.reasonPhrase()) .withBody("some_body_response") .withHeaders(header("headerNameResponse", "headerValueResponse")) .withCookies(cookie("cookieNameResponse", "cookieValueResponse")) ); // then // - in http - url query string assertEquals( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withReasonPhrase(HttpStatusCode.ACCEPTED_202.reasonPhrase()) .withBody("some_body_response") .withCookies(cookie("cookieNameResponse", "cookieValueResponse")) .withHeaders( header("headerNameResponse", "headerValueResponse"), header(SET_COOKIE.toString(), "cookieNameResponse=cookieValueResponse") ), makeRequest( request() .withMethod("POST") .withPath(calculatePath("some_pathRequest")) .withQueryStringParameters( param("queryStringParameterOneName", "queryStringParameterOneValueOne", "queryStringParameterOneValueTwo"), param("queryStringParameterTwoName", "queryStringParameterTwoValue") ) .withBody("some_bodyRequest") .withHeaders(header("headerNameRequest", "headerValueRequest")) .withCookies(cookie("cookieNameRequest", "cookieValueRequest")), headersToIgnore) ); // - in http - query string parameter objects assertEquals( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withReasonPhrase(HttpStatusCode.ACCEPTED_202.reasonPhrase()) .withBody("some_body_response") .withCookies(cookie("cookieNameResponse", "cookieValueResponse")) .withHeaders( header("headerNameResponse", "headerValueResponse"), header(SET_COOKIE.toString(), "cookieNameResponse=cookieValueResponse") ), makeRequest( request() .withMethod("POST") .withPath(calculatePath("some_pathRequest")) .withQueryStringParameters( param("queryStringParameterOneName", "queryStringParameterOneValueOne", "queryStringParameterOneValueTwo"), param("queryStringParameterTwoName", "queryStringParameterTwoValue") ) .withBody("some_bodyRequest") .withHeaders(header("headerNameRequest", "headerValueRequest")) .withCookies(cookie("cookieNameRequest", "cookieValueRequest")), headersToIgnore) ); // - in https - url string and query string parameter objects assertEquals( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withReasonPhrase(HttpStatusCode.ACCEPTED_202.reasonPhrase()) .withBody("some_body_response") .withCookies(cookie("cookieNameResponse", "cookieValueResponse")) .withHeaders( header("headerNameResponse", "headerValueResponse"), header(SET_COOKIE.toString(), "cookieNameResponse=cookieValueResponse") ), makeRequest( request() .withMethod("POST") .withPath(calculatePath("some_pathRequest")) .withQueryStringParameters( param("queryStringParameterOneName", "queryStringParameterOneValueOne", "queryStringParameterOneValueTwo"), param("queryStringParameterTwoName", "queryStringParameterTwoValue") ) .withBody("some_bodyRequest") .withHeaders(header("headerNameRequest", "headerValueRequest")) .withCookies(cookie("cookieNameRequest", "cookieValueRequest")), headersToIgnore) ); } @Test public void shouldReturnResponseByMatchingPathAndMethodAndBodyParameters() { // when mockServerClient .when( request() .withMethod("POST") .withPath(calculatePath("some_pathRequest")) .withBody(params( param("bodyParameterOneName", "Parameter One Value One", "Parameter One Value Two"), param("bodyParameterTwoName", "Parameter Two") )) ) .respond( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withReasonPhrase(HttpStatusCode.ACCEPTED_202.reasonPhrase()) .withBody("some_body_response") .withHeaders(header("headerNameResponse", "headerValueResponse")) .withCookies(cookie("cookieNameResponse", "cookieValueResponse")) ); // then // - in http - body string assertEquals( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withReasonPhrase(HttpStatusCode.ACCEPTED_202.reasonPhrase()) .withBody("some_body_response") .withCookies(cookie("cookieNameResponse", "cookieValueResponse")) .withHeaders( header("headerNameResponse", "headerValueResponse"), header(SET_COOKIE.toString(), "cookieNameResponse=cookieValueResponse") ), makeRequest( request() .withMethod("POST") .withPath(calculatePath("some_pathRequest")) .withBody(new StringBody("bodyParameterOneName=Parameter+One+Value+One" + "&bodyParameterOneName=Parameter+One+Value+Two" + "&bodyParameterTwoName=Parameter+Two")) .withHeaders(header("headerNameRequest", "headerValueRequest")) .withCookies(cookie("cookieNameRequest", "cookieValueRequest")), headersToIgnore) ); // - in http - body parameter objects assertEquals( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withReasonPhrase(HttpStatusCode.ACCEPTED_202.reasonPhrase()) .withBody("some_body_response") .withCookies(cookie("cookieNameResponse", "cookieValueResponse")) .withHeaders( header("headerNameResponse", "headerValueResponse"), header(SET_COOKIE.toString(), "cookieNameResponse=cookieValueResponse") ), makeRequest( request() .withMethod("POST") .withPath(calculatePath("some_pathRequest")) .withBody(params( param("bodyParameterOneName", "Parameter One Value One", "Parameter One Value Two"), param("bodyParameterTwoName", "Parameter Two") )) .withHeaders(header("headerNameRequest", "headerValueRequest")) .withCookies(cookie("cookieNameRequest", "cookieValueRequest")), headersToIgnore) ); // - in https - url string and query string parameter objects assertEquals( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withReasonPhrase(HttpStatusCode.ACCEPTED_202.reasonPhrase()) .withBody("some_body_response") .withCookies(cookie("cookieNameResponse", "cookieValueResponse")) .withHeaders( header("headerNameResponse", "headerValueResponse"), header(SET_COOKIE.toString(), "cookieNameResponse=cookieValueResponse") ), makeRequest( request() .withMethod("POST") .withPath(calculatePath("some_pathRequest")) .withBody(params( param("bodyParameterOneName", "Parameter One Value One", "Parameter One Value Two"), param("bodyParameterTwoName", "Parameter Two") )) .withHeaders(header("headerNameRequest", "headerValueRequest")) .withCookies(cookie("cookieNameRequest", "cookieValueRequest")), headersToIgnore) ); } @Test public void shouldReturnResponseByMatchingPathAndMethodAndParametersAndHeadersAndCookies() { // when mockServerClient .when( request() .withMethod("PUT") .withPath(calculatePath("some_pathRequest")) .withBody(new StringBody("bodyParameterOneName=Parameter+One+Value+One" + "&bodyParameterOneName=Parameter+One+Value+Two" + "&bodyParameterTwoName=Parameter+Two")) .withHeaders(header("headerNameRequest", "headerValueRequest")) .withCookies(cookie("cookieNameRequest", "cookieValueRequest")) ) .respond( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withReasonPhrase(HttpStatusCode.ACCEPTED_202.reasonPhrase()) .withBody("some_body_response") .withHeaders(header("headerNameResponse", "headerValueResponse")) .withCookies(cookie("cookieNameResponse", "cookieValueResponse")) ); // then // - in http - body string assertEquals( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withReasonPhrase(HttpStatusCode.ACCEPTED_202.reasonPhrase()) .withBody("some_body_response") .withCookies(cookie("cookieNameResponse", "cookieValueResponse")) .withHeaders( header("headerNameResponse", "headerValueResponse"), header(SET_COOKIE.toString(), "cookieNameResponse=cookieValueResponse") ), makeRequest( request() .withMethod("PUT") .withPath(calculatePath("some_pathRequest")) .withBody(new StringBody("bodyParameterOneName=Parameter+One+Value+One" + "&bodyParameterOneName=Parameter+One+Value+Two" + "&bodyParameterTwoName=Parameter+Two")) .withHeaders( header("headerNameRequest", "headerValueRequest"), header("Cookie", "cookieNameRequest=cookieValueRequest") ), headersToIgnore) ); // - in http - body parameter objects assertEquals( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withReasonPhrase(HttpStatusCode.ACCEPTED_202.reasonPhrase()) .withBody("some_body_response") .withCookies(cookie("cookieNameResponse", "cookieValueResponse")) .withHeaders( header("headerNameResponse", "headerValueResponse"), header(SET_COOKIE.toString(), "cookieNameResponse=cookieValueResponse") ), makeRequest( request() .withMethod("PUT") .withPath(calculatePath("some_pathRequest")) .withBody(params( param("bodyParameterOneName", "Parameter One Value One", "Parameter One Value Two"), param("bodyParameterTwoName", "Parameter Two") )) .withHeaders(header("headerNameRequest", "headerValueRequest")) .withCookies(cookie("cookieNameRequest", "cookieValueRequest")), headersToIgnore) ); } @Test public void shouldReturnResponseByNotMatchingBodyParameterWithNotOperatorForNameAndValue() { // when mockServerClient .when( request() .withMethod("POST") .withPath(calculatePath("some_pathRequest")) .withBody(params( param(not("bodyParameterOneName"), not("Parameter One Value One"), not("Parameter One Value Two")), param("bodyParameterTwoName", "Parameter Two") )) ) .respond( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withReasonPhrase(HttpStatusCode.ACCEPTED_202.reasonPhrase()) .withBody("some_body_response") ); // then // wrong query string parameter name assertEquals( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withReasonPhrase(HttpStatusCode.ACCEPTED_202.reasonPhrase()) .withBody("some_body_response"), makeRequest( request() .withMethod("POST") .withPath(calculatePath("some_pathRequest")) .withBody(params( param("OTHERBodyParameterOneName", "Parameter One Value One", "Parameter One Value Two"), param("bodyParameterTwoName", "Parameter Two") )) .withHeaders(header("headerNameRequest", "headerValueRequest")) .withCookies(cookie("cookieNameRequest", "cookieValueRequest")), headersToIgnore) ); // wrong query string parameter name assertEquals( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withReasonPhrase(HttpStatusCode.ACCEPTED_202.reasonPhrase()) .withBody("some_body_response"), makeRequest( request() .withMethod("POST") .withPath(calculatePath("some_pathRequest")) .withBody(new StringBody("OTHERBodyParameterOneName=Parameter+One+Value+One" + "&OTHERBodyParameterOneName=Parameter+One+Value+Two" + "&bodyParameterTwoName=Parameter+Two")) .withHeaders(header("headerNameRequest", "headerValueRequest")) .withCookies(cookie("cookieNameRequest", "cookieValueRequest")), headersToIgnore) ); // wrong query string parameter value assertEquals( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withReasonPhrase(HttpStatusCode.ACCEPTED_202.reasonPhrase()) .withBody("some_body_response"), makeRequest( request() .withMethod("POST") .withPath(calculatePath("some_pathRequest")) .withBody(params( param("bodyParameterOneName", "OTHER Parameter One Value One", "OTHER Parameter One Value Two"), param("bodyParameterTwoName", "Parameter Two") )) .withHeaders(header("headerNameRequest", "headerValueRequest")) .withCookies(cookie("cookieNameRequest", "cookieValueRequest")), headersToIgnore) ); // wrong query string parameter value assertEquals( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withReasonPhrase(HttpStatusCode.ACCEPTED_202.reasonPhrase()) .withBody("some_body_response"), makeRequest( request() .withMethod("POST") .withPath(calculatePath("some_pathRequest")) .withBody(new StringBody("bodyParameterOneName=OTHER Parameter+One+Value+One" + "&bodyParameterOneName=OTHER Parameter+One+Value+Two" + "&bodyParameterTwoName=Parameter+Two")) .withHeaders(header("headerNameRequest", "headerValueRequest")) .withCookies(cookie("cookieNameRequest", "cookieValueRequest")), headersToIgnore) ); } @Test public void shouldReturnResponseByNotMatchingBodyParameterWithNotOperatorForName() { // when mockServerClient .when( request() .withMethod("POST") .withPath(calculatePath("some_pathRequest")) .withBody(params( param(not("bodyParameterOneName"), string("Parameter One Value One"), string("Parameter One Value Two")), param("bodyParameterTwoName", "Parameter Two") )) ) .respond( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withReasonPhrase(HttpStatusCode.ACCEPTED_202.reasonPhrase()) .withBody("some_body_response") ); // then // wrong query string parameter name assertEquals( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withReasonPhrase(HttpStatusCode.ACCEPTED_202.reasonPhrase()) .withBody("some_body_response"), makeRequest( request() .withMethod("POST") .withPath(calculatePath("some_pathRequest")) .withBody(params( param("OTHERBodyParameterOneName", "Parameter One Value One", "Parameter One Value Two"), param("bodyParameterTwoName", "Parameter Two") )) .withHeaders(header("headerNameRequest", "headerValueRequest")) .withCookies(cookie("cookieNameRequest", "cookieValueRequest")), headersToIgnore) ); // wrong query string parameter name assertEquals( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withReasonPhrase(HttpStatusCode.ACCEPTED_202.reasonPhrase()) .withBody("some_body_response"), makeRequest( request() .withMethod("POST") .withPath(calculatePath("some_pathRequest")) .withBody(new StringBody("OTHERBodyParameterOneName=Parameter+One+Value+One" + "&OTHERBodyParameterOneName=Parameter+One+Value+Two" + "&bodyParameterTwoName=Parameter+Two")) .withHeaders(header("headerNameRequest", "headerValueRequest")) .withCookies(cookie("cookieNameRequest", "cookieValueRequest")), headersToIgnore) ); } @Test public void shouldReturnResponseByNotMatchingBodyParameterWithNotOperatorForValue() { // when mockServerClient .when( request() .withMethod("POST") .withPath(calculatePath("some_pathRequest")) .withBody(params( param(string("bodyParameterOneName"), not("Parameter One Value One"), not("Parameter One Value Two")), param("bodyParameterTwoName", "Parameter Two") )) ) .respond( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withReasonPhrase(HttpStatusCode.ACCEPTED_202.reasonPhrase()) .withBody("some_body_response") ); // then // wrong query string parameter value assertEquals( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withReasonPhrase(HttpStatusCode.ACCEPTED_202.reasonPhrase()) .withBody("some_body_response"), makeRequest( request() .withMethod("POST") .withPath(calculatePath("some_pathRequest")) .withBody(params( param("bodyParameterOneName", "OTHER Parameter One Value One", "OTHER Parameter One Value Two"), param("bodyParameterTwoName", "Parameter Two") )) .withHeaders(header("headerNameRequest", "headerValueRequest")) .withCookies(cookie("cookieNameRequest", "cookieValueRequest")), headersToIgnore) ); // wrong query string parameter value assertEquals( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withReasonPhrase(HttpStatusCode.ACCEPTED_202.reasonPhrase()) .withBody("some_body_response"), makeRequest( request() .withMethod("POST") .withPath(calculatePath("some_pathRequest")) .withBody(new StringBody("bodyParameterOneName=OTHER Parameter+One+Value+One" + "&bodyParameterOneName=OTHER Parameter+One+Value+Two" + "&bodyParameterTwoName=Parameter+Two")) .withHeaders(header("headerNameRequest", "headerValueRequest")) .withCookies(cookie("cookieNameRequest", "cookieValueRequest")), headersToIgnore) ); } @Test public void shouldReturnResponseByNotMatchingQueryStringParameterWithNotOperatorForNameAndValue() { // when mockServerClient .when( request() .withMethod("POST") .withPath(calculatePath("some_pathRequest")) .withQueryStringParameters( param(not("queryStringParameterOneName"), not("Parameter One Value One"), not("Parameter One Value Two")), param("queryStringParameterTwoName", "Parameter Two") ) ) .respond( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withReasonPhrase(HttpStatusCode.ACCEPTED_202.reasonPhrase()) .withBody("some_body_response") ); // then // wrong query string parameter name assertEquals( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withReasonPhrase(HttpStatusCode.ACCEPTED_202.reasonPhrase()) .withBody("some_body_response"), makeRequest( request() .withMethod("POST") .withPath(calculatePath("some_pathRequest")) .withQueryStringParameters( param("OTHERQueryStringParameterOneName", "Parameter One Value One", "Parameter One Value Two"), param("queryStringParameterTwoName", "Parameter Two") ), headersToIgnore) ); // wrong query string parameter value assertEquals( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withReasonPhrase(HttpStatusCode.ACCEPTED_202.reasonPhrase()) .withBody("some_body_response"), makeRequest( request() .withMethod("POST") .withPath(calculatePath("some_pathRequest")) .withQueryStringParameters( param("queryStringParameterOneName", "OTHER Parameter One Value One", "OTHER Parameter One Value Two"), param("queryStringParameterTwoName", "Parameter Two") ), headersToIgnore) ); } @Test public void shouldReturnResponseByNotMatchingQueryStringParameterWithNotOperatorForName() { // when mockServerClient .when( request() .withMethod("POST") .withPath(calculatePath("some_pathRequest")) .withQueryStringParameters( param(not("queryStringParameterOneName"), string("Parameter One Value One"), string("Parameter One Value Two")), param("queryStringParameterTwoName", "Parameter Two") ) ) .respond( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withReasonPhrase(HttpStatusCode.ACCEPTED_202.reasonPhrase()) .withBody("some_body_response") ); // then // wrong query string parameter name assertEquals( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withReasonPhrase(HttpStatusCode.ACCEPTED_202.reasonPhrase()) .withBody("some_body_response"), makeRequest( request() .withMethod("POST") .withPath(calculatePath("some_pathRequest")) .withQueryStringParameters( param("OTHERQueryStringParameterOneName", "Parameter One Value One", "Parameter One Value Two"), param("queryStringParameterTwoName", "Parameter Two") ), headersToIgnore) ); } @Test public void shouldReturnResponseByNotMatchingQueryStringParameterWithNotOperatorForValue() { // when mockServerClient .when( request() .withMethod("POST") .withPath(calculatePath("some_pathRequest")) .withQueryStringParameters( param(string("queryStringParameterOneName"), not("Parameter One Value One"), not("Parameter One Value Two")), param("queryStringParameterTwoName", "Parameter Two") ) ) .respond( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withReasonPhrase(HttpStatusCode.ACCEPTED_202.reasonPhrase()) .withBody("some_body_response") ); // then // wrong query string parameter value assertEquals( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withReasonPhrase(HttpStatusCode.ACCEPTED_202.reasonPhrase()) .withBody("some_body_response"), makeRequest( request() .withMethod("POST") .withPath(calculatePath("some_pathRequest")) .withQueryStringParameters( param("queryStringParameterOneName", "OTHER Parameter One Value One", "OTHER Parameter One Value Two"), param("queryStringParameterTwoName", "Parameter Two") ), headersToIgnore) ); } @Test public void shouldReturnResponseByNotMatchingCookieWithNotOperatorForNameAndValue() { // when mockServerClient .when( request() .withMethod("GET") .withPath(calculatePath("some_pathRequest")) .withCookies( cookie(not("requestCookieNameOne"), not("requestCookieValueOne")), cookie("requestCookieNameTwo", "requestCookieValueTwo") ) ) .respond( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withReasonPhrase(HttpStatusCode.ACCEPTED_202.reasonPhrase()) .withBody("some_body_response") ); // then // wrong query string cookie name assertEquals( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withReasonPhrase(HttpStatusCode.ACCEPTED_202.reasonPhrase()) .withBody("some_body_response"), makeRequest( request() .withMethod("GET") .withPath(calculatePath("some_pathRequest")) .withCookies( cookie("OTHERrequestCookieNameOne", "requestCookieValueOne"), cookie("requestCookieNameTwo", "requestCookieValueTwo") ), headersToIgnore) ); // wrong query string cookie value assertEquals( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withReasonPhrase(HttpStatusCode.ACCEPTED_202.reasonPhrase()) .withBody("some_body_response"), makeRequest( request() .withMethod("GET") .withPath(calculatePath("some_pathRequest")) .withCookies( cookie("requestCookieNameOne", "OTHERrequestCookieValueOne"), cookie("requestCookieNameTwo", "requestCookieValueTwo") ), headersToIgnore) ); } @Test public void shouldReturnResponseByNotMatchingCookieWithNotOperatorForName() { // when mockServerClient .when( request() .withMethod("GET") .withPath(calculatePath("some_pathRequest")) .withCookies( cookie(not("requestCookieNameOne"), string("requestCookieValueOne")), cookie("requestCookieNameTwo", "requestCookieValueTwo") ) ) .respond( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withReasonPhrase(HttpStatusCode.ACCEPTED_202.reasonPhrase()) .withBody("some_body_response") ); // then // wrong query string cookie name assertEquals( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withReasonPhrase(HttpStatusCode.ACCEPTED_202.reasonPhrase()) .withBody("some_body_response"), makeRequest( request() .withMethod("GET") .withPath(calculatePath("some_pathRequest")) .withCookies( cookie("OTHERrequestCookieNameOne", "requestCookieValueOne"), cookie("requestCookieNameTwo", "requestCookieValueTwo") ), headersToIgnore) ); } @Test public void shouldReturnResponseByNotMatchingCookieWithNotOperatorForValue() { // when mockServerClient .when( request() .withMethod("GET") .withPath(calculatePath("some_pathRequest")) .withCookies( cookie(string("requestCookieNameOne"), not("requestCookieValueOne")), cookie("requestCookieNameTwo", "requestCookieValueTwo") ) ) .respond( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withReasonPhrase(HttpStatusCode.ACCEPTED_202.reasonPhrase()) .withBody("some_body_response") ); // then // wrong query string cookie value assertEquals( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withReasonPhrase(HttpStatusCode.ACCEPTED_202.reasonPhrase()) .withBody("some_body_response"), makeRequest( request() .withMethod("GET") .withPath(calculatePath("some_pathRequest")) .withCookies( cookie("requestCookieNameOne", "OTHERrequestCookieValueOne"), cookie("requestCookieNameTwo", "requestCookieValueTwo") ), headersToIgnore) ); } @Test public void shouldReturnResponseByNotMatchingHeaderWithNotOperatorForNameAndValue() { // when mockServerClient .when( request() .withMethod("GET") .withPath(calculatePath("some_pathRequest")) .withHeaders( header(not("requestHeaderNameOne"), not("requestHeaderValueOne")), header("requestHeaderNameTwo", "requestHeaderValueTwo") ) ) .respond( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withReasonPhrase(HttpStatusCode.ACCEPTED_202.reasonPhrase()) .withBody("some_body_response") ); // then // wrong query string header name assertEquals( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withReasonPhrase(HttpStatusCode.ACCEPTED_202.reasonPhrase()) .withBody("some_body_response"), makeRequest( request() .withMethod("GET") .withPath(calculatePath("some_pathRequest")) .withHeaders( header("OTHERrequestHeaderNameOne", "requestHeaderValueOne"), header("requestHeaderNameTwo", "requestHeaderValueTwo") ), headersToIgnore) ); // wrong query string header value assertEquals( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withReasonPhrase(HttpStatusCode.ACCEPTED_202.reasonPhrase()) .withBody("some_body_response"), makeRequest( request() .withMethod("GET") .withPath(calculatePath("some_pathRequest")) .withHeaders( header("requestHeaderNameOne", "OTHERrequestHeaderValueOne"), header("requestHeaderNameTwo", "requestHeaderValueTwo") ), headersToIgnore) ); } @Test public void shouldReturnResponseByNotMatchingHeaderWithNotOperatorForName() { // when mockServerClient .when( request() .withMethod("GET") .withPath(calculatePath("some_pathRequest")) .withHeaders( header(not("requestHeaderNameOne"), string("requestHeaderValueOne")), header("requestHeaderNameTwo", "requestHeaderValueTwo") ) ) .respond( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withReasonPhrase(HttpStatusCode.ACCEPTED_202.reasonPhrase()) .withBody("some_body_response") ); // then // wrong query string header name assertEquals( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withReasonPhrase(HttpStatusCode.ACCEPTED_202.reasonPhrase()) .withBody("some_body_response"), makeRequest( request() .withMethod("GET") .withPath(calculatePath("some_pathRequest")) .withHeaders( header("OTHERrequestHeaderNameOne", "requestHeaderValueOne"), header("requestHeaderNameTwo", "requestHeaderValueTwo") ), headersToIgnore) ); } @Test public void shouldReturnResponseByNotMatchingHeaderWithNotOperatorForValue() { // when mockServerClient .when( request() .withMethod("GET") .withPath(calculatePath("some_pathRequest")) .withHeaders( header(string("requestHeaderNameOne"), not("requestHeaderValueOne")), header("requestHeaderNameTwo", "requestHeaderValueTwo") ) ) .respond( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withReasonPhrase(HttpStatusCode.ACCEPTED_202.reasonPhrase()) .withBody("some_body_response") ); // then // wrong query string header value assertEquals( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withReasonPhrase(HttpStatusCode.ACCEPTED_202.reasonPhrase()) .withBody("some_body_response"), makeRequest( request() .withMethod("GET") .withPath(calculatePath("some_pathRequest")) .withHeaders( header("requestHeaderNameOne", "OTHERrequestHeaderValueOne"), header("requestHeaderNameTwo", "requestHeaderValueTwo") ), headersToIgnore) ); } @Test public void shouldNotReturnResponseForWhenTimeToLiveExpired() { // when mockServerClient .when( request().withPath(calculatePath("some_path")), exactly(2), TimeToLive.exactly(TimeUnit.SECONDS, 3L) ) .respond( response().withBody("some_body").withDelay(TimeUnit.SECONDS, 3L) ); // then assertEquals( response() .withStatusCode(OK_200.code()) .withReasonPhrase(OK_200.reasonPhrase()) .withBody("some_body"), makeRequest( request() .withPath(calculatePath("some_path")), headersToIgnore) ); // - in http assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()) .withReasonPhrase(HttpStatusCode.NOT_FOUND_404.reasonPhrase()), makeRequest( request() .withPath(calculatePath("some_path")), headersToIgnore) ); // - in https assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()) .withReasonPhrase(HttpStatusCode.NOT_FOUND_404.reasonPhrase()), makeRequest( request() .withSecure(true) .withPath(calculatePath("some_path")), headersToIgnore) ); } @Test public void shouldNotReturnResponseForMatchingBodyWithNotOperator() { // when mockServerClient .when( request() .withBody(Not.not(json("{" + NEW_LINE + " \"id\": 1," + NEW_LINE + " \"name\": \"A green door\"," + NEW_LINE + " \"price\": 12.50," + NEW_LINE + " \"tags\": [\"home\", \"green\"]" + NEW_LINE + "}"))), exactly(2) ) .respond( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withReasonPhrase(HttpStatusCode.ACCEPTED_202.reasonPhrase()) .withBody("some_body") ); // then // - in http assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()) .withReasonPhrase(HttpStatusCode.NOT_FOUND_404.reasonPhrase()), makeRequest( request() .withPath(calculatePath("some_path")) .withMethod("POST") .withBody("{" + NEW_LINE + " \"id\": 1," + NEW_LINE + " \"extra_ignored_field\": \"some value\"," + NEW_LINE + " \"name\": \"A green door\"," + NEW_LINE + " \"price\": 12.50," + NEW_LINE + " \"tags\": [\"home\", \"green\"]" + NEW_LINE + "}"), headersToIgnore) ); // - in https assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()) .withReasonPhrase(HttpStatusCode.NOT_FOUND_404.reasonPhrase()), makeRequest( request() .withSecure(true) .withPath(calculatePath("some_path")) .withMethod("POST") .withBody("{" + NEW_LINE + " \"id\": 1," + NEW_LINE + " \"extra_ignored_array\": [\"one\", \"two\"]," + NEW_LINE + " \"name\": \"A green door\"," + NEW_LINE + " \"price\": 12.50," + NEW_LINE + " \"tags\": [\"home\", \"green\"]" + NEW_LINE + "}"), headersToIgnore) ); } @Test public void shouldNotReturnResponseForNonMatchingXPathBody() { // when mockServerClient.when(request().withBody(new XPathBody("/bookstore/book[price>35]/price")), exactly(2)).respond(response().withBody("some_body")); // then // - in http assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()) .withReasonPhrase(HttpStatusCode.NOT_FOUND_404.reasonPhrase()), makeRequest( request() .withSecure(true) .withPath(calculatePath("some_path")) .withMethod("POST") .withBody(new StringBody("" + "<?xml version=\"1.0\" encoding=\"ISO-8859-1\"?>" + NEW_LINE + "<bookstore>" + NEW_LINE + " <book category=\"COOKING\">" + NEW_LINE + " <title lang=\"en\">Everyday Italian</title>" + NEW_LINE + " <author>Giada De Laurentiis</author>" + NEW_LINE + " <year>2005</year>" + NEW_LINE + " <price>30.00</price>" + NEW_LINE + " </book>" + NEW_LINE + " <book category=\"CHILDREN\">" + NEW_LINE + " <title lang=\"en\">Harry Potter</title>" + NEW_LINE + " <author>J K. Rowling</author>" + NEW_LINE + " <year>2005</year>" + NEW_LINE + " <price>29.99</price>" + NEW_LINE + " </book>" + NEW_LINE + " <book category=\"WEB\">" + NEW_LINE + " <title lang=\"en\">Learning XML</title>" + NEW_LINE + " <author>Erik T. Ray</author>" + NEW_LINE + " <year>2003</year>" + NEW_LINE + " <price>31.95</price>" + NEW_LINE + " </book>" + NEW_LINE + "</bookstore>")), headersToIgnore) ); // - in https assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()) .withReasonPhrase(HttpStatusCode.NOT_FOUND_404.reasonPhrase()), makeRequest( request() .withSecure(true) .withPath(calculatePath("some_path")) .withMethod("POST") .withBody(new StringBody("" + "<?xml version=\"1.0\" encoding=\"ISO-8859-1\"?>" + NEW_LINE + "<bookstore>" + NEW_LINE + " <book category=\"COOKING\">" + NEW_LINE + " <title lang=\"en\">Everyday Italian</title>" + NEW_LINE + " <author>Giada De Laurentiis</author>" + NEW_LINE + " <year>2005</year>" + NEW_LINE + " <price>30.00</price>" + NEW_LINE + " </book>" + NEW_LINE + " <book category=\"CHILDREN\">" + NEW_LINE + " <title lang=\"en\">Harry Potter</title>" + NEW_LINE + " <author>J K. Rowling</author>" + NEW_LINE + " <year>2005</year>" + NEW_LINE + " <price>29.99</price>" + NEW_LINE + " </book>" + NEW_LINE + " <book category=\"WEB\">" + NEW_LINE + " <title lang=\"en\">Learning XML</title>" + NEW_LINE + " <author>Erik T. Ray</author>" + NEW_LINE + " <year>2003</year>" + NEW_LINE + " <price>31.95</price>" + NEW_LINE + " </book>" + NEW_LINE + "</bookstore>")), headersToIgnore) ); } @Test public void shouldNotReturnResponseForNonMatchingXmlBody() { // when mockServerClient.when(request().withBody(xml("" + "<?xml version=\"1.0\" encoding=\"ISO-8859-1\"?>" + NEW_LINE + "<bookstore>" + NEW_LINE + " <book category=\"COOKING\" nationality=\"ITALIAN\">" + NEW_LINE + " <title lang=\"en\">Everyday Italian</title>" + NEW_LINE + " <author>Giada De Laurentiis</author>" + NEW_LINE + " <year>2005</year>" + NEW_LINE + " <price>30.00</price>" + NEW_LINE + " </book>" + NEW_LINE + "</bookstore>")), exactly(2)).respond(response().withBody("some_body")); // then // - in http assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()) .withReasonPhrase(HttpStatusCode.NOT_FOUND_404.reasonPhrase()), makeRequest( request() .withSecure(true) .withPath(calculatePath("some_path")) .withMethod("POST") .withBody(new StringBody("" + "<?xml version=\"1.0\" encoding=\"ISO-8859-1\"?>" + NEW_LINE + "<bookstore>" + NEW_LINE + " <book category=\"COOKING\">" + NEW_LINE + " <title lang=\"en\">Everyday Italian</title>" + NEW_LINE + " <author>Giada De Laurentiis</author>" + NEW_LINE + " <year>2005</year>" + NEW_LINE + " <price>30.00</price>" + NEW_LINE + " </book>" + NEW_LINE + "</bookstore>")), headersToIgnore) ); // - in https assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()) .withReasonPhrase(HttpStatusCode.NOT_FOUND_404.reasonPhrase()), makeRequest( request() .withSecure(true) .withPath(calculatePath("some_path")) .withMethod("POST") .withBody(new StringBody("" + "<?xml version=\"1.0\" encoding=\"ISO-8859-1\"?>" + NEW_LINE + "<bookstore>" + NEW_LINE + " <book category=\"COOKING\">" + NEW_LINE + " <title lang=\"en\">Everyday Italian</title>" + NEW_LINE + " <author>Giada De Laurentiis</author>" + NEW_LINE + " <year>2005</year>" + NEW_LINE + " <price>30.00</price>" + NEW_LINE + " </book>" + NEW_LINE + "</bookstore>")), headersToIgnore) ); } @Test public void shouldNotReturnResponseForNonMatchingJsonBody() { // when mockServerClient.when(request().withBody(json("{" + NEW_LINE + " \"id\": 1," + NEW_LINE + " \"name\": \"A green door\"," + NEW_LINE + " \"price\": 12.50," + NEW_LINE + " \"tags\": [\"home\", \"green\"]" + NEW_LINE + "}")), exactly(2)).respond(response().withBody("some_body")); // then // - in http assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()) .withReasonPhrase(HttpStatusCode.NOT_FOUND_404.reasonPhrase()), makeRequest( request() .withPath(calculatePath("some_path")) .withMethod("POST") .withBody("{" + NEW_LINE + " \"id\": 1," + NEW_LINE + " \"name\": \"---- XXXX WRONG VALUE XXXX ----\"," + NEW_LINE + " \"price\": 12.50," + NEW_LINE + " \"tags\": [\"home\", \"green\"]" + NEW_LINE + "}"), headersToIgnore) ); // - in https assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()) .withReasonPhrase(HttpStatusCode.NOT_FOUND_404.reasonPhrase()), makeRequest( request() .withSecure(true) .withPath(calculatePath("some_path")) .withMethod("POST") .withBody("{" + NEW_LINE + " \"id\": 1," + NEW_LINE + " \"name\": \"---- XXXX WRONG VALUE XXXX ----\"," + NEW_LINE + " \"price\": 12.50," + NEW_LINE + " \"tags\": [\"home\", \"green\"]" + NEW_LINE + "}"), headersToIgnore) ); } @Test public void shouldNotReturnResponseForNonMatchingJsonBodyWithMatchType() { // when mockServerClient .when( request() .withBody(json("{" + NEW_LINE + " \"id\": 1," + NEW_LINE + " \"name\": \"A green door\"," + NEW_LINE + " \"price\": 12.50," + NEW_LINE + " \"tags\": [\"home\", \"green\"]" + NEW_LINE + "}", MatchType.STRICT)), exactly(2)) .respond( response() .withBody("some_body") ); // then // - in http assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()) .withReasonPhrase(HttpStatusCode.NOT_FOUND_404.reasonPhrase()), makeRequest( request() .withPath(calculatePath("some_path")) .withMethod("POST") .withBody("{" + NEW_LINE + " \"id\": 1," + NEW_LINE + " \"extra field\": \"some value\"," + NEW_LINE + " \"name\": \"A green door\"," + NEW_LINE + " \"price\": 12.50," + NEW_LINE + " \"tags\": [\"home\", \"green\"]" + NEW_LINE + "}"), headersToIgnore) ); // - in https assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()) .withReasonPhrase(HttpStatusCode.NOT_FOUND_404.reasonPhrase()), makeRequest( request() .withSecure(true) .withPath(calculatePath("some_path")) .withMethod("POST") .withBody("{" + NEW_LINE + " \"id\": 1," + NEW_LINE + " \"extra field\": \"some value\"," + NEW_LINE + " \"name\": \"A green door\"," + NEW_LINE + " \"price\": 12.50," + NEW_LINE + " \"tags\": [\"home\", \"green\"]" + NEW_LINE + "}"), headersToIgnore) ); } @Test public void shouldNotReturnResponseForNonMatchingJsonSchema() { // when mockServerClient.when(request().withBody(jsonSchema("{" + NEW_LINE + " \"$schema\": \"http://json-schema.org/draft-04/schema#\"," + NEW_LINE + " \"title\": \"Product\"," + NEW_LINE + " \"description\": \"A product from Acme's catalog\"," + NEW_LINE + " \"type\": \"object\"," + NEW_LINE + " \"properties\": {" + NEW_LINE + " \"id\": {" + NEW_LINE + " \"description\": \"The unique identifier for a product\"," + NEW_LINE + " \"type\": \"integer\"" + NEW_LINE + " }," + NEW_LINE + " \"name\": {" + NEW_LINE + " \"description\": \"Name of the product\"," + NEW_LINE + " \"type\": \"string\"" + NEW_LINE + " }," + NEW_LINE + " \"price\": {" + NEW_LINE + " \"type\": \"number\"," + NEW_LINE + " \"minimum\": 0," + NEW_LINE + " \"exclusiveMinimum\": true" + NEW_LINE + " }," + NEW_LINE + " \"tags\": {" + NEW_LINE + " \"type\": \"array\"," + NEW_LINE + " \"items\": {" + NEW_LINE + " \"type\": \"string\"" + NEW_LINE + " }," + NEW_LINE + " \"minItems\": 1," + NEW_LINE + " \"uniqueItems\": true" + NEW_LINE + " }" + NEW_LINE + " }," + NEW_LINE + " \"required\": [\"id\", \"name\", \"price\"]" + NEW_LINE + "}")), exactly(2)).respond(response().withBody("some_body")); // then // - in http assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()) .withReasonPhrase(HttpStatusCode.NOT_FOUND_404.reasonPhrase()), makeRequest( request() .withPath(calculatePath("some_path")) .withMethod("POST") .withBody("{" + NEW_LINE + " \"id\": 1," + NEW_LINE + " \"wrong field name\": \"A green door\"," + NEW_LINE + " \"price\": 12.50," + NEW_LINE + " \"tags\": [\"home\", \"green\"]" + NEW_LINE + "}"), headersToIgnore) ); // - in https assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()) .withReasonPhrase(HttpStatusCode.NOT_FOUND_404.reasonPhrase()), makeRequest( request() .withSecure(true) .withPath(calculatePath("some_path")) .withMethod("POST") .withBody("{" + NEW_LINE + " \"id\": 1," + NEW_LINE + " \"name\": \"A green door\"," + NEW_LINE + " \"wrong field name\": 12.50," + NEW_LINE + " \"tags\": [\"home\", \"green\"]" + NEW_LINE + "}"), headersToIgnore) ); } @Test public void shouldNotReturnResponseForMatchingPathWithNotOperator() { // when mockServerClient .when( request() .withPath(not(calculatePath("some_path"))) ) .respond( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withReasonPhrase(HttpStatusCode.ACCEPTED_202.reasonPhrase()) .withBody("some_body_response") ); // then // - in http assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()) .withReasonPhrase(HttpStatusCode.NOT_FOUND_404.reasonPhrase()), makeRequest( request() .withPath(calculatePath("some_path")), headersToIgnore) ); // - in https assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()) .withReasonPhrase(HttpStatusCode.NOT_FOUND_404.reasonPhrase()), makeRequest( request() .withPath(calculatePath("some_path")), headersToIgnore) ); } @Test public void shouldNotReturnResponseForMatchingMethodWithNotOperator() { // when mockServerClient .when( request() .withMethod(not("GET")) ) .respond( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withReasonPhrase(HttpStatusCode.ACCEPTED_202.reasonPhrase()) .withBody("some_body_response") ); // then // - in http assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()) .withReasonPhrase(HttpStatusCode.NOT_FOUND_404.reasonPhrase()), makeRequest( request() .withMethod("GET"), headersToIgnore) ); // - in https assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()) .withReasonPhrase(HttpStatusCode.NOT_FOUND_404.reasonPhrase()), makeRequest( request() .withMethod("GET"), headersToIgnore) ); } @Test public void shouldNotReturnResponseForNonMatchingBodyParameterName() { // when mockServerClient .when( request() .withMethod("POST") .withPath(calculatePath("some_pathRequest")) .withBody(params( param("bodyParameterOneName", "Parameter One Value One", "Parameter One Value Two"), param("bodyParameterTwoName", "Parameter Two") )) ) .respond( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withReasonPhrase(HttpStatusCode.ACCEPTED_202.reasonPhrase()) .withBody("some_body_response") .withHeaders(header("headerNameResponse", "headerValueResponse")) .withCookies(cookie("cookieNameResponse", "cookieValueResponse")) ); // then // wrong query string parameter name assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()) .withReasonPhrase(HttpStatusCode.NOT_FOUND_404.reasonPhrase()), makeRequest( request() .withMethod("POST") .withPath(calculatePath("some_pathRequest")) .withBody(params( param("OTHERBodyParameterOneName", "Parameter One Value One", "Parameter One Value Two"), param("bodyParameterTwoName", "Parameter Two") )) .withHeaders(header("headerNameRequest", "headerValueRequest")) .withCookies(cookie("cookieNameRequest", "cookieValueRequest")), headersToIgnore) ); // wrong query string parameter name assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()) .withReasonPhrase(HttpStatusCode.NOT_FOUND_404.reasonPhrase()), makeRequest( request() .withMethod("POST") .withPath(calculatePath("some_pathRequest")) .withBody(new StringBody("OTHERBodyParameterOneName=Parameter+One+Value+One" + "&bodyParameterOneName=Parameter+One+Value+Two" + "&bodyParameterTwoName=Parameter+Two")) .withHeaders(header("headerNameRequest", "headerValueRequest")) .withCookies(cookie("cookieNameRequest", "cookieValueRequest")), headersToIgnore) ); } @Test public void shouldNotReturnResponseForMatchingBodyParameterWithNotOperator() { // when mockServerClient .when( request() .withMethod("POST") .withPath(calculatePath("some_pathRequest")) .withBody(params( param(not("bodyParameterOneName"), not("Parameter One Value One"), not("Parameter One Value Two")), param("bodyParameterTwoName", "Parameter Two") )) ) .respond( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withReasonPhrase(HttpStatusCode.ACCEPTED_202.reasonPhrase()) .withBody("some_body_response") ); // then // wrong query string parameter name assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()) .withReasonPhrase(HttpStatusCode.NOT_FOUND_404.reasonPhrase()), makeRequest( request() .withMethod("POST") .withPath(calculatePath("some_pathRequest")) .withBody(params( param("bodyParameterOneName", "Parameter One Value One", "Parameter One Value Two"), param("bodyParameterTwoName", "Parameter Two") )) .withHeaders(header("headerNameRequest", "headerValueRequest")) .withCookies(cookie("cookieNameRequest", "cookieValueRequest")), headersToIgnore) ); // wrong query string parameter name assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()) .withReasonPhrase(HttpStatusCode.NOT_FOUND_404.reasonPhrase()), makeRequest( request() .withMethod("POST") .withPath(calculatePath("some_pathRequest")) .withBody(new StringBody("bodyParameterOneName=Other Parameter+One+Value+One" + "&bodyParameterOneName=Parameter+One+Value+Two" + "&bodyParameterTwoName=Parameter+Two")) .withHeaders(header("headerNameRequest", "headerValueRequest")) .withCookies(cookie("cookieNameRequest", "cookieValueRequest")), headersToIgnore) ); } @Test public void shouldNotReturnResponseForNonMatchingBodyParameterValue() { // when mockServerClient .when( request() .withMethod("POST") .withPath(calculatePath("some_pathRequest")) .withBody(params( param("bodyParameterOneName", "Parameter One Value One", "Parameter One Value Two"), param("bodyParameterTwoName", "Parameter Two") )) ) .respond( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withReasonPhrase(HttpStatusCode.ACCEPTED_202.reasonPhrase()) .withBody("some_body_response") .withHeaders(header("headerNameResponse", "headerValueResponse")) .withCookies(cookie("cookieNameResponse", "cookieValueResponse")) ); // then // wrong body parameter value assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()) .withReasonPhrase(HttpStatusCode.NOT_FOUND_404.reasonPhrase()), makeRequest( request() .withMethod("POST") .withPath(calculatePath("some_pathRequest")) .withBody(params( param("bodyParameterOneName", "Other Parameter One Value One", "Parameter One Value Two"), param("bodyParameterTwoName", "Parameter Two") )) .withHeaders(header("headerNameRequest", "headerValueRequest")) .withCookies(cookie("cookieNameRequest", "cookieValueRequest")), headersToIgnore) ); // wrong body parameter value assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()) .withReasonPhrase(HttpStatusCode.NOT_FOUND_404.reasonPhrase()), makeRequest( request() .withMethod("POST") .withPath(calculatePath("some_pathRequest")) .withBody(new StringBody("bodyParameterOneName=Other Parameter+One+Value+One" + "&bodyParameterOneName=Parameter+One+Value+Two" + "&bodyParameterTwoName=Parameter+Two")) .withHeaders(header("headerNameRequest", "headerValueRequest")) .withCookies(cookie("cookieNameRequest", "cookieValueRequest")), headersToIgnore) ); } @Test public void shouldNotReturnResponseForNonMatchingQueryStringParameterName() { // when mockServerClient .when( request() .withMethod("POST") .withPath(calculatePath("some_pathRequest")) .withQueryStringParameters( param("queryStringParameterOneName", "queryStringParameterOneValueOne", "queryStringParameterOneValueTwo"), param("queryStringParameterTwoName", "queryStringParameterTwoValue") ) .withBody("some_bodyRequest") ) .respond( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withReasonPhrase(HttpStatusCode.ACCEPTED_202.reasonPhrase()) .withBody("some_body_response") .withHeaders(header("headerNameResponse", "headerValueResponse")) .withCookies(cookie("cookieNameResponse", "cookieValueResponse")) ); // then // wrong query string parameter name assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()) .withReasonPhrase(HttpStatusCode.NOT_FOUND_404.reasonPhrase()), makeRequest( request() .withMethod("POST") .withPath(calculatePath("some_pathRequest")) .withQueryStringParameters( param("OTHERQueryStringParameterOneName", "queryStringParameterOneValueOne", "queryStringParameterOneValueTwo"), param("queryStringParameterTwoName", "queryStringParameterTwoValue") ) .withBody("some_bodyRequest") .withHeaders( header("headerNameRequest", "headerValueRequest") ) .withCookies(cookie("cookieNameRequest", "cookieValueRequest")), headersToIgnore) ); } @Test public void shouldNotReturnResponseForNonMatchingQueryStringParameterValue() { // when mockServerClient .when( request() .withMethod("POST") .withPath(calculatePath("some_pathRequest")) .withQueryStringParameters( param("queryStringParameterOneName", "queryStringParameterOneValueOne", "queryStringParameterOneValueTwo"), param("queryStringParameterTwoName", "queryStringParameterTwoValue") ) .withBody("some_bodyRequest") ) .respond( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withReasonPhrase(HttpStatusCode.ACCEPTED_202.reasonPhrase()) .withBody("some_body_response") .withHeaders(header("headerNameResponse", "headerValueResponse")) .withCookies(cookie("cookieNameResponse", "cookieValueResponse")) ); // then // wrong query string parameter value assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()) .withReasonPhrase(HttpStatusCode.NOT_FOUND_404.reasonPhrase()), makeRequest( request() .withMethod("POST") .withPath(calculatePath("some_pathRequest")) .withQueryStringParameters( param("queryStringParameterOneName", "OTHERqueryStringParameterOneValueOne", "queryStringParameterOneValueTwo"), param("queryStringParameterTwoName", "queryStringParameterTwoValue") ) .withBody("some_bodyRequest") .withHeaders(header("headerNameRequest", "headerValueRequest")) .withCookies(cookie("cookieNameRequest", "cookieValueRequest")), headersToIgnore) ); } @Test public void shouldNotReturnResponseForMatchingQueryStringParameterWithNotOperator() { // when mockServerClient .when( request() .withMethod("POST") .withPath(calculatePath("some_pathRequest")) .withQueryStringParameters( param(not("queryStringParameterOneName"), not("Parameter One Value One"), not("Parameter One Value Two")), param("queryStringParameterTwoName", "Parameter Two") ) ) .respond( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withReasonPhrase(HttpStatusCode.ACCEPTED_202.reasonPhrase()) .withBody("some_body_response") ); // then // wrong query string parameter name assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()) .withReasonPhrase(HttpStatusCode.NOT_FOUND_404.reasonPhrase()), makeRequest( request() .withMethod("POST") .withPath(calculatePath("some_pathRequest")) .withQueryStringParameters( param("queryStringParameterOneName", "Parameter One Value One", "Parameter One Value Two"), param("queryStringParameterTwoName", "Parameter Two") ), headersToIgnore) ); // wrong query string parameter name assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()) .withReasonPhrase(HttpStatusCode.NOT_FOUND_404.reasonPhrase()), makeRequest( request() .withMethod("POST") .withPath(calculatePath("some_pathRequest")) .withQueryStringParameters( param("queryStringParameterOneName", "Parameter One Value One", "Parameter One Value Two"), param("queryStringParameterTwoName", "Parameter Two") ), headersToIgnore) ); } @Test public void shouldNotReturnResponseForNonMatchingCookieName() { // when mockServerClient .when( request() .withMethod("GET") .withPath(calculatePath("some_path")) .withQueryStringParameters( param("queryStringParameterOneName", "queryStringParameterOneValue"), param("queryStringParameterTwoName", "queryStringParameterTwoValue") ) .withBody(exact("some_body")) .withHeaders(header("headerName", "headerValue")) .withCookies(cookie("cookieName", "cookieValue")) ) .respond( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withReasonPhrase(HttpStatusCode.ACCEPTED_202.reasonPhrase()) .withBody("some_body") .withHeaders(header("headerName", "headerValue")) .withCookies(cookie("cookieName", "cookieValue")) ); // then // - in http assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()) .withReasonPhrase(HttpStatusCode.NOT_FOUND_404.reasonPhrase()), makeRequest( request() .withMethod("GET") .withPath(calculatePath("some_path")) .withQueryStringParameters( param("queryStringParameterOneName", "queryStringParameterOneValue"), param("queryStringParameterTwoName", "queryStringParameterTwoValue") ) .withBody(exact("some_body")) .withHeaders(header("headerName", "headerValue")) .withCookies(cookie("cookieOtherName", "cookieValue")), headersToIgnore) ); // - in https assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()) .withReasonPhrase(HttpStatusCode.NOT_FOUND_404.reasonPhrase()), makeRequest( request() .withMethod("GET") .withSecure(true) .withPath(calculatePath("some_path")) .withQueryStringParameters( param("queryStringParameterOneName", "queryStringParameterOneValue"), param("queryStringParameterTwoName", "queryStringParameterTwoValue") ) .withBody(exact("some_body")) .withHeaders(header("headerName", "headerValue")) .withCookies(cookie("cookieOtherName", "cookieValue")), headersToIgnore) ); } @Test public void shouldNotReturnResponseForNonMatchingCookieValue() { // when mockServerClient .when( request() .withMethod("GET") .withPath(calculatePath("some_path")) .withQueryStringParameters( param("queryStringParameterOneName", "queryStringParameterOneValue"), param("queryStringParameterTwoName", "queryStringParameterTwoValue") ) .withBody(exact("some_body")) .withHeaders(header("headerName", "headerValue")) .withCookies(cookie("cookieName", "cookieValue")) ) .respond( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withReasonPhrase(HttpStatusCode.ACCEPTED_202.reasonPhrase()) .withBody("some_body") .withHeaders(header("headerName", "headerValue")) .withCookies(cookie("cookieName", "cookieValue")) ); // then // - in http assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()) .withReasonPhrase(HttpStatusCode.NOT_FOUND_404.reasonPhrase()), makeRequest( request() .withMethod("GET") .withPath(calculatePath("some_path")) .withQueryStringParameters( param("queryStringParameterOneName", "queryStringParameterOneValue"), param("queryStringParameterTwoName", "queryStringParameterTwoValue") ) .withBody(exact("some_body")) .withHeaders(header("headerName", "headerValue")) .withCookies(cookie("cookieName", "cookieOtherValue")), headersToIgnore) ); // - in https assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()) .withReasonPhrase(HttpStatusCode.NOT_FOUND_404.reasonPhrase()), makeRequest( request() .withMethod("GET") .withSecure(true) .withPath(calculatePath("some_path")) .withQueryStringParameters( param("queryStringParameterOneName", "queryStringParameterOneValue"), param("queryStringParameterTwoName", "queryStringParameterTwoValue") ) .withBody(exact("some_body")) .withHeaders(header("headerName", "headerValue")) .withCookies(cookie("cookieName", "cookieOtherValue")), headersToIgnore) ); } @Test public void shouldNotReturnResponseForMatchingCookieWithNotOperator() { // when mockServerClient .when( request() .withMethod("GET") .withPath(calculatePath("some_pathRequest")) .withCookies( cookie(not("requestCookieNameOne"), not("requestCookieValueOne")), cookie("requestCookieNameTwo", "requestCookieValueTwo") ) ) .respond( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withReasonPhrase(HttpStatusCode.ACCEPTED_202.reasonPhrase()) .withBody("some_body_response") ); // then // wrong query string parameter name assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()) .withReasonPhrase(HttpStatusCode.NOT_FOUND_404.reasonPhrase()), makeRequest( request() .withMethod("GET") .withPath(calculatePath("some_pathRequest")) .withCookies( cookie("requestCookieNameOne", "requestCookieValueOne"), cookie("requestCookieNameTwo", "requestCookieValueTwo") ), headersToIgnore) ); // wrong query string parameter name assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()) .withReasonPhrase(HttpStatusCode.NOT_FOUND_404.reasonPhrase()), makeRequest( request() .withMethod("GET") .withPath(calculatePath("some_pathRequest")) .withCookies( cookie("requestCookieNameOne", "requestCookieValueOne"), cookie("requestCookieNameTwo", "requestCookieValueTwo") ), headersToIgnore) ); } @Test public void shouldNotReturnResponseForNonMatchingHeaderName() { // when mockServerClient .when( request() .withMethod("GET") .withPath(calculatePath("some_path")) .withQueryStringParameters( param("queryStringParameterOneName", "queryStringParameterOneValue"), param("queryStringParameterTwoName", "queryStringParameterTwoValue") ) .withBody(exact("some_body")) .withHeaders(header("headerName", "headerValue")) .withCookies(cookie("cookieName", "cookieValue")) ) .respond( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withReasonPhrase(HttpStatusCode.ACCEPTED_202.reasonPhrase()) .withBody("some_body") .withHeaders(header("headerName", "headerValue")) .withCookies(cookie("cookieName", "cookieValue")) ); // then // - in http assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()) .withReasonPhrase(HttpStatusCode.NOT_FOUND_404.reasonPhrase()), makeRequest( request() .withMethod("GET") .withPath(calculatePath("some_path")) .withQueryStringParameters( param("queryStringParameterOneName", "queryStringParameterOneValue"), param("queryStringParameterTwoName", "queryStringParameterTwoValue") ) .withBody(exact("some_body")) .withHeaders(header("headerOtherName", "headerValue")) .withCookies(cookie("cookieName", "cookieValue")), headersToIgnore) ); // - in https assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()) .withReasonPhrase(HttpStatusCode.NOT_FOUND_404.reasonPhrase()), makeRequest( request() .withMethod("GET") .withSecure(true) .withPath(calculatePath("some_path")) .withQueryStringParameters( param("queryStringParameterOneName", "queryStringParameterOneValue"), param("queryStringParameterTwoName", "queryStringParameterTwoValue") ) .withBody(exact("some_body")) .withHeaders(header("headerOtherName", "headerValue")) .withCookies(cookie("cookieName", "cookieValue")), headersToIgnore) ); } @Test public void shouldNotReturnResponseForNonMatchingHeaderValue() { // when mockServerClient .when( request() .withMethod("GET") .withPath(calculatePath("some_path")) .withQueryStringParameters( param("queryStringParameterOneName", "queryStringParameterOneValue"), param("queryStringParameterTwoName", "queryStringParameterTwoValue") ) .withBody(exact("some_body")) .withHeaders(header("headerName", "headerValue")) .withCookies(cookie("cookieName", "cookieValue")) ) .respond( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withReasonPhrase(HttpStatusCode.ACCEPTED_202.reasonPhrase()) .withBody("some_body") .withHeaders(header("headerName", "headerValue")) .withCookies(cookie("cookieName", "cookieValue")) ); // then // - in http assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()) .withReasonPhrase(HttpStatusCode.NOT_FOUND_404.reasonPhrase()), makeRequest( request() .withMethod("GET") .withPath(calculatePath("some_path")) .withQueryStringParameters( param("queryStringParameterOneName", "queryStringParameterOneValue"), param("queryStringParameterTwoName", "queryStringParameterTwoValue") ) .withBody(exact("some_body")) .withHeaders(header("headerName", "headerOtherValue")) .withCookies(cookie("cookieName", "cookieValue")), headersToIgnore) ); // - in https assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()) .withReasonPhrase(HttpStatusCode.NOT_FOUND_404.reasonPhrase()), makeRequest( request() .withMethod("GET") .withSecure(true) .withPath(calculatePath("some_path")) .withQueryStringParameters( param("queryStringParameterOneName", "queryStringParameterOneValue"), param("queryStringParameterTwoName", "queryStringParameterTwoValue") ) .withBody(exact("some_body")) .withHeaders(header("headerName", "headerOtherValue")) .withCookies(cookie("cookieName", "cookieValue")), headersToIgnore) ); } @Test public void shouldNotReturnResponseForMatchingHeaderWithNotOperator() { // when mockServerClient .when( request() .withMethod("GET") .withPath(calculatePath("some_pathRequest")) .withHeaders( header(not("requestHeaderNameOne"), not("requestHeaderValueOne")), header("requestHeaderNameTwo", "requestHeaderValueTwo") ) ) .respond( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withReasonPhrase(HttpStatusCode.ACCEPTED_202.reasonPhrase()) .withBody("some_body_response") ); // then // wrong query string parameter name assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()) .withReasonPhrase(HttpStatusCode.NOT_FOUND_404.reasonPhrase()), makeRequest( request() .withMethod("GET") .withPath(calculatePath("some_pathRequest")) .withHeaders( header("requestHeaderNameOne", "requestHeaderValueOne"), header("requestHeaderNameTwo", "requestHeaderValueTwo") ), headersToIgnore) ); // wrong query string parameter name assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()) .withReasonPhrase(HttpStatusCode.NOT_FOUND_404.reasonPhrase()), makeRequest( request() .withMethod("GET") .withPath(calculatePath("some_pathRequest")) .withHeaders( header("requestHeaderNameOne", "requestHeaderValueOne"), header("requestHeaderNameTwo", "requestHeaderValueTwo") ), headersToIgnore) ); } @Test public void shouldVerifyReceivedRequestInSsl() { // when mockServerClient .when( request() .withPath(calculatePath("some.*path")), exactly(2) ) .respond( response() .withBody("some_body") ); // then // - in http assertEquals( response() .withStatusCode(OK_200.code()) .withReasonPhrase(OK_200.reasonPhrase()) .withBody("some_body"), makeRequest( request() .withPath(calculatePath("some_path")), headersToIgnore) ); mockServerClient.verify(request() .withPath(calculatePath("some_path")) .withSecure(false)); mockServerClient.verify(request() .withPath(calculatePath("some_path")) .withSecure(false), VerificationTimes.exactly(1)); // - in https assertEquals( response() .withStatusCode(OK_200.code()) .withReasonPhrase(OK_200.reasonPhrase()) .withBody("some_body"), makeRequest( request() .withPath(calculatePath("some_secure_path")) .withSecure(true), headersToIgnore) ); mockServerClient.verify(request() .withPath(calculatePath("some_secure_path")) .withSecure(true)); mockServerClient.verify(request() .withPath(calculatePath("some_secure_path")) .withSecure(true), VerificationTimes.exactly(1)); } @Test public void shouldVerifyReceivedRequestsWithRegexBody() { // when mockServerClient .when( request() .withMethod("POST") .withPath(calculatePath("some_path")) .withBody("{type: 'some_random_type', value: 'some_random_value'}"), exactly(2) ) .respond( response() .withBody("some_response") ); // then // - in http assertEquals( response() .withStatusCode(OK_200.code()) .withReasonPhrase(OK_200.reasonPhrase()) .withBody("some_response"), makeRequest( request() .withMethod("POST") .withPath(calculatePath("some_path")) .withBody("{type: 'some_random_type', value: 'some_random_value'}"), headersToIgnore) ); mockServerClient.verify( request() .withBody(regex("\\{type\\: \\'some_random_type\\'\\, value\\: \\'some_random_value\\'\\}")) ); mockServerClient.verify( request() .withBody(regex("\\{type\\: \\'some_random_type\\'\\, value\\: \\'some_random_value\\'\\}")), VerificationTimes.exactly(1) ); // - in https assertEquals( response() .withStatusCode(OK_200.code()) .withReasonPhrase(OK_200.reasonPhrase()) .withBody("some_response"), makeRequest( request() .withSecure(true) .withMethod("POST") .withPath(calculatePath("some_path")) .withBody("{type: 'some_random_type', value: 'some_random_value'}"), headersToIgnore) ); mockServerClient.verify( request() .withSecure(true) .withBody(regex("\\{type\\: \\'some_random_type\\'\\, value\\: \\'some_random_value\\'\\}")) ); mockServerClient.verify( request() .withSecure(true) .withBody(regex("\\{type\\: \\'some_random_type\\'\\, value\\: \\'some_random_value\\'\\}")), VerificationTimes.atLeast(1) ); } @Test public void shouldVerifyReceivedRequestsWithNoBody() { // when mockServerClient.when(request().withPath(calculatePath("some_path")), exactly(2)).respond(response()); // then // - in http assertEquals( response() .withStatusCode(OK_200.code()) .withReasonPhrase(OK_200.reasonPhrase()), makeRequest( request() .withPath(calculatePath("some_path")), headersToIgnore) ); mockServerClient.verify(request() .withPath(calculatePath("some_path"))); mockServerClient.verify(request() .withPath(calculatePath("some_path")), VerificationTimes.exactly(1)); } @Test public void shouldVerifyTooManyRequestsReceived() { // when mockServerClient.when(request().withPath(calculatePath("some_path")), exactly(2)).respond(response().withBody("some_body")); // then assertEquals( response() .withStatusCode(OK_200.code()) .withReasonPhrase(OK_200.reasonPhrase()) .withBody("some_body"), makeRequest( request() .withPath(calculatePath("some_path")), headersToIgnore) ); try { mockServerClient.verify(request() .withPath(calculatePath("some_path")), VerificationTimes.exactly(0)); fail(); } catch (AssertionError ae) { assertThat(ae.getMessage(), startsWith("Request not found exactly 0 times, expected:<{" + NEW_LINE + " \"path\" : \"" + calculatePath("some_path") + "\"" + NEW_LINE + "}> but was:<{" + NEW_LINE + " \"method\" : \"GET\"," + NEW_LINE + " \"path\" : \"" + calculatePath("some_path") + "\"," + NEW_LINE)); } } @Test public void shouldVerifyNoMatchingRequestsReceived() { // when mockServerClient.when(request().withPath(calculatePath("some_path")), exactly(2)).respond(response().withBody("some_body")); // then assertEquals( response() .withStatusCode(OK_200.code()) .withReasonPhrase(OK_200.reasonPhrase()) .withBody("some_body"), makeRequest( request() .withPath(calculatePath("some_path")), headersToIgnore) ); try { mockServerClient.verify(request() .withPath(calculatePath("some_other_path")), VerificationTimes.exactly(2)); fail(); } catch (AssertionError ae) { assertThat(ae.getMessage(), startsWith("Request not found exactly 2 times, expected:<{" + NEW_LINE + " \"path\" : \"" + calculatePath("some_other_path") + "\"" + NEW_LINE + "}> but was:<{" + NEW_LINE + " \"method\" : \"GET\"," + NEW_LINE + " \"path\" : \"" + calculatePath("some_path") + "\"," + NEW_LINE)); } } @Test public void shouldNotVerifyNoRequestsReceived() { // when mockServerClient.when(request().withPath(calculatePath("some_path")), exactly(2)).respond(response().withBody("some_body")); // then assertEquals( response() .withStatusCode(OK_200.code()) .withReasonPhrase(OK_200.reasonPhrase()) .withBody("some_body"), makeRequest( request() .withPath(calculatePath("some_path")), headersToIgnore) ); try { mockServerClient.verifyZeroInteractions(); fail(); } catch (AssertionError ae) { assertThat(ae.getMessage(), startsWith("Request not found exactly 0 times, expected:<{ }> but was:<{" + NEW_LINE + " \"method\" : \"GET\"," + NEW_LINE + " \"path\" : \"" + calculatePath("some_path") + "\"," + NEW_LINE)); } } @Test public void shouldVerifyNoMatchingRequestsReceivedInSsl() { // when mockServerClient.when(request().withPath(calculatePath("some.*path")), exactly(2)).respond(response().withBody("some_body")); // then // - in http assertEquals( response() .withStatusCode(OK_200.code()) .withReasonPhrase(OK_200.reasonPhrase()) .withBody("some_body"), makeRequest( request() .withPath(calculatePath("some_path")), headersToIgnore) ); try { mockServerClient.verify( request() .withPath(calculatePath("some_path")) .withSecure(true), VerificationTimes.atLeast(1) ); fail(); } catch (AssertionError ae) { assertThat(ae.getMessage(), startsWith("Request not found at least once, expected:<{" + NEW_LINE + " \"path\" : \"" + calculatePath("some_path") + "\"," + NEW_LINE + " \"secure\" : true" + NEW_LINE + "}> but was:<{" + NEW_LINE + " \"method\" : \"GET\"," + NEW_LINE + " \"path\" : \"" + calculatePath("some_path") + "\"," + NEW_LINE)); } // - in https assertEquals( response() .withStatusCode(OK_200.code()) .withReasonPhrase(OK_200.reasonPhrase()) .withBody("some_body"), makeRequest( request() .withPath(calculatePath("some_secure_path")) .withSecure(true), headersToIgnore) ); try { mockServerClient.verify( request() .withPath(calculatePath("some_secure_path")) .withSecure(false), VerificationTimes.atLeast(1) ); fail(); } catch (AssertionError ae) { assertThat(ae.getMessage(), startsWith("Request not found at least once, expected:<{" + NEW_LINE + " \"path\" : \"" + calculatePath("some_secure_path") + "\"," + NEW_LINE + " \"secure\" : false" + NEW_LINE + "}> but was:<[ {" + NEW_LINE + " \"method\" : \"GET\"," + NEW_LINE + " \"path\" : \"" + calculatePath("some_path") + "\"," + NEW_LINE)); } } @Test public void shouldVerifySequenceOfRequestsReceivedIncludingThoseNotMatchingAnException() { // when mockServerClient.when(request().withPath(calculatePath("some_path.*")), exactly(4)).respond(response().withBody("some_body")); // then assertEquals( response("some_body"), makeRequest( request().withPath(calculatePath("some_path_one")), headersToIgnore) ); assertEquals( notFoundResponse(), makeRequest( request().withPath(calculatePath("not_found")), headersToIgnore) ); assertEquals( response("some_body"), makeRequest( request().withPath(calculatePath("some_path_three")), headersToIgnore) ); mockServerClient.verify(request(calculatePath("some_path_one")), request(calculatePath("some_path_three"))); mockServerClient.verify(request(calculatePath("some_path_one")), request(calculatePath("not_found"))); mockServerClient.verify(request(calculatePath("some_path_one")), request(calculatePath("not_found")), request(calculatePath("some_path_three"))); mockServerClient.verify(request(calculatePath("some_path_one")), request(calculatePath("not_found")), request(calculatePath("some_path_three"))); } @Test public void shouldVerifySequenceOfRequestsNotReceived() { // when mockServerClient.when(request().withPath(calculatePath("some_path.*")), exactly(6)).respond(response().withBody("some_body")); // then assertEquals( response("some_body"), makeRequest( request().withPath(calculatePath("some_path_one")), headersToIgnore) ); assertEquals( response("some_body"), makeRequest( request().withPath(calculatePath("some_path_two")), headersToIgnore) ); assertEquals( response("some_body"), makeRequest( request().withPath(calculatePath("some_path_three")), headersToIgnore) ); try { mockServerClient.verify(request(calculatePath("some_path_two")), request(calculatePath("some_path_one"))); fail(); } catch (AssertionError ae) { assertThat(ae.getMessage(), startsWith("Request sequence not found, expected:<[ {" + NEW_LINE + " \"path\" : \"" + calculatePath("some_path_two") + "\"" + NEW_LINE + "}, {" + NEW_LINE + " \"path\" : \"" + calculatePath("some_path_one") + "\"" + NEW_LINE + "} ]> but was:<[ {" + NEW_LINE + " \"method\" : \"GET\"," + NEW_LINE + " \"path\" : \"" + calculatePath("some_path_one") + "\"," + NEW_LINE)); } try { mockServerClient.verify(request(calculatePath("some_path_three")), request(calculatePath("some_path_two"))); fail(); } catch (AssertionError ae) { assertThat(ae.getMessage(), startsWith("Request sequence not found, expected:<[ {" + NEW_LINE + " \"path\" : \"" + calculatePath("some_path_three") + "\"" + NEW_LINE + "}, {" + NEW_LINE + " \"path\" : \"" + calculatePath("some_path_two") + "\"" + NEW_LINE + "} ]> but was:<[ {" + NEW_LINE + " \"method\" : \"GET\"," + NEW_LINE + " \"path\" : \"" + calculatePath("some_path_one") + "\"," + NEW_LINE)); } try { mockServerClient.verify(request(calculatePath("some_path_four"))); fail(); } catch (AssertionError ae) { assertThat(ae.getMessage(), startsWith("Request sequence not found, expected:<[ {" + NEW_LINE + " \"path\" : \"" + calculatePath("some_path_four") + "\"" + NEW_LINE + "} ]> but was:<[ {" + NEW_LINE + " \"method\" : \"GET\"," + NEW_LINE + " \"path\" : \"" + calculatePath("some_path_one") + "\"," + NEW_LINE)); } } @Test public void shouldRetrieveRecordedRequestsAsJson() { // when mockServerClient.when(request().withPath(calculatePath("some_path.*")), exactly(4)).respond(response().withBody("some_body")); assertEquals( response("some_body"), makeRequest( request().withPath(calculatePath("some_path_one")), headersToIgnore) ); assertEquals( notFoundResponse(), makeRequest( request().withPath(calculatePath("not_found")), headersToIgnore) ); assertEquals( response("some_body"), makeRequest( request().withPath(calculatePath("some_path_three")), headersToIgnore) ); // then verifyRequestsMatches( new HttpRequestSerializer(new MockServerLogger()).deserializeArray(mockServerClient.retrieveRecordedRequests(request().withPath(calculatePath("some_path.*")), Format.JSON)), request(calculatePath("some_path_one")), request(calculatePath("some_path_three")) ); verifyRequestsMatches( new HttpRequestSerializer(new MockServerLogger()).deserializeArray(mockServerClient.retrieveRecordedRequests(request(), Format.JSON)), request(calculatePath("some_path_one")), request(calculatePath("not_found")), request(calculatePath("some_path_three")) ); verifyRequestsMatches( new HttpRequestSerializer(new MockServerLogger()).deserializeArray(mockServerClient.retrieveRecordedRequests(null, Format.JSON)), request(calculatePath("some_path_one")), request(calculatePath("not_found")), request(calculatePath("some_path_three")) ); } @Test public void shouldRetrieveActiveExpectationsAsJson() { // when mockServerClient.when(request().withPath(calculatePath("some_path.*")), exactly(4)) .respond(response().withBody("some_body")); mockServerClient.when(request().withPath(calculatePath("some_path.*"))) .respond(response().withBody("some_body")); mockServerClient.when(request().withPath(calculatePath("some_other_path"))) .respond(response().withBody("some_other_body")); mockServerClient.when(request().withPath(calculatePath("some_forward_path"))) .forward(forward()); // then assertThat( mockServerClient.retrieveActiveExpectations(request().withPath(calculatePath("some_path.*")), Format.JSON), is(new ExpectationSerializer(new MockServerLogger()).serialize(Arrays.asList( new Expectation(request().withPath(calculatePath("some_path.*")), exactly(4), TimeToLive.unlimited()) .thenRespond(response().withBody("some_body")), new Expectation(request().withPath(calculatePath("some_path.*"))) .thenRespond(response().withBody("some_body")) ))) ); assertThat( mockServerClient.retrieveActiveExpectations(null, Format.JSON), is(new ExpectationSerializer(new MockServerLogger()).serialize(Arrays.asList( new Expectation(request().withPath(calculatePath("some_path.*")), exactly(4), TimeToLive.unlimited()) .thenRespond(response().withBody("some_body")), new Expectation(request().withPath(calculatePath("some_path.*"))) .thenRespond(response().withBody("some_body")), new Expectation(request().withPath(calculatePath("some_other_path"))) .thenRespond(response().withBody("some_other_body")), new Expectation(request().withPath(calculatePath("some_forward_path"))) .thenForward(forward()) ))) ); assertThat( mockServerClient.retrieveActiveExpectations(request(), Format.JSON), is(new ExpectationSerializer(new MockServerLogger()).serialize(Arrays.asList( new Expectation(request().withPath(calculatePath("some_path.*")), exactly(4), TimeToLive.unlimited()) .thenRespond(response().withBody("some_body")), new Expectation(request().withPath(calculatePath("some_path.*"))) .thenRespond(response().withBody("some_body")), new Expectation(request().withPath(calculatePath("some_other_path"))) .thenRespond(response().withBody("some_other_body")), new Expectation(request().withPath(calculatePath("some_forward_path"))) .thenForward(forward()) ))) ); } @Test public void shouldRetrieveActiveExpectationsAsJava() { // when mockServerClient.when(request().withPath(calculatePath("some_path.*")), exactly(4)) .respond(response().withBody("some_body")); mockServerClient.when(request().withPath(calculatePath("some_path.*"))) .respond(response().withBody("some_body")); mockServerClient.when(request().withPath(calculatePath("some_other_path"))) .respond(response().withBody("some_other_body")); mockServerClient.when(request().withPath(calculatePath("some_forward_path"))) .forward(forward()); // then assertThat( mockServerClient.retrieveActiveExpectations(request().withPath(calculatePath("some_path.*")), Format.JAVA), is(new ExpectationToJavaSerializer().serialize(Arrays.asList( new Expectation(request().withPath(calculatePath("some_path.*")), exactly(4), TimeToLive.unlimited()) .thenRespond(response().withBody("some_body")), new Expectation(request().withPath(calculatePath("some_path.*"))) .thenRespond(response().withBody("some_body")) ))) ); assertThat( mockServerClient.retrieveActiveExpectations(null, Format.JAVA), is(new ExpectationToJavaSerializer().serialize(Arrays.asList( new Expectation(request().withPath(calculatePath("some_path.*")), exactly(4), TimeToLive.unlimited()) .thenRespond(response().withBody("some_body")), new Expectation(request().withPath(calculatePath("some_path.*"))) .thenRespond(response().withBody("some_body")), new Expectation(request().withPath(calculatePath("some_other_path"))) .thenRespond(response().withBody("some_other_body")), new Expectation(request().withPath(calculatePath("some_forward_path"))) .thenForward(forward()) ))) ); assertThat( mockServerClient.retrieveActiveExpectations(request(), Format.JAVA), is(new ExpectationToJavaSerializer().serialize(Arrays.asList( new Expectation(request().withPath(calculatePath("some_path.*")), exactly(4), TimeToLive.unlimited()) .thenRespond(response().withBody("some_body")), new Expectation(request().withPath(calculatePath("some_path.*"))) .thenRespond(response().withBody("some_body")), new Expectation(request().withPath(calculatePath("some_other_path"))) .thenRespond(response().withBody("some_other_body")), new Expectation(request().withPath(calculatePath("some_forward_path"))) .thenForward(forward()) ))) ); } @Test public void shouldRetrieveRecordedExpectationsAsJson() { // when EchoServer secureEchoServer = new EchoServer(false); try { mockServerClient.when(request().withPath(calculatePath("some_path.*")), exactly(4)).forward( forward() .withHost("127.0.0.1") .withPort(secureEchoServer.getPort()) ); assertEquals( response("some_body_one"), makeRequest( request().withPath(calculatePath("some_path_one")).withBody("some_body_one"), headersToIgnore ) ); assertEquals( response("some_body_three"), makeRequest( request().withPath(calculatePath("some_path_three")).withBody("some_body_three"), headersToIgnore ) ); // then Expectation[] recordedExpectations = new ExpectationSerializer(new MockServerLogger()).deserializeArray( mockServerClient.retrieveRecordedExpectations(request().withPath(calculatePath("some_path_one")), Format.JSON) ); assertThat(recordedExpectations.length, is(1)); verifyRequestsMatches( new HttpRequest[]{ recordedExpectations[0].getHttpRequest() }, request(calculatePath("some_path_one")).withBody("some_body_one") ); assertThat(recordedExpectations[0].getHttpResponse().getBodyAsString(), is("some_body_one")); // and recordedExpectations = new ExpectationSerializer(new MockServerLogger()).deserializeArray( mockServerClient.retrieveRecordedExpectations(request(), Format.JSON) ); assertThat(recordedExpectations.length, is(2)); verifyRequestsMatches( new HttpRequest[]{ recordedExpectations[0].getHttpRequest(), recordedExpectations[1].getHttpRequest() }, request(calculatePath("some_path_one")).withBody("some_body_one"), request(calculatePath("some_path_three")).withBody("some_body_three") ); assertThat(recordedExpectations[0].getHttpResponse().getBodyAsString(), is("some_body_one")); assertThat(recordedExpectations[1].getHttpResponse().getBodyAsString(), is("some_body_three")); // and recordedExpectations = new ExpectationSerializer(new MockServerLogger()).deserializeArray( mockServerClient.retrieveRecordedExpectations(null, Format.JSON) ); assertThat(recordedExpectations.length, is(2)); verifyRequestsMatches( new HttpRequest[]{ recordedExpectations[0].getHttpRequest(), recordedExpectations[1].getHttpRequest() }, request(calculatePath("some_path_one")).withBody("some_body_one"), request(calculatePath("some_path_three")).withBody("some_body_three") ); assertThat(recordedExpectations[0].getHttpResponse().getBodyAsString(), is("some_body_one")); assertThat(recordedExpectations[1].getHttpResponse().getBodyAsString(), is("some_body_three")); } finally { secureEchoServer.stop(); } } @Test public void shouldClearExpectationsOnly() { // given - some expectations mockServerClient .when( request() .withPath(calculatePath("some_path1")) ) .respond( response() .withBody("some_body1") ); mockServerClient .when( request() .withPath(calculatePath("some_path2")) ) .respond( response() .withBody("some_body2") ); // and - some matching requests assertEquals( response() .withStatusCode(OK_200.code()) .withReasonPhrase(OK_200.reasonPhrase()) .withBody("some_body1"), makeRequest( request() .withPath(calculatePath("some_path1")), headersToIgnore) ); assertEquals( response() .withStatusCode(OK_200.code()) .withReasonPhrase(OK_200.reasonPhrase()) .withBody("some_body2"), makeRequest( request() .withPath(calculatePath("some_path2")), headersToIgnore) ); // when mockServerClient .clear( request() .withPath(calculatePath("some_path1")), ClearType.EXPECTATIONS ); // then - expectations cleared assertThat( mockServerClient.retrieveActiveExpectations(null), arrayContaining( new Expectation(request() .withPath(calculatePath("some_path2"))) .thenRespond( response() .withBody("some_body2") ) ) ); // and then - request log not cleared verifyRequestsMatches( mockServerClient.retrieveRecordedRequests(null), request(calculatePath("some_path1")), request(calculatePath("some_path2")) ); } @Test public void shouldClearLogsOnly() { // given - some expectations mockServerClient .when( request() .withPath(calculatePath("some_path1")) ) .respond( response() .withBody("some_body1") ); mockServerClient .when( request() .withPath(calculatePath("some_path2")) ) .respond( response() .withBody("some_body2") ); // and - some matching requests assertEquals( response() .withStatusCode(OK_200.code()) .withReasonPhrase(OK_200.reasonPhrase()) .withBody("some_body1"), makeRequest( request() .withPath(calculatePath("some_path1")), headersToIgnore) ); assertEquals( response() .withStatusCode(OK_200.code()) .withReasonPhrase(OK_200.reasonPhrase()) .withBody("some_body2"), makeRequest( request() .withPath(calculatePath("some_path2")), headersToIgnore) ); // when mockServerClient .clear( request() .withPath(calculatePath("some_path1")), ClearType.LOG ); // then - expectations cleared assertThat( mockServerClient.retrieveActiveExpectations(null), arrayContaining( new Expectation(request() .withPath(calculatePath("some_path1"))) .thenRespond( response() .withBody("some_body1") ), new Expectation(request() .withPath(calculatePath("some_path2"))) .thenRespond( response() .withBody("some_body2") ) ) ); // and then - request log cleared verifyRequestsMatches( mockServerClient.retrieveRecordedRequests(null), request(calculatePath("some_path2")) ); } @Test public void shouldClearAllExpectationsWithNull() { // given mockServerClient .when( request() .withPath(calculatePath("some_path1")) ) .respond( response() .withBody("some_body1") ); mockServerClient .when( request() .withPath(calculatePath("some_path2")) ) .respond( response() .withBody("some_body2") ); assertEquals( response() .withStatusCode(OK_200.code()) .withReasonPhrase(OK_200.reasonPhrase()) .withBody("some_body2"), makeRequest( request() .withPath(calculatePath("some_path2")), headersToIgnore) ); // when mockServerClient.clear(null); // then assertThat(mockServerClient.retrieveActiveExpectations(null), emptyArray()); assertThat(mockServerClient.retrieveRecordedRequests(null), emptyArray()); } @Test public void shouldClearAllExpectationsWithEmptyRequest() { // given mockServerClient .when( request() .withPath(calculatePath("some_path1")) ) .respond( response() .withBody("some_body1") ); mockServerClient .when( request() .withPath(calculatePath("some_path2")) ) .respond( response() .withBody("some_body2") ); assertEquals( response() .withStatusCode(OK_200.code()) .withReasonPhrase(OK_200.reasonPhrase()) .withBody("some_body2"), makeRequest( request() .withPath(calculatePath("some_path2")), headersToIgnore) ); // when mockServerClient.clear(request()); // then assertThat(mockServerClient.retrieveActiveExpectations(null), emptyArray()); assertThat(mockServerClient.retrieveRecordedRequests(null), emptyArray()); } @Test public void shouldClearExpectationsWithXPathBody() { // given mockServerClient .when( request() .withBody(xpath("/bookstore/book[year=2005]/price")) ) .respond( response() .withBody("some_body1") ); mockServerClient .when( request() .withBody(xpath("/bookstore/book[year=2006]/price")) ) .respond( response() .withBody("some_body2") ); // and StringBody xmlBody = new StringBody("" + "<?xml version=\"1.0\" encoding=\"ISO-8859-1\"?>" + NEW_LINE + "<bookstore>" + NEW_LINE + " <book category=\"COOKING\">" + NEW_LINE + " <title lang=\"en\">Everyday Italian</title>" + NEW_LINE + " <author>Giada De Laurentiis</author>" + NEW_LINE + " <year>2005</year>" + NEW_LINE + " <price>30.00</price>" + NEW_LINE + " </book>" + NEW_LINE + " <book category=\"CHILDREN\">" + NEW_LINE + " <title lang=\"en\">Harry Potter</title>" + NEW_LINE + " <author>J K. Rowling</author>" + NEW_LINE + " <year>2006</year>" + NEW_LINE + " <price>29.99</price>" + NEW_LINE + " </book>" + NEW_LINE + " <book category=\"WEB\">" + NEW_LINE + " <title lang=\"en\">Learning XML</title>" + NEW_LINE + " <author>Erik T. Ray</author>" + NEW_LINE + " <year>2003</year>" + NEW_LINE + " <price>31.95</price>" + NEW_LINE + " </book>" + NEW_LINE + "</bookstore>"); // then assertEquals( response() .withStatusCode(OK_200.code()) .withReasonPhrase(OK_200.reasonPhrase()) .withBody("some_body1"), makeRequest( request() .withBody(xmlBody), headersToIgnore) ); // when mockServerClient .clear( request() .withBody(xpath("/bookstore/book[year=2005]/price")) ); // then assertThat( mockServerClient.retrieveActiveExpectations(null), arrayContaining( new Expectation(request() .withBody(xpath("/bookstore/book[year=2006]/price"))) .thenRespond( response() .withBody("some_body2") ) ) ); // - in http assertEquals( response() .withStatusCode(OK_200.code()) .withReasonPhrase(OK_200.reasonPhrase()) .withBody("some_body2"), makeRequest( request() .withBody(xmlBody), headersToIgnore) ); // - in https assertEquals( response() .withStatusCode(OK_200.code()) .withReasonPhrase(OK_200.reasonPhrase()) .withBody("some_body2"), makeRequest( request() .withSecure(true) .withBody(xmlBody), headersToIgnore) ); } @Test public void shouldClearExpectationsWithJsonSchemaBody() { // given JsonSchemaBody jsonSchemaBodyOne = jsonSchema("{" + NEW_LINE + " \"$schema\": \"http://json-schema.org/draft-04/schema#\"," + NEW_LINE + " \"title\": \"Product\"," + NEW_LINE + " \"description\": \"A product from Acme's catalog\"," + NEW_LINE + " \"type\": \"object\"," + NEW_LINE + " \"properties\": {" + NEW_LINE + " \"id\": {" + NEW_LINE + " \"description\": \"The unique identifier for a product\"," + NEW_LINE + " \"type\": \"integer\"" + NEW_LINE + " }," + NEW_LINE + " \"name\": {" + NEW_LINE + " \"description\": \"Name of the product\"," + NEW_LINE + " \"type\": \"string\"" + NEW_LINE + " }," + NEW_LINE + " \"price\": {" + NEW_LINE + " \"type\": \"number\"," + NEW_LINE + " \"minimum\": 0," + NEW_LINE + " \"exclusiveMinimum\": true" + NEW_LINE + " }," + NEW_LINE + " \"tags\": {" + NEW_LINE + " \"type\": \"array\"," + NEW_LINE + " \"items\": {" + NEW_LINE + " \"type\": \"string\"" + NEW_LINE + " }," + NEW_LINE + " \"minItems\": 1," + NEW_LINE + " \"uniqueItems\": true" + NEW_LINE + " }" + NEW_LINE + " }," + NEW_LINE + " \"required\": [\"id\", \"name\", \"price\"]" + NEW_LINE + "}"); JsonSchemaBody jsonSchemaBodyTwo = jsonSchema("{" + NEW_LINE + " \"$schema\": \"http://json-schema.org/draft-04/schema#\"," + NEW_LINE + " \"title\": \"Product\"," + NEW_LINE + " \"description\": \"A product from Acme's catalog\"," + NEW_LINE + " \"type\": \"object\"," + NEW_LINE + " \"properties\": {" + NEW_LINE + " \"id\": {" + NEW_LINE + " \"description\": \"The unique identifier for a product\"," + NEW_LINE + " \"type\": \"integer\"" + NEW_LINE + " }," + NEW_LINE + " \"name\": {" + NEW_LINE + " \"description\": \"Name of the product\"," + NEW_LINE + " \"type\": \"string\"" + NEW_LINE + " }," + NEW_LINE + " \"price\": {" + NEW_LINE + " \"type\": \"number\"," + NEW_LINE + " \"minimum\": 10," + NEW_LINE + " \"exclusiveMinimum\": true" + NEW_LINE + " }," + NEW_LINE + " \"tags\": {" + NEW_LINE + " \"type\": \"array\"," + NEW_LINE + " \"items\": {" + NEW_LINE + " \"type\": \"string\"" + NEW_LINE + " }," + NEW_LINE + " \"minItems\": 1," + NEW_LINE + " \"uniqueItems\": true" + NEW_LINE + " }" + NEW_LINE + " }," + NEW_LINE + " \"required\": [\"id\", \"name\", \"price\"]" + NEW_LINE + "}"); mockServerClient .when( request() .withBody(jsonSchemaBodyOne) ) .respond( response() .withBody("some_body1") ); mockServerClient .when( request() .withBody(jsonSchemaBodyTwo) ) .respond( response() .withBody("some_body2") ); // then assertEquals( response() .withStatusCode(OK_200.code()) .withReasonPhrase(OK_200.reasonPhrase()) .withBody("some_body1"), makeRequest( request() .withBody("{" + NEW_LINE + " \"id\": 1," + NEW_LINE + " \"name\": \"A green door\"," + NEW_LINE + " \"price\": 12.50," + NEW_LINE + " \"tags\": [\"home\", \"green\"]" + NEW_LINE + "}"), headersToIgnore) ); // when mockServerClient .clear( request() .withBody(jsonSchemaBodyOne) ); // then assertThat( mockServerClient.retrieveActiveExpectations(null), arrayContaining( new Expectation(request() .withBody(jsonSchemaBodyTwo)) .thenRespond( response() .withBody("some_body2") ) ) ); // - in http assertEquals( response() .withStatusCode(OK_200.code()) .withReasonPhrase(OK_200.reasonPhrase()) .withBody("some_body2"), makeRequest( request() .withBody("{" + NEW_LINE + " \"id\": 1," + NEW_LINE + " \"name\": \"A green door\"," + NEW_LINE + " \"price\": 12.50," + NEW_LINE + " \"tags\": [\"home\", \"green\"]" + NEW_LINE + "}"), headersToIgnore) ); // - in https assertEquals( response() .withStatusCode(OK_200.code()) .withReasonPhrase(OK_200.reasonPhrase()) .withBody("some_body2"), makeRequest( request() .withSecure(true) .withBody("{" + NEW_LINE + " \"id\": 1," + NEW_LINE + " \"name\": \"A green door\"," + NEW_LINE + " \"price\": 12.50," + NEW_LINE + " \"tags\": [\"home\", \"green\"]" + NEW_LINE + "}"), headersToIgnore) ); } @Test public void shouldClearExpectationsWithParameterBody() { // given mockServerClient .when( request() .withBody(params(param("bodyParameterNameOne", "bodyParameterValueOne"))) ) .respond( response() .withBody("some_body1") ); mockServerClient .when( request() .withBody(params(param("bodyParameterNameTwo", "bodyParameterValueTwo"))) ) .respond( response() .withBody("some_body2") ); // then assertEquals( response() .withStatusCode(OK_200.code()) .withReasonPhrase(OK_200.reasonPhrase()) .withBody("some_body1"), makeRequest( request() .withBody(params(param("bodyParameterName.*", "bodyParameterValue.*"))), headersToIgnore) ); // when mockServerClient .clear( request() .withBody(params(param("bodyParameterNameOne", "bodyParameterValueOne"))) ); // then assertThat( mockServerClient.retrieveActiveExpectations(null), arrayContaining( new Expectation(request() .withBody(params(param("bodyParameterNameTwo", "bodyParameterValueTwo")))) .thenRespond( response() .withBody("some_body2") ) ) ); // - in http assertEquals( response() .withStatusCode(OK_200.code()) .withReasonPhrase(OK_200.reasonPhrase()) .withBody("some_body2"), makeRequest( request() .withBody(params(param("bodyParameterName.*", "bodyParameterValue.*"))), headersToIgnore) ); // - in https assertEquals( response() .withStatusCode(OK_200.code()) .withReasonPhrase(OK_200.reasonPhrase()) .withBody("some_body2"), makeRequest( request() .withSecure(true) .withBody(params(param("bodyParameterName.*", "bodyParameterValue.*"))), headersToIgnore) ); } @Test public void shouldEnsureThatInterruptedRequestsAreVerifiable() throws Exception { mockServerClient .when( request(calculatePath("delayed")) ) .respond( response("delayed data") .withDelay(new Delay(TimeUnit.SECONDS, 3)) ); Future<HttpResponse> delayedFuture = Executors.newSingleThreadExecutor().submit(new Callable<HttpResponse>() { @Override public HttpResponse call() throws Exception { return httpClient.sendRequest( request(addContextToPath(calculatePath("delayed"))) .withHeader(HOST.toString(), "localhost:" + getServerPort()) ).get(10, TimeUnit.SECONDS); } }); Uninterruptibles.sleepUninterruptibly(1, TimeUnit.SECONDS); // Let request reach server delayedFuture.cancel(true); // Then interrupt requesting thread mockServerClient.verify(request(calculatePath("delayed"))); // We should be able to verify request that reached server even though its later interrupted } @Test public void shouldEnsureThatRequestDelaysDoNotAffectOtherRequests() throws Exception { mockServerClient .when( request("/slow") ) .respond( response("super slow") .withDelay(new Delay(TimeUnit.SECONDS, 5)) ); mockServerClient .when( request("/fast") ) .respond( response("quite fast") ); ExecutorService executorService = Executors.newFixedThreadPool(2); Future<Long> slowFuture = executorService.submit(new Callable<Long>() { @Override public Long call() throws Exception { long start = System.currentTimeMillis(); makeRequest(request("/slow"), Collections.<String>emptySet()); return System.currentTimeMillis() - start; } }); // Let fast request come to the server slightly after slow request Uninterruptibles.sleepUninterruptibly(1, TimeUnit.SECONDS); Future<Long> fastFuture = executorService.submit(new Callable<Long>() { @Override public Long call() throws Exception { long start = System.currentTimeMillis(); makeRequest(request("/fast"), Collections.<String>emptySet()); return System.currentTimeMillis() - start; } }); Long slowRequestElapsedMillis = slowFuture.get(); Long fastRequestElapsedMillis = fastFuture.get(); assertThat("Slow request takes less than expected", slowRequestElapsedMillis, is(greaterThan(5 * 1000L))); assertThat("Fast request takes longer than expected", fastRequestElapsedMillis, is(lessThan(5 * 1000L))); } }
wushian/mockserver
mockserver-integration-testing/src/main/java/org/mockserver/integration/server/AbstractExtendedMockingIntegrationTest.java
935
package org.mockserver.integration.server; import com.fasterxml.jackson.databind.ObjectMapper; import com.google.common.net.MediaType; import com.google.common.util.concurrent.Uninterruptibles; import io.netty.util.CharsetUtil; import org.apache.commons.io.IOUtils; import org.junit.Test; import org.mockserver.logging.MockServerLogger; import org.mockserver.matchers.MatchType; import org.mockserver.matchers.TimeToLive; import org.mockserver.mock.Expectation; import org.mockserver.model.*; import org.mockserver.serialization.ExpectationSerializer; import org.mockserver.serialization.HttpRequestSerializer; import org.mockserver.serialization.JsonArraySerializer; import org.mockserver.serialization.ObjectMapperFactory; import org.mockserver.serialization.java.ExpectationToJavaSerializer; import org.mockserver.verify.VerificationTimes; import java.io.IOException; import java.nio.charset.StandardCharsets; import java.util.*; import java.util.concurrent.*; import static io.netty.handler.codec.http.HttpHeaderNames.*; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.*; import static org.hamcrest.core.Is.is; import static org.hamcrest.core.StringStartsWith.startsWith; import static org.hamcrest.number.OrderingComparison.greaterThan; import static org.junit.Assert.assertEquals; import static org.junit.Assert.fail; import static org.mockserver.character.Character.NEW_LINE; import static org.mockserver.matchers.Times.exactly; import static org.mockserver.model.BinaryBody.binary; import static org.mockserver.model.Cookie.cookie; import static org.mockserver.model.Header.header; import static org.mockserver.model.HttpForward.forward; import static org.mockserver.model.HttpRequest.request; import static org.mockserver.model.HttpResponse.notFoundResponse; import static org.mockserver.model.HttpResponse.response; import static org.mockserver.model.HttpStatusCode.NOT_FOUND_404; import static org.mockserver.model.HttpStatusCode.OK_200; import static org.mockserver.model.JsonBody.json; import static org.mockserver.model.JsonPathBody.jsonPath; import static org.mockserver.model.JsonSchemaBody.jsonSchema; import static org.mockserver.model.NottableString.not; import static org.mockserver.model.NottableString.string; import static org.mockserver.model.Parameter.param; import static org.mockserver.model.ParameterBody.params; import static org.mockserver.model.RegexBody.regex; import static org.mockserver.model.StringBody.exact; import static org.mockserver.model.StringBody.subString; import static org.mockserver.model.XPathBody.xpath; import static org.mockserver.model.XmlBody.xml; import static org.mockserver.model.XmlSchemaBody.xmlSchema; import static org.mockserver.model.XmlSchemaBody.xmlSchemaFromResource; /** * @author jamesdbloom */ public abstract class AbstractExtendedMockingIntegrationTest extends AbstractBasicMockingIntegrationTest { @Test public void shouldReturnResponseForRequestInSsl() { // when mockServerClient.when(request().withSecure(true)).respond(response().withBody("some_body")); // then // - in http assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()) .withReasonPhrase(HttpStatusCode.NOT_FOUND_404.reasonPhrase()), makeRequest( request() .withPath(calculatePath("")), headersToIgnore) ); // - in https assertEquals( response() .withStatusCode(OK_200.code()) .withReasonPhrase(OK_200.reasonPhrase()) .withBody("some_body"), makeRequest( request() .withSecure(true) .withPath(calculatePath("")), headersToIgnore) ); } @Test public void shouldReturnResponseForRequestNotInSsl() { // when mockServerClient.when(request().withSecure(false)).respond(response().withBody("some_body")); // then // - in http assertEquals( response() .withStatusCode(OK_200.code()) .withReasonPhrase(OK_200.reasonPhrase()) .withBody("some_body"), makeRequest( request() .withPath(calculatePath("")), headersToIgnore) ); // - in https assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()) .withReasonPhrase(HttpStatusCode.NOT_FOUND_404.reasonPhrase()), makeRequest( request() .withSecure(true) .withPath(calculatePath("")), headersToIgnore) ); } @Test public void shouldReturnResponseByMatchingPath() { // when mockServerClient .when( request() .withPath(calculatePath("some_path1")) ) .respond( response() .withBody("some_body1") ); mockServerClient .when( request() .withPath(calculatePath("some_path2")) ) .respond( response() .withBody("some_body2") ); // then // - in http assertEquals( response() .withStatusCode(OK_200.code()) .withReasonPhrase(OK_200.reasonPhrase()) .withBody("some_body2"), makeRequest( request() .withPath(calculatePath("some_path2")), headersToIgnore) ); assertEquals( response() .withStatusCode(OK_200.code()) .withReasonPhrase(OK_200.reasonPhrase()) .withBody("some_body1"), makeRequest( request() .withPath(calculatePath("some_path1")), headersToIgnore) ); // - in https assertEquals( response() .withStatusCode(OK_200.code()) .withReasonPhrase(OK_200.reasonPhrase()) .withBody("some_body2"), makeRequest( request() .withSecure(true) .withPath(calculatePath("some_path2")), headersToIgnore) ); assertEquals( response() .withStatusCode(OK_200.code()) .withReasonPhrase(OK_200.reasonPhrase()) .withBody("some_body1"), makeRequest( request() .withSecure(true) .withPath(calculatePath("some_path1")), headersToIgnore) ); } @Test public void shouldReturnResponseByMatchingPathExactTimes() { // when mockServerClient .when( request() .withPath(calculatePath("some_path")), exactly(2) ) .respond( response() .withBody("some_body") ); // then // - in http assertEquals( response() .withStatusCode(OK_200.code()) .withReasonPhrase(OK_200.reasonPhrase()) .withBody("some_body"), makeRequest( request() .withPath(calculatePath("some_path")), headersToIgnore) ); // - in https assertEquals( response() .withStatusCode(OK_200.code()) .withReasonPhrase(OK_200.reasonPhrase()) .withBody("some_body"), makeRequest( request() .withSecure(true) .withPath(calculatePath("some_path")), headersToIgnore) ); // - in http assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()) .withReasonPhrase(HttpStatusCode.NOT_FOUND_404.reasonPhrase()), makeRequest( request() .withPath(calculatePath("some_path")), headersToIgnore) ); // - in https assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()) .withReasonPhrase(HttpStatusCode.NOT_FOUND_404.reasonPhrase()), makeRequest( request() .withSecure(true) .withPath(calculatePath("some_path")), headersToIgnore) ); } @Test public void shouldReturnResponseWhenTimeToLiveHasNotExpired() { // when mockServerClient .when( request().withPath(calculatePath("some_path")), exactly(2), TimeToLive.exactly(TimeUnit.HOURS, 1L) ) .respond( response().withBody("some_body") ); // then // - in http assertEquals( response() .withStatusCode(OK_200.code()) .withReasonPhrase(OK_200.reasonPhrase()) .withBody("some_body"), makeRequest( request() .withPath(calculatePath("some_path")), headersToIgnore) ); // - in https assertEquals( response() .withStatusCode(OK_200.code()) .withReasonPhrase(OK_200.reasonPhrase()) .withBody("some_body"), makeRequest( request() .withSecure(true) .withPath(calculatePath("some_path")), headersToIgnore) ); // - in http assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()) .withReasonPhrase(HttpStatusCode.NOT_FOUND_404.reasonPhrase()), makeRequest( request() .withPath(calculatePath("some_path")), headersToIgnore) ); // - in https assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()) .withReasonPhrase(HttpStatusCode.NOT_FOUND_404.reasonPhrase()), makeRequest( request() .withSecure(true) .withPath(calculatePath("some_path")), headersToIgnore) ); } @Test public void shouldReturnMatchRequestWithBodyInUTF16() { // when String body = "我说中国话"; mockServerClient .when( request() .withBody(body, StandardCharsets.UTF_16) ) .respond( response() .withBody(body, StandardCharsets.UTF_8) ); // then // - in http assertEquals( response() .withStatusCode(OK_200.code()) .withReasonPhrase(OK_200.reasonPhrase()) .withHeader(CONTENT_TYPE.toString(), MediaType.PLAIN_TEXT_UTF_8.toString()) .withBody(body, MediaType.PLAIN_TEXT_UTF_8), makeRequest( request() .withPath(calculatePath("")) .withBody(body, StandardCharsets.UTF_16), headersToIgnore) ); // - in https assertEquals( response() .withStatusCode(OK_200.code()) .withReasonPhrase(OK_200.reasonPhrase()) .withHeader(CONTENT_TYPE.toString(), MediaType.PLAIN_TEXT_UTF_8.toString()) .withBody(body, MediaType.PLAIN_TEXT_UTF_8), makeRequest( request() .withSecure(true) .withPath(calculatePath("")) .withBody(body, StandardCharsets.UTF_16), headersToIgnore) ); } @Test public void shouldReturnMatchRequestWithBodyInUTF8WithContentTypeHeader() { // when String body = "我说中国话"; mockServerClient .when( request() .withHeader(CONTENT_TYPE.toString(), MediaType.PLAIN_TEXT_UTF_8.toString()) .withBody(body) ) .respond( response() .withBody(body, StandardCharsets.UTF_8) ); // then // - in http assertEquals( response() .withStatusCode(OK_200.code()) .withReasonPhrase(OK_200.reasonPhrase()) .withHeader(CONTENT_TYPE.toString(), MediaType.PLAIN_TEXT_UTF_8.toString()) .withBody(body, MediaType.PLAIN_TEXT_UTF_8), makeRequest( request() .withHeader(CONTENT_TYPE.toString(), MediaType.PLAIN_TEXT_UTF_8.toString()) .withPath(calculatePath("")) .withBody(body, StandardCharsets.UTF_8), headersToIgnore) ); // - in https assertEquals( response() .withStatusCode(OK_200.code()) .withReasonPhrase(OK_200.reasonPhrase()) .withHeader(CONTENT_TYPE.toString(), MediaType.PLAIN_TEXT_UTF_8.toString()) .withBody(body, MediaType.PLAIN_TEXT_UTF_8), makeRequest( request() .withHeader(CONTENT_TYPE.toString(), MediaType.PLAIN_TEXT_UTF_8.toString()) .withSecure(true) .withPath(calculatePath("")) .withBody(body, StandardCharsets.UTF_8), headersToIgnore) ); } @Test public void shouldReturnResponseWithBodyInUTF16() { // when String body = "我说中国话"; mockServerClient .when( request() .withHeader(CONTENT_TYPE.toString(), MediaType.create("text", "plain").withCharset(StandardCharsets.UTF_16).toString()) .withBody(body) ) .respond( response() .withHeader(CONTENT_TYPE.toString(), MediaType.create("text", "plain").withCharset(StandardCharsets.UTF_16).toString()) .withBody(body, StandardCharsets.UTF_16) ); // then // - in http assertEquals( response() .withStatusCode(OK_200.code()) .withReasonPhrase(OK_200.reasonPhrase()) .withHeader(CONTENT_TYPE.toString(), MediaType.create("text", "plain").withCharset(StandardCharsets.UTF_16).toString()) .withBody(body, StandardCharsets.UTF_16), makeRequest( request() .withHeader(CONTENT_TYPE.toString(), MediaType.create("text", "plain").withCharset(StandardCharsets.UTF_16).toString()) .withPath(calculatePath("")) .withBody(body), headersToIgnore) ); // - in https assertEquals( response() .withStatusCode(OK_200.code()) .withReasonPhrase(OK_200.reasonPhrase()) .withHeader(CONTENT_TYPE.toString(), MediaType.create("text", "plain").withCharset(StandardCharsets.UTF_16).toString()) .withBody(body, StandardCharsets.UTF_16), makeRequest( request() .withHeader(CONTENT_TYPE.toString(), MediaType.create("text", "plain").withCharset(StandardCharsets.UTF_16).toString()) .withSecure(true) .withPath(calculatePath("")) .withBody(body), headersToIgnore) ); } @Test public void shouldReturnResponseWithBodyInUTF8WithContentTypeHeader() { // when String body = "我说中国话"; mockServerClient .when( request() ) .respond( response() .withHeader(CONTENT_TYPE.toString(), MediaType.PLAIN_TEXT_UTF_8.toString()) .withBody(body) ); // then // - in http assertEquals( response() .withStatusCode(OK_200.code()) .withReasonPhrase(OK_200.reasonPhrase()) .withHeader(CONTENT_TYPE.toString(), MediaType.PLAIN_TEXT_UTF_8.toString()) .withBody(body, MediaType.PLAIN_TEXT_UTF_8), makeRequest( request() .withPath(calculatePath("")), headersToIgnore) ); // - in https assertEquals( response() .withStatusCode(OK_200.code()) .withReasonPhrase(OK_200.reasonPhrase()) .withHeader(CONTENT_TYPE.toString(), MediaType.PLAIN_TEXT_UTF_8.toString()) .withBody(body, MediaType.PLAIN_TEXT_UTF_8), makeRequest( request() .withSecure(true) .withPath(calculatePath("")), headersToIgnore) ); } @Test public void shouldReturnResponseWithBodyInUTF8WithNoContentTypeHeader() { // when String body = "我说中国话"; mockServerClient .when( request() ) .respond( response() .withBody(body, CharsetUtil.UTF_8) ); // then // - in http assertEquals( response() .withStatusCode(OK_200.code()) .withReasonPhrase(OK_200.reasonPhrase()) .withHeader(CONTENT_TYPE.toString(), MediaType.PLAIN_TEXT_UTF_8.toString()) .withBody(body, CharsetUtil.UTF_8), makeRequest( request() .withPath(calculatePath("")), headersToIgnore) ); // - in https assertEquals( response() .withStatusCode(OK_200.code()) .withReasonPhrase(OK_200.reasonPhrase()) .withHeader(CONTENT_TYPE.toString(), MediaType.PLAIN_TEXT_UTF_8.toString()) .withBody(body, CharsetUtil.UTF_8), makeRequest( request() .withSecure(true) .withPath(calculatePath("")), headersToIgnore) ); } @Test public void shouldReturnResponseByMatchingSubStringBody() { // when mockServerClient .when( request() .withBody( subString("random") ), exactly(2) ) .respond( response() .withBody("some_sub_string_body_response") ); // then // - in http assertEquals( response() .withStatusCode(OK_200.code()) .withReasonPhrase(OK_200.reasonPhrase()) .withBody("some_sub_string_body_response"), makeRequest( request() .withMethod("POST") .withPath(calculatePath("some_path")) .withBody("some_random_body"), headersToIgnore) ); // - in https assertEquals( response() .withStatusCode(OK_200.code()) .withReasonPhrase(OK_200.reasonPhrase()) .withBody("some_sub_string_body_response"), makeRequest( request() .withSecure(true) .withMethod("POST") .withPath(calculatePath("some_path")) .withBody("some_random_body"), headersToIgnore) ); } @Test public void shouldReturnResponseByMatchingBodyWithXPath() { // when mockServerClient.when(request().withBody(xpath("/bookstore/book[price>30]/price")), exactly(2)).respond(response().withBody("some_body")); // then // - in http assertEquals( response() .withStatusCode(OK_200.code()) .withReasonPhrase(OK_200.reasonPhrase()) .withBody("some_body"), makeRequest( request() .withPath(calculatePath("some_path")) .withMethod("POST") .withBody(new StringBody("" + "<?xml version=\"1.0\" encoding=\"ISO-8859-1\"?>" + NEW_LINE + "<bookstore>" + NEW_LINE + " <book category=\"COOKING\">" + NEW_LINE + " <title lang=\"en\">Everyday Italian</title>" + NEW_LINE + " <author>Giada De Laurentiis</author>" + NEW_LINE + " <year>2005</year>" + NEW_LINE + " <price>30.00</price>" + NEW_LINE + " </book>" + NEW_LINE + " <book category=\"CHILDREN\">" + NEW_LINE + " <title lang=\"en\">Harry Potter</title>" + NEW_LINE + " <author>J K. Rowling</author>" + NEW_LINE + " <year>2005</year>" + NEW_LINE + " <price>29.99</price>" + NEW_LINE + " </book>" + NEW_LINE + " <book category=\"WEB\">" + NEW_LINE + " <title lang=\"en\">Learning XML</title>" + NEW_LINE + " <author>Erik T. Ray</author>" + NEW_LINE + " <year>2003</year>" + NEW_LINE + " <price>31.95</price>" + NEW_LINE + " </book>" + NEW_LINE + "</bookstore>")), headersToIgnore) ); // - in https assertEquals( response() .withStatusCode(OK_200.code()) .withReasonPhrase(OK_200.reasonPhrase()) .withBody("some_body"), makeRequest( request() .withSecure(true) .withPath(calculatePath("some_path")) .withMethod("POST") .withBody(new StringBody("" + "<?xml version=\"1.0\" encoding=\"ISO-8859-1\"?>" + NEW_LINE + "<bookstore>" + NEW_LINE + " <book category=\"COOKING\">" + NEW_LINE + " <title lang=\"en\">Everyday Italian</title>" + NEW_LINE + " <author>Giada De Laurentiis</author>" + NEW_LINE + " <year>2005</year>" + NEW_LINE + " <price>30.00</price>" + NEW_LINE + " </book>" + NEW_LINE + " <book category=\"CHILDREN\">" + NEW_LINE + " <title lang=\"en\">Harry Potter</title>" + NEW_LINE + " <author>J K. Rowling</author>" + NEW_LINE + " <year>2005</year>" + NEW_LINE + " <price>29.99</price>" + NEW_LINE + " </book>" + NEW_LINE + " <book category=\"WEB\">" + NEW_LINE + " <title lang=\"en\">Learning XML</title>" + NEW_LINE + " <author>Erik T. Ray</author>" + NEW_LINE + " <year>2003</year>" + NEW_LINE + " <price>31.95</price>" + NEW_LINE + " </book>" + NEW_LINE + "</bookstore>")), headersToIgnore) ); } @Test public void shouldReturnResponseByMatchingBodyWithXmlSchema() { // when mockServerClient.when(request() .withBody( xmlSchema("<?xml version=\"1.0\" encoding=\"UTF-8\"?>" + NEW_LINE + "<xs:schema xmlns:xs=\"http://www.w3.org/2001/XMLSchema\" elementFormDefault=\"qualified\" attributeFormDefault=\"unqualified\">" + NEW_LINE + " <!-- XML Schema Generated from XML Document on Wed Jun 28 2017 21:52:45 GMT+0100 (BST) -->" + NEW_LINE + " <!-- with XmlGrid.net Free Online Service http://xmlgrid.net -->" + NEW_LINE + " <xs:element name=\"notes\">" + NEW_LINE + " <xs:complexType>" + NEW_LINE + " <xs:sequence>" + NEW_LINE + " <xs:element name=\"note\" maxOccurs=\"unbounded\">" + NEW_LINE + " <xs:complexType>" + NEW_LINE + " <xs:sequence>" + NEW_LINE + " <xs:element name=\"to\" minOccurs=\"1\" maxOccurs=\"1\" type=\"xs:string\"></xs:element>" + NEW_LINE + " <xs:element name=\"from\" minOccurs=\"1\" maxOccurs=\"1\" type=\"xs:string\"></xs:element>" + NEW_LINE + " <xs:element name=\"heading\" minOccurs=\"1\" maxOccurs=\"1\" type=\"xs:string\"></xs:element>" + NEW_LINE + " <xs:element name=\"body\" minOccurs=\"1\" maxOccurs=\"1\" type=\"xs:string\"></xs:element>" + NEW_LINE + " </xs:sequence>" + NEW_LINE + " </xs:complexType>" + NEW_LINE + " </xs:element>" + NEW_LINE + " </xs:sequence>" + NEW_LINE + " </xs:complexType>" + NEW_LINE + " </xs:element>" + NEW_LINE + "</xs:schema>")), exactly(2) ) .respond( response() .withBody("some_body") ); // then // - in http assertEquals( response() .withStatusCode(NOT_FOUND_404.code()) .withReasonPhrase(NOT_FOUND_404.reasonPhrase()), makeRequest( request() .withMethod("POST") .withBody("<?xml version=\"1.0\" encoding=\"utf-8\"?>" + NEW_LINE + "<notes>" + NEW_LINE + " <note>" + NEW_LINE + " <to>Bob</to>" + NEW_LINE + " <heading>Reminder</heading>" + NEW_LINE + " <body>Buy Bread</body>" + NEW_LINE + " </note>" + NEW_LINE + " <note>" + NEW_LINE + " <to>Jack</to>" + NEW_LINE + " <from>Jill</from>" + NEW_LINE + " <heading>Reminder</heading>" + NEW_LINE + " <body>Wash Shirts</body>" + NEW_LINE + " </note>" + NEW_LINE + "</notes>"), headersToIgnore) ); assertEquals( response() .withStatusCode(OK_200.code()) .withReasonPhrase(OK_200.reasonPhrase()) .withBody("some_body"), makeRequest( request() .withPath(calculatePath("some_path")) .withMethod("POST") .withBody("<?xml version=\"1.0\" encoding=\"utf-8\"?>" + NEW_LINE + "<notes>" + NEW_LINE + " <note>" + NEW_LINE + " <to>Bob</to>" + NEW_LINE + " <from>Bill</from>" + NEW_LINE + " <heading>Reminder</heading>" + NEW_LINE + " <body>Buy Bread</body>" + NEW_LINE + " </note>" + NEW_LINE + " <note>" + NEW_LINE + " <to>Jack</to>" + NEW_LINE + " <from>Jill</from>" + NEW_LINE + " <heading>Reminder</heading>" + NEW_LINE + " <body>Wash Shirts</body>" + NEW_LINE + " </note>" + NEW_LINE + "</notes>"), headersToIgnore) ); // - in https assertEquals( response() .withStatusCode(OK_200.code()) .withReasonPhrase(OK_200.reasonPhrase()) .withBody("some_body"), makeRequest( request() .withSecure(true) .withPath(calculatePath("some_path")) .withMethod("POST") .withBody("<?xml version=\"1.0\" encoding=\"utf-8\"?>" + NEW_LINE + "<notes>" + NEW_LINE + " <note>" + NEW_LINE + " <to>Bob</to>" + NEW_LINE + " <from>Bill</from>" + NEW_LINE + " <heading>Reminder</heading>" + NEW_LINE + " <body>Buy Bread</body>" + NEW_LINE + " </note>" + NEW_LINE + " <note>" + NEW_LINE + " <to>Jack</to>" + NEW_LINE + " <from>Jill</from>" + NEW_LINE + " <heading>Reminder</heading>" + NEW_LINE + " <body>Wash Shirts</body>" + NEW_LINE + " </note>" + NEW_LINE + "</notes>"), headersToIgnore) ); } @Test public void shouldReturnResponseByMatchingBodyWithXmlSchemaByClasspath() { // when mockServerClient.when(request() .withBody( xmlSchemaFromResource("org/mockserver/model/testXmlSchema.xsd")), exactly(2) ) .respond( response() .withBody("some_body") ); // then // - in http assertEquals( response() .withStatusCode(NOT_FOUND_404.code()) .withReasonPhrase(NOT_FOUND_404.reasonPhrase()), makeRequest( request() .withMethod("POST") .withBody("<?xml version=\"1.0\" encoding=\"utf-8\"?>" + NEW_LINE + "<notes>" + NEW_LINE + " <note>" + NEW_LINE + " <to>Bob</to>" + NEW_LINE + " <heading>Reminder</heading>" + NEW_LINE + " <body>Buy Bread</body>" + NEW_LINE + " </note>" + NEW_LINE + " <note>" + NEW_LINE + " <to>Jack</to>" + NEW_LINE + " <from>Jill</from>" + NEW_LINE + " <heading>Reminder</heading>" + NEW_LINE + " <body>Wash Shirts</body>" + NEW_LINE + " </note>" + NEW_LINE + "</notes>"), headersToIgnore) ); assertEquals( response() .withStatusCode(OK_200.code()) .withReasonPhrase(OK_200.reasonPhrase()) .withBody("some_body"), makeRequest( request() .withPath(calculatePath("some_path")) .withMethod("POST") .withBody("<?xml version=\"1.0\" encoding=\"utf-8\"?>" + NEW_LINE + "<notes>" + NEW_LINE + " <note>" + NEW_LINE + " <to>Bob</to>" + NEW_LINE + " <from>Bill</from>" + NEW_LINE + " <heading>Reminder</heading>" + NEW_LINE + " <body>Buy Bread</body>" + NEW_LINE + " </note>" + NEW_LINE + " <note>" + NEW_LINE + " <to>Jack</to>" + NEW_LINE + " <from>Jill</from>" + NEW_LINE + " <heading>Reminder</heading>" + NEW_LINE + " <body>Wash Shirts</body>" + NEW_LINE + " </note>" + NEW_LINE + "</notes>"), headersToIgnore) ); // - in https assertEquals( response() .withStatusCode(OK_200.code()) .withReasonPhrase(OK_200.reasonPhrase()) .withBody("some_body"), makeRequest( request() .withSecure(true) .withPath(calculatePath("some_path")) .withMethod("POST") .withBody("<?xml version=\"1.0\" encoding=\"utf-8\"?>" + NEW_LINE + "<notes>" + NEW_LINE + " <note>" + NEW_LINE + " <to>Bob</to>" + NEW_LINE + " <from>Bill</from>" + NEW_LINE + " <heading>Reminder</heading>" + NEW_LINE + " <body>Buy Bread</body>" + NEW_LINE + " </note>" + NEW_LINE + " <note>" + NEW_LINE + " <to>Jack</to>" + NEW_LINE + " <from>Jill</from>" + NEW_LINE + " <heading>Reminder</heading>" + NEW_LINE + " <body>Wash Shirts</body>" + NEW_LINE + " </note>" + NEW_LINE + "</notes>"), headersToIgnore) ); } @Test public void shouldReturnResponseByMatchingBodyWithXml() { // when mockServerClient.when(request().withBody(xml("" + "<bookstore>" + NEW_LINE + " <book nationality=\"ITALIAN\" category=\"COOKING\"><title lang=\"en\">Everyday Italian</title><author>Giada De Laurentiis</author><year>2005</year><price>30.00</price></book>" + NEW_LINE + "</bookstore>")), exactly(2)).respond(response().withBody("some_body")); // then // - in http assertEquals( response() .withStatusCode(OK_200.code()) .withReasonPhrase(OK_200.reasonPhrase()) .withBody("some_body"), makeRequest( request() .withPath(calculatePath("some_path")) .withMethod("POST") .withBody(new StringBody("" + "<?xml version=\"1.0\" encoding=\"ISO-8859-1\"?>" + NEW_LINE + "<bookstore>" + NEW_LINE + " <book category=\"COOKING\" nationality=\"ITALIAN\">" + NEW_LINE + " <title lang=\"en\">Everyday Italian</title>" + NEW_LINE + " <author>Giada De Laurentiis</author>" + NEW_LINE + " <year>2005</year>" + NEW_LINE + " <price>30.00</price>" + NEW_LINE + " </book>" + NEW_LINE + "</bookstore>")), headersToIgnore) ); // - in https assertEquals( response() .withStatusCode(OK_200.code()) .withReasonPhrase(OK_200.reasonPhrase()) .withBody("some_body"), makeRequest( request() .withSecure(true) .withPath(calculatePath("some_path")) .withMethod("POST") .withBody(new StringBody("" + "<?xml version=\"1.0\" encoding=\"ISO-8859-1\"?>" + NEW_LINE + "<bookstore>" + NEW_LINE + " <book category=\"COOKING\" nationality=\"ITALIAN\">" + NEW_LINE + " <title lang=\"en\">Everyday Italian</title>" + NEW_LINE + " <author>Giada De Laurentiis</author>" + NEW_LINE + " <year>2005</year>" + NEW_LINE + " <price>30.00</price>" + NEW_LINE + " </book>" + NEW_LINE + "</bookstore>")), headersToIgnore) ); } @Test public void shouldReturnResponseByMatchingBodyWithJson() { // when mockServerClient .when( request() .withBody(json("{" + NEW_LINE + " \"id\": 1," + NEW_LINE + " \"name\": \"A green door\"," + NEW_LINE + " \"price\": 12.50," + NEW_LINE + " \"tags\": [\"home\", \"green\"]" + NEW_LINE + "}")), exactly(2) ) .respond( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withReasonPhrase(HttpStatusCode.ACCEPTED_202.reasonPhrase()) .withBody("some_body") ); // then // - in http assertEquals( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withReasonPhrase(HttpStatusCode.ACCEPTED_202.reasonPhrase()) .withBody("some_body"), makeRequest( request() .withPath(calculatePath("some_path")) .withMethod("POST") .withBody("{" + NEW_LINE + " \"id\": 1," + NEW_LINE + " \"extra ignored field\": \"some value\"," + NEW_LINE + " \"name\": \"A green door\"," + NEW_LINE + " \"price\": 12.50," + NEW_LINE + " \"tags\": [\"home\", \"green\"]" + NEW_LINE + "}"), headersToIgnore) ); // - in https assertEquals( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withReasonPhrase(HttpStatusCode.ACCEPTED_202.reasonPhrase()) .withBody("some_body"), makeRequest( request() .withSecure(true) .withPath(calculatePath("some_path")) .withMethod("POST") .withBody("{" + NEW_LINE + " \"id\": 1," + NEW_LINE + " \"extra ignored array\": [\"one\", \"two\"]," + NEW_LINE + " \"name\": \"A green door\"," + NEW_LINE + " \"price\": 12.50," + NEW_LINE + " \"tags\": [\"home\", \"green\"]" + NEW_LINE + "}"), headersToIgnore) ); } @Test public void shouldReturnResponseByMatchingBodyWithJsonWithCharsetUTF8() { // when mockServerClient .when( request() .withBody(json("{" + NEW_LINE + " \"ταυτότητα\": 1," + NEW_LINE + " \"όνομα\": \"μια πράσινη πόρτα\"," + NEW_LINE + " \"τιμή\": 12.50," + NEW_LINE + " \"ετικέτες\": [\"σπίτι\", \"πράσινος\"]" + NEW_LINE + "}", StandardCharsets.UTF_16, MatchType.ONLY_MATCHING_FIELDS)), exactly(2) ) .respond( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withReasonPhrase(HttpStatusCode.ACCEPTED_202.reasonPhrase()) .withBody("some_body") ); // then // - in http assertEquals( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withReasonPhrase(HttpStatusCode.ACCEPTED_202.reasonPhrase()) .withBody("some_body"), makeRequest( request() .withPath(calculatePath("some_path")) .withMethod("POST") .withBody(json("{" + NEW_LINE + " \"ταυτότητα\": 1," + NEW_LINE + " \"επιπλέον αγνοούνται τομέα\": \"κάποια αξία\"," + NEW_LINE + " \"όνομα\": \"μια πράσινη πόρτα\"," + NEW_LINE + " \"τιμή\": 12.50," + NEW_LINE + " \"ετικέτες\": [\"σπίτι\", \"πράσινος\"]" + NEW_LINE + "}", StandardCharsets.UTF_16, MatchType.ONLY_MATCHING_FIELDS)), headersToIgnore) ); // - in https assertEquals( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withReasonPhrase(HttpStatusCode.ACCEPTED_202.reasonPhrase()) .withBody("some_body"), makeRequest( request() .withSecure(true) .withPath(calculatePath("some_path")) .withMethod("POST") .withBody(json("{" + NEW_LINE + " \"ταυτότητα\": 1," + NEW_LINE + " \"επιπλέον αγνοούνται σειρά\": [\"ένας\", \"δυο\"]," + NEW_LINE + " \"όνομα\": \"μια πράσινη πόρτα\"," + NEW_LINE + " \"τιμή\": 12.50," + NEW_LINE + " \"ετικέτες\": [\"σπίτι\", \"πράσινος\"]" + NEW_LINE + "}", StandardCharsets.UTF_16, MatchType.ONLY_MATCHING_FIELDS)), headersToIgnore) ); } @Test public void shouldReturnResponseByMatchingBodyWithJsonWithContentTypeHeader() { // when mockServerClient .when( request() .withBody(json("{" + NEW_LINE + " \"ταυτότητα\": 1," + NEW_LINE + " \"όνομα\": \"μια πράσινη πόρτα\"," + NEW_LINE + " \"τιμή\": 12.50," + NEW_LINE + " \"ετικέτες\": [\"σπίτι\", \"πράσινος\"]" + NEW_LINE + "}", StandardCharsets.UTF_16, MatchType.ONLY_MATCHING_FIELDS)), exactly(2) ) .respond( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withReasonPhrase(HttpStatusCode.ACCEPTED_202.reasonPhrase()) .withBody("some_body") ); // then // - in http assertEquals( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withReasonPhrase(HttpStatusCode.ACCEPTED_202.reasonPhrase()) .withBody("some_body"), makeRequest( request() .withHeader(CONTENT_TYPE.toString(), MediaType.create("text", "plain").withCharset(StandardCharsets.UTF_16).toString()) .withPath(calculatePath("some_path")) .withMethod("POST") .withBody(json("{" + NEW_LINE + " \"ταυτότητα\": 1," + NEW_LINE + " \"επιπλέον αγνοούνται τομέα\": \"κάποια αξία\"," + NEW_LINE + " \"όνομα\": \"μια πράσινη πόρτα\"," + NEW_LINE + " \"τιμή\": 12.50," + NEW_LINE + " \"ετικέτες\": [\"σπίτι\", \"πράσινος\"]" + NEW_LINE + "}")), headersToIgnore) ); // - in https assertEquals( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withReasonPhrase(HttpStatusCode.ACCEPTED_202.reasonPhrase()) .withBody("some_body"), makeRequest( request() .withSecure(true) .withHeader(CONTENT_TYPE.toString(), MediaType.create("text", "plain").withCharset(StandardCharsets.UTF_16).toString()) .withPath(calculatePath("some_path")) .withMethod("POST") .withBody(json("{" + NEW_LINE + " \"ταυτότητα\": 1," + NEW_LINE + " \"επιπλέον αγνοούνται σειρά\": [\"ένας\", \"δυο\"]," + NEW_LINE + " \"όνομα\": \"μια πράσινη πόρτα\"," + NEW_LINE + " \"τιμή\": 12.50," + NEW_LINE + " \"ετικέτες\": [\"σπίτι\", \"πράσινος\"]" + NEW_LINE + "}")), headersToIgnore) ); } @Test public void shouldReturnResponseByMatchingBodyWithJsonWithMatchType() { // when mockServerClient .when( request() .withBody(json("{" + NEW_LINE + " \"id\": 1," + NEW_LINE + " \"name\": \"A green door\"," + NEW_LINE + " \"price\": 12.50," + NEW_LINE + " \"tags\": [\"home\", \"green\"]" + NEW_LINE + "}", MatchType.ONLY_MATCHING_FIELDS)), exactly(2) ) .respond( response() .withBody("some_body") ); // then // - in http assertEquals( response("some_body"), makeRequest( request() .withPath(calculatePath("some_path")) .withMethod("POST") .withBody("{" + NEW_LINE + " \"id\": 1," + NEW_LINE + " \"extra field\": \"some value\"," + NEW_LINE + " \"name\": \"A green door\"," + NEW_LINE + " \"price\": 12.50," + NEW_LINE + " \"tags\": [\"home\", \"green\"]" + NEW_LINE + "}"), headersToIgnore) ); // - in https assertEquals( response("some_body"), makeRequest( request() .withSecure(true) .withPath(calculatePath("some_path")) .withMethod("POST") .withBody("{" + NEW_LINE + " \"id\": 1," + NEW_LINE + " \"extra field\": \"some value\"," + NEW_LINE + " \"name\": \"A green door\"," + NEW_LINE + " \"price\": 12.50," + NEW_LINE + " \"tags\": [\"home\", \"green\"]" + NEW_LINE + "}"), headersToIgnore) ); } @Test public void shouldReturnResponseByMatchingBodyWithJsonSchema() { // when mockServerClient.when(request().withBody(jsonSchema("{" + NEW_LINE + " \"$schema\": \"http://json-schema.org/draft-04/schema#\"," + NEW_LINE + " \"title\": \"Product\"," + NEW_LINE + " \"description\": \"A product from Acme's catalog\"," + NEW_LINE + " \"type\": \"object\"," + NEW_LINE + " \"properties\": {" + NEW_LINE + " \"id\": {" + NEW_LINE + " \"description\": \"The unique identifier for a product\"," + NEW_LINE + " \"type\": \"integer\"" + NEW_LINE + " }," + NEW_LINE + " \"name\": {" + NEW_LINE + " \"description\": \"Name of the product\"," + NEW_LINE + " \"type\": \"string\"" + NEW_LINE + " }," + NEW_LINE + " \"price\": {" + NEW_LINE + " \"type\": \"number\"," + NEW_LINE + " \"minimum\": 0," + NEW_LINE + " \"exclusiveMinimum\": true" + NEW_LINE + " }," + NEW_LINE + " \"tags\": {" + NEW_LINE + " \"type\": \"array\"," + NEW_LINE + " \"items\": {" + NEW_LINE + " \"type\": \"string\"" + NEW_LINE + " }," + NEW_LINE + " \"minItems\": 1," + NEW_LINE + " \"uniqueItems\": true" + NEW_LINE + " }" + NEW_LINE + " }," + NEW_LINE + " \"required\": [\"id\", \"name\", \"price\"]" + NEW_LINE + "}")), exactly(2)).respond(response().withBody("some_body")); // then // - in http assertEquals( response() .withStatusCode(OK_200.code()) .withReasonPhrase(OK_200.reasonPhrase()) .withBody("some_body"), makeRequest( request() .withPath(calculatePath("some_path")) .withMethod("POST") .withBody("{" + NEW_LINE + " \"id\": 1," + NEW_LINE + " \"name\": \"A green door\"," + NEW_LINE + " \"price\": 12.50," + NEW_LINE + " \"tags\": [\"home\", \"green\"]" + NEW_LINE + "}"), headersToIgnore) ); // - in https assertEquals( response() .withStatusCode(OK_200.code()) .withReasonPhrase(OK_200.reasonPhrase()) .withBody("some_body"), makeRequest( request() .withSecure(true) .withPath(calculatePath("some_path")) .withMethod("POST") .withBody("{" + NEW_LINE + " \"id\": 1," + NEW_LINE + " \"name\": \"A green door\"," + NEW_LINE + " \"price\": 12.50," + NEW_LINE + " \"tags\": [\"home\", \"green\"]" + NEW_LINE + "}"), headersToIgnore) ); } @Test public void shouldReturnResponseByMatchingBodyWithJsonPath() { // when mockServerClient.when(request().withBody(jsonPath("$..book[?(@.price <= $['expensive'])]")), exactly(2)).respond(response().withBody("some_body")); // then // - in http assertEquals( response() .withStatusCode(OK_200.code()) .withReasonPhrase(OK_200.reasonPhrase()) .withBody("some_body"), makeRequest( request() .withPath(calculatePath("some_path")) .withMethod("POST") .withBody(new StringBody("" + "{\n" + " \"store\": {\n" + " \"book\": [\n" + " {\n" + " \"category\": \"reference\",\n" + " \"author\": \"Nigel Rees\",\n" + " \"title\": \"Sayings of the Century\",\n" + " \"price\": 8.95\n" + " },\n" + " {\n" + " \"category\": \"fiction\",\n" + " \"author\": \"Herman Melville\",\n" + " \"title\": \"Moby Dick\",\n" + " \"isbn\": \"0-553-21311-3\",\n" + " \"price\": 8.99\n" + " }\n" + " ],\n" + " \"bicycle\": {\n" + " \"color\": \"red\",\n" + " \"price\": 19.95\n" + " }\n" + " },\n" + " \"expensive\": 10\n" + "}")), headersToIgnore) ); // - in https assertEquals( response() .withStatusCode(OK_200.code()) .withReasonPhrase(OK_200.reasonPhrase()) .withBody("some_body"), makeRequest( request() .withSecure(true) .withPath(calculatePath("some_path")) .withMethod("POST") .withBody(new StringBody("" + "{\n" + " \"store\": {\n" + " \"book\": [\n" + " {\n" + " \"category\": \"reference\",\n" + " \"author\": \"Nigel Rees\",\n" + " \"title\": \"Sayings of the Century\",\n" + " \"price\": 8.95\n" + " },\n" + " {\n" + " \"category\": \"fiction\",\n" + " \"author\": \"Herman Melville\",\n" + " \"title\": \"Moby Dick\",\n" + " \"isbn\": \"0-553-21311-3\",\n" + " \"price\": 8.99\n" + " }\n" + " ],\n" + " \"bicycle\": {\n" + " \"color\": \"red\",\n" + " \"price\": 19.95\n" + " }\n" + " },\n" + " \"expensive\": 10\n" + "}")), headersToIgnore) ); } @Test public void shouldReturnPDFResponseByMatchingPath() throws IOException { // when byte[] pdfBytes = IOUtils.toByteArray(getClass().getClassLoader().getResourceAsStream("test.pdf")); mockServerClient .when( request() .withPath(calculatePath("ws/rest/user/[0-9]+/document/[0-9]+\\.pdf")) ) .respond( response() .withStatusCode(OK_200.code()) .withReasonPhrase(OK_200.reasonPhrase()) .withHeaders( header(CONTENT_TYPE.toString(), MediaType.PDF.toString()), header(CONTENT_DISPOSITION.toString(), "form-data; name=\"test.pdf\"; filename=\"test.pdf\""), header(CACHE_CONTROL.toString(), "must-revalidate, post-check=0, pre-check=0") ) .withBody(binary(pdfBytes)) ); // then // - in http assertEquals( response() .withStatusCode(OK_200.code()) .withReasonPhrase(OK_200.reasonPhrase()) .withHeaders( header(CONTENT_DISPOSITION.toString(), "form-data; name=\"test.pdf\"; filename=\"test.pdf\""), header(CACHE_CONTROL.toString(), "must-revalidate, post-check=0, pre-check=0"), header(CONTENT_TYPE.toString(), MediaType.PDF.toString()) ) .withBody(binary(pdfBytes)), makeRequest( request() .withPath(calculatePath("ws/rest/user/1/document/2.pdf")) .withMethod("GET"), headersToIgnore) ); // - in https assertEquals( response() .withStatusCode(OK_200.code()) .withReasonPhrase(OK_200.reasonPhrase()) .withHeaders( header(CONTENT_DISPOSITION.toString(), "form-data; name=\"test.pdf\"; filename=\"test.pdf\""), header(CACHE_CONTROL.toString(), "must-revalidate, post-check=0, pre-check=0"), header(CONTENT_TYPE.toString(), MediaType.PDF.toString()) ) .withBody(binary(pdfBytes)), makeRequest( request() .withSecure(true) .withPath(calculatePath("ws/rest/user/1/document/2.pdf")) .withMethod("GET"), headersToIgnore) ); } @Test public void shouldReturnPNGResponseByMatchingPath() throws IOException { // when byte[] pngBytes = IOUtils.toByteArray(getClass().getClassLoader().getResourceAsStream("test.png")); mockServerClient .when( request() .withPath(calculatePath("ws/rest/user/[0-9]+/icon/[0-9]+\\.png")) ) .respond( response() .withStatusCode(OK_200.code()) .withReasonPhrase(OK_200.reasonPhrase()) .withHeaders( header(CONTENT_TYPE.toString(), MediaType.PNG.toString()), header(CONTENT_DISPOSITION.toString(), "form-data; name=\"test.png\"; filename=\"test.png\"") ) .withBody(binary(pngBytes)) ); // then // - in http assertEquals( response() .withStatusCode(OK_200.code()) .withReasonPhrase(OK_200.reasonPhrase()) .withHeaders( header(CONTENT_DISPOSITION.toString(), "form-data; name=\"test.png\"; filename=\"test.png\""), header(CONTENT_TYPE.toString(), MediaType.PNG.toString()) ) .withBody(binary(pngBytes)), makeRequest( request() .withPath(calculatePath("ws/rest/user/1/icon/1.png")) .withMethod("GET"), headersToIgnore) ); // - in https assertEquals( response() .withStatusCode(OK_200.code()) .withReasonPhrase(OK_200.reasonPhrase()) .withHeaders( header(CONTENT_DISPOSITION.toString(), "form-data; name=\"test.png\"; filename=\"test.png\""), header(CONTENT_TYPE.toString(), MediaType.PNG.toString()) ) .withBody(binary(pngBytes)), makeRequest( request() .withSecure(true) .withPath(calculatePath("ws/rest/user/1/icon/1.png")) .withMethod("GET"), headersToIgnore) ); } @Test public void shouldReturnPDFResponseByMatchingBinaryPDFBody() throws IOException { // when byte[] pdfBytes = IOUtils.toByteArray(getClass().getClassLoader().getResourceAsStream("test.pdf")); mockServerClient .when( request() .withBody(binary(pdfBytes, MediaType.PDF)) ) .respond( response() .withStatusCode(OK_200.code()) .withReasonPhrase(OK_200.reasonPhrase()) .withHeaders( header(CONTENT_TYPE.toString(), MediaType.PDF.toString()), header(CONTENT_DISPOSITION.toString(), "form-data; name=\"test.pdf\"; filename=\"test.pdf\""), header(CACHE_CONTROL.toString(), "must-revalidate, post-check=0, pre-check=0") ) .withBody(binary(pdfBytes)) ); // then // - in http assertEquals( response() .withStatusCode(OK_200.code()) .withReasonPhrase(OK_200.reasonPhrase()) .withHeaders( header(CONTENT_DISPOSITION.toString(), "form-data; name=\"test.pdf\"; filename=\"test.pdf\""), header(CACHE_CONTROL.toString(), "must-revalidate, post-check=0, pre-check=0"), header(CONTENT_TYPE.toString(), MediaType.PDF.toString()) ) .withBody(binary(pdfBytes)), makeRequest( request() .withPath(calculatePath("ws/rest/user/1/document/2.pdf")) .withBody(binary(pdfBytes, MediaType.PDF)) .withMethod("POST"), headersToIgnore) ); // - in https assertEquals( response() .withStatusCode(OK_200.code()) .withReasonPhrase(OK_200.reasonPhrase()) .withHeaders( header(CONTENT_DISPOSITION.toString(), "form-data; name=\"test.pdf\"; filename=\"test.pdf\""), header(CACHE_CONTROL.toString(), "must-revalidate, post-check=0, pre-check=0"), header(CONTENT_TYPE.toString(), MediaType.PDF.toString()) ) .withBody(binary(pdfBytes)), makeRequest( request() .withSecure(true) .withPath(calculatePath("ws/rest/user/1/document/2.pdf")) .withBody(binary(pdfBytes, MediaType.PDF)) .withMethod("POST"), headersToIgnore) ); } @Test public void shouldReturnPNGResponseByMatchingBinaryPNGBody() throws IOException { // when byte[] pngBytes = IOUtils.toByteArray(getClass().getClassLoader().getResourceAsStream("test.png")); mockServerClient .when( request() .withBody(binary(pngBytes, MediaType.ANY_IMAGE_TYPE)) ) .respond( response() .withStatusCode(OK_200.code()) .withReasonPhrase(OK_200.reasonPhrase()) .withHeaders( header(CONTENT_TYPE.toString(), MediaType.PNG.toString()), header(CONTENT_DISPOSITION.toString(), "form-data; name=\"test.png\"; filename=\"test.png\"") ) .withBody(binary(pngBytes)) ); // then // - in http assertEquals( response() .withStatusCode(OK_200.code()) .withReasonPhrase(OK_200.reasonPhrase()) .withHeaders( header(CONTENT_DISPOSITION.toString(), "form-data; name=\"test.png\"; filename=\"test.png\""), header(CONTENT_TYPE.toString(), MediaType.PNG.toString()) ) .withBody(binary(pngBytes)), makeRequest( request() .withPath(calculatePath("ws/rest/user/1/icon/1.png")) .withBody(binary(pngBytes, MediaType.ANY_IMAGE_TYPE)) .withMethod("POST"), headersToIgnore) ); // - in https assertEquals( response() .withStatusCode(OK_200.code()) .withReasonPhrase(OK_200.reasonPhrase()) .withHeaders( header(CONTENT_DISPOSITION.toString(), "form-data; name=\"test.png\"; filename=\"test.png\""), header(CONTENT_TYPE.toString(), MediaType.PNG.toString()) ) .withBody(binary(pngBytes)), makeRequest( request() .withSecure(true) .withPath(calculatePath("ws/rest/user/1/icon/1.png")) .withBody(binary(pngBytes, MediaType.ANY_IMAGE_TYPE)) .withMethod("POST"), headersToIgnore) ); } @Test public void shouldReturnResponseByNotMatchingPathWithNotOperator() { // when mockServerClient .when( request() .withPath(not(calculatePath("some_path"))) ) .respond( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withReasonPhrase(HttpStatusCode.ACCEPTED_202.reasonPhrase()) .withBody("some_body_response") ); // then // - in http assertEquals( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withReasonPhrase(HttpStatusCode.ACCEPTED_202.reasonPhrase()) .withBody("some_body_response"), makeRequest( request() .withPath(calculatePath("some_other_path")), headersToIgnore) ); // - in https assertEquals( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withReasonPhrase(HttpStatusCode.ACCEPTED_202.reasonPhrase()) .withBody("some_body_response"), makeRequest( request() .withPath(calculatePath("some_other_path")), headersToIgnore) ); } @Test public void shouldReturnResponseByNotMatchingMethodWithNotOperator() { // when mockServerClient .when( request() .withMethod(not("GET")) ) .respond( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withReasonPhrase(HttpStatusCode.ACCEPTED_202.reasonPhrase()) .withBody("some_body_response") ); // then // - in http assertEquals( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withReasonPhrase(HttpStatusCode.ACCEPTED_202.reasonPhrase()) .withBody("some_body_response"), makeRequest( request() .withMethod("POST"), headersToIgnore) ); // - in https assertEquals( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withReasonPhrase(HttpStatusCode.ACCEPTED_202.reasonPhrase()) .withBody("some_body_response"), makeRequest( request() .withMethod("POST"), headersToIgnore) ); } @Test public void shouldReturnResponseByMatchingPathAndMethodAndBody() { // when mockServerClient .when( request() .withMethod("POST") .withPath(calculatePath("some_pathRequest")) .withBody("some_bodyRequest") ) .respond( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withReasonPhrase(HttpStatusCode.ACCEPTED_202.reasonPhrase()) .withBody("some_body_response") .withHeaders(header("headerNameResponse", "headerValueResponse")) ); // then // - in http assertEquals( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withReasonPhrase(HttpStatusCode.ACCEPTED_202.reasonPhrase()) .withBody("some_body_response") .withHeaders( header("headerNameResponse", "headerValueResponse") ), makeRequest( request() .withMethod("POST") .withPath(calculatePath("some_pathRequest")) .withQueryStringParameters( param("queryStringParameterOneName", "queryStringParameterOneValue"), param("queryStringParameterTwoName", "queryStringParameterTwoValue") ) .withBody("some_bodyRequest") .withHeaders(header("headerNameRequest", "headerValueRequest")) .withCookies(cookie("cookieNameRequest", "cookieValueRequest")), headersToIgnore) ); // - in https assertEquals( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withReasonPhrase(HttpStatusCode.ACCEPTED_202.reasonPhrase()) .withBody("some_body_response") .withHeaders( header("headerNameResponse", "headerValueResponse") ), makeRequest( request() .withMethod("POST") .withSecure(true) .withPath(calculatePath("some_pathRequest")) .withQueryStringParameters( param("queryStringParameterOneName", "queryStringParameterOneValue"), param("queryStringParameterTwoName", "queryStringParameterTwoValue") ) .withBody("some_bodyRequest") .withHeaders(header("headerNameRequest", "headerValueRequest")) .withCookies(cookie("cookieNameRequest", "cookieValueRequest")), headersToIgnore) ); } @Test public void shouldReturnResponseByMatchingPathAndMethodAndQueryStringParameters() { // when mockServerClient .when( request() .withMethod("GET") .withPath(calculatePath("some_pathRequest")) .withQueryStringParameters( param("queryStringParameterOneName", "queryStringParameterOneValue"), param("queryStringParameterTwoName", "queryStringParameterTwoValue") ) ) .respond( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withReasonPhrase(HttpStatusCode.ACCEPTED_202.reasonPhrase()) .withBody("some_body_response") .withCookies(cookie("cookieNameResponse", "cookieValueResponse")) ); // then // - in http assertEquals( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withReasonPhrase(HttpStatusCode.ACCEPTED_202.reasonPhrase()) .withBody("some_body_response") .withCookies(cookie("cookieNameResponse", "cookieValueResponse")) .withHeaders( header(SET_COOKIE.toString(), "cookieNameResponse=cookieValueResponse") ), makeRequest( request() .withMethod("GET") .withPath(calculatePath("some_pathRequest")) .withQueryStringParameters( param("queryStringParameterOneName", "queryStringParameterOneValue"), param("queryStringParameterTwoName", "queryStringParameterTwoValue") ) .withHeaders(header("headerNameRequest", "headerValueRequest")) .withCookies(cookie("cookieNameRequest", "cookieValueRequest")), headersToIgnore) ); // - in https assertEquals( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withReasonPhrase(HttpStatusCode.ACCEPTED_202.reasonPhrase()) .withBody("some_body_response") .withCookies(cookie("cookieNameResponse", "cookieValueResponse")) .withHeaders( header(SET_COOKIE.toString(), "cookieNameResponse=cookieValueResponse") ), makeRequest( request() .withMethod("GET") .withSecure(true) .withPath(calculatePath("some_pathRequest")) .withQueryStringParameters( param("queryStringParameterOneName", "queryStringParameterOneValue"), param("queryStringParameterTwoName", "queryStringParameterTwoValue") ) .withHeaders(header("headerNameRequest", "headerValueRequest")) .withCookies(cookie("cookieNameRequest", "cookieValueRequest")), headersToIgnore) ); } @Test public void shouldReturnResponseByMatchingPathAndMethodAndHeaders() { // when mockServerClient .when( request() .withMethod("GET") .withPath(calculatePath("some_pathRequest")) .withHeaders( header("requestHeaderNameOne", "requestHeaderValueOne_One", "requestHeaderValueOne_Two"), header("requestHeaderNameTwo", "requestHeaderValueTwo") ) ) .respond( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withReasonPhrase(HttpStatusCode.ACCEPTED_202.reasonPhrase()) .withBody("some_body_response") .withCookies(cookie("cookieNameResponse", "cookieValueResponse")) ); // then // - in http assertEquals( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withReasonPhrase(HttpStatusCode.ACCEPTED_202.reasonPhrase()) .withBody("some_body_response") .withCookies(cookie("cookieNameResponse", "cookieValueResponse")) .withHeaders( header(SET_COOKIE.toString(), "cookieNameResponse=cookieValueResponse") ), makeRequest( request() .withMethod("GET") .withPath(calculatePath("some_pathRequest")) .withHeaders( header("requestHeaderNameOne", "requestHeaderValueOne_One", "requestHeaderValueOne_Two"), header("requestHeaderNameTwo", "requestHeaderValueTwo") ) .withCookies(cookie("cookieNameRequest", "cookieValueRequest")), headersToIgnore) ); // - in https assertEquals( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withReasonPhrase(HttpStatusCode.ACCEPTED_202.reasonPhrase()) .withBody("some_body_response") .withCookies(cookie("cookieNameResponse", "cookieValueResponse")) .withHeaders( header(SET_COOKIE.toString(), "cookieNameResponse=cookieValueResponse") ), makeRequest( request() .withMethod("GET") .withSecure(true) .withPath(calculatePath("some_pathRequest")) .withHeaders( header("requestHeaderNameOne", "requestHeaderValueOne_One", "requestHeaderValueOne_Two"), header("requestHeaderNameTwo", "requestHeaderValueTwo") ) .withCookies(cookie("cookieNameRequest", "cookieValueRequest")), headersToIgnore) ); } @Test public void shouldReturnResponseByMatchingPathAndMethodAndCookies() { // when mockServerClient .when( request() .withMethod("GET") .withPath(calculatePath("some_pathRequest")) .withCookies( cookie("requestCookieNameOne", "requestCookieValueOne"), cookie("requestCookieNameTwo", "requestCookieValueTwo") ) ) .respond( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withReasonPhrase(HttpStatusCode.ACCEPTED_202.reasonPhrase()) .withBody("some_body_response") .withCookies( cookie("responseCookieNameOne", "responseCookieValueOne"), cookie("responseCookieNameTwo", "responseCookieValueTwo") ) ); // then // - in http - cookie objects assertEquals( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withReasonPhrase(HttpStatusCode.ACCEPTED_202.reasonPhrase()) .withBody("some_body_response") .withCookies( cookie("responseCookieNameOne", "responseCookieValueOne"), cookie("responseCookieNameTwo", "responseCookieValueTwo") ) .withHeaders( header(SET_COOKIE.toString(), "responseCookieNameOne=responseCookieValueOne", "responseCookieNameTwo=responseCookieValueTwo") ), makeRequest( request() .withMethod("GET") .withPath(calculatePath("some_pathRequest")) .withHeaders( header("headerNameRequest", "headerValueRequest"), header(CONTENT_TYPE.toString(), MediaType.create("text", "plain").toString()) ) .withCookies( cookie("requestCookieNameOne", "requestCookieValueOne"), cookie("requestCookieNameTwo", "requestCookieValueTwo") ), headersToIgnore) ); // - in http - cookie header assertEquals( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withReasonPhrase(HttpStatusCode.ACCEPTED_202.reasonPhrase()) .withBody("some_body_response") .withCookies( cookie("responseCookieNameOne", "responseCookieValueOne"), cookie("responseCookieNameTwo", "responseCookieValueTwo") ) .withHeaders( header(SET_COOKIE.toString(), "responseCookieNameOne=responseCookieValueOne", "responseCookieNameTwo=responseCookieValueTwo") ), makeRequest( request() .withMethod("GET") .withPath(calculatePath("some_pathRequest")) .withHeaders( header("headerNameRequest", "headerValueRequest"), header("Cookie", "requestCookieNameOne=requestCookieValueOne; requestCookieNameTwo=requestCookieValueTwo") ), headersToIgnore) ); // - in https - cookie objects assertEquals( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withReasonPhrase(HttpStatusCode.ACCEPTED_202.reasonPhrase()) .withBody("some_body_response") .withCookies( cookie("responseCookieNameOne", "responseCookieValueOne"), cookie("responseCookieNameTwo", "responseCookieValueTwo") ) .withHeaders( header(SET_COOKIE.toString(), "responseCookieNameOne=responseCookieValueOne", "responseCookieNameTwo=responseCookieValueTwo") ), makeRequest( request() .withMethod("GET") .withSecure(true) .withPath(calculatePath("some_pathRequest")) .withHeaders( header("headerNameRequest", "headerValueRequest") ) .withCookies( cookie("requestCookieNameOne", "requestCookieValueOne"), cookie("requestCookieNameTwo", "requestCookieValueTwo") ), headersToIgnore) ); // - in https - cookie header assertEquals( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withReasonPhrase(HttpStatusCode.ACCEPTED_202.reasonPhrase()) .withBody("some_body_response") .withCookies( cookie("responseCookieNameOne", "responseCookieValueOne"), cookie("responseCookieNameTwo", "responseCookieValueTwo") ) .withHeaders( header(SET_COOKIE.toString(), "responseCookieNameOne=responseCookieValueOne", "responseCookieNameTwo=responseCookieValueTwo") ), makeRequest( request() .withMethod("GET") .withSecure(true) .withPath(calculatePath("some_pathRequest")) .withHeaders( header("headerNameRequest", "headerValueRequest"), header("Cookie", "requestCookieNameOne=requestCookieValueOne; requestCookieNameTwo=requestCookieValueTwo") ), headersToIgnore) ); } @Test public void shouldReturnResponseByMatchingPathAndMethodAndQueryStringParametersAndBodyParameters() { // when mockServerClient .when( request() .withMethod("POST") .withPath(calculatePath("some_pathRequest")) .withQueryStringParameters( param("queryStringParameterOneName", "queryStringParameterOneValueOne", "queryStringParameterOneValueTwo"), param("queryStringParameterTwoName", "queryStringParameterTwoValue") ) .withBody(params(param("bodyParameterName", "bodyParameterValue"))) ) .respond( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withReasonPhrase(HttpStatusCode.ACCEPTED_202.reasonPhrase()) .withBody("some_body") ); // then // - in http - url query string assertEquals( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withReasonPhrase(HttpStatusCode.ACCEPTED_202.reasonPhrase()) .withBody("some_body"), makeRequest( request() .withMethod("POST") .withPath(calculatePath("some_pathRequest")) .withQueryStringParameters( param("queryStringParameterOneName", "queryStringParameterOneValueOne", "queryStringParameterOneValueTwo"), param("queryStringParameterTwoName", "queryStringParameterTwoValue") ) .withBody(params(param("bodyParameterName", "bodyParameterValue"))), headersToIgnore) ); // - in https - query string parameter objects assertEquals( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withReasonPhrase(HttpStatusCode.ACCEPTED_202.reasonPhrase()) .withBody("some_body"), makeRequest( request() .withSecure(true) .withMethod("POST") .withPath(calculatePath("some_pathRequest")) .withQueryStringParameters( param("queryStringParameterOneName", "queryStringParameterOneValueOne", "queryStringParameterOneValueTwo"), param("queryStringParameterTwoName", "queryStringParameterTwoValue") ) .withBody(params(param("bodyParameterName", "bodyParameterValue"))), headersToIgnore) ); } @Test public void shouldReturnResponseByMatchingPathAndMethodAndQueryStringParametersAndBody() { // when mockServerClient .when( request() .withMethod("POST") .withPath(calculatePath("some_pathRequest")) .withQueryStringParameters( param("queryStringParameterOneName", "queryStringParameterOneValueOne", "queryStringParameterOneValueTwo"), param("queryStringParameterTwoName", "queryStringParameterTwoValue") ) .withBody("some_bodyRequest") ) .respond( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withReasonPhrase(HttpStatusCode.ACCEPTED_202.reasonPhrase()) .withBody("some_body_response") .withHeaders(header("headerNameResponse", "headerValueResponse")) .withCookies(cookie("cookieNameResponse", "cookieValueResponse")) ); // then // - in http - url query string assertEquals( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withReasonPhrase(HttpStatusCode.ACCEPTED_202.reasonPhrase()) .withBody("some_body_response") .withCookies(cookie("cookieNameResponse", "cookieValueResponse")) .withHeaders( header("headerNameResponse", "headerValueResponse"), header(SET_COOKIE.toString(), "cookieNameResponse=cookieValueResponse") ), makeRequest( request() .withMethod("POST") .withPath(calculatePath("some_pathRequest")) .withQueryStringParameters( param("queryStringParameterOneName", "queryStringParameterOneValueOne", "queryStringParameterOneValueTwo"), param("queryStringParameterTwoName", "queryStringParameterTwoValue") ) .withBody("some_bodyRequest") .withHeaders(header("headerNameRequest", "headerValueRequest")) .withCookies(cookie("cookieNameRequest", "cookieValueRequest")), headersToIgnore) ); // - in http - query string parameter objects assertEquals( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withReasonPhrase(HttpStatusCode.ACCEPTED_202.reasonPhrase()) .withBody("some_body_response") .withCookies(cookie("cookieNameResponse", "cookieValueResponse")) .withHeaders( header("headerNameResponse", "headerValueResponse"), header(SET_COOKIE.toString(), "cookieNameResponse=cookieValueResponse") ), makeRequest( request() .withMethod("POST") .withPath(calculatePath("some_pathRequest")) .withQueryStringParameters( param("queryStringParameterOneName", "queryStringParameterOneValueOne", "queryStringParameterOneValueTwo"), param("queryStringParameterTwoName", "queryStringParameterTwoValue") ) .withBody("some_bodyRequest") .withHeaders(header("headerNameRequest", "headerValueRequest")) .withCookies(cookie("cookieNameRequest", "cookieValueRequest")), headersToIgnore) ); // - in https - url string and query string parameter objects assertEquals( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withReasonPhrase(HttpStatusCode.ACCEPTED_202.reasonPhrase()) .withBody("some_body_response") .withCookies(cookie("cookieNameResponse", "cookieValueResponse")) .withHeaders( header("headerNameResponse", "headerValueResponse"), header(SET_COOKIE.toString(), "cookieNameResponse=cookieValueResponse") ), makeRequest( request() .withMethod("POST") .withPath(calculatePath("some_pathRequest")) .withQueryStringParameters( param("queryStringParameterOneName", "queryStringParameterOneValueOne", "queryStringParameterOneValueTwo"), param("queryStringParameterTwoName", "queryStringParameterTwoValue") ) .withBody("some_bodyRequest") .withHeaders(header("headerNameRequest", "headerValueRequest")) .withCookies(cookie("cookieNameRequest", "cookieValueRequest")), headersToIgnore) ); } @Test public void shouldReturnResponseByMatchingPathAndMethodAndBodyParameters() { // when mockServerClient .when( request() .withMethod("POST") .withPath(calculatePath("some_pathRequest")) .withBody(params( param("bodyParameterOneName", "Parameter One Value One", "Parameter One Value Two"), param("bodyParameterTwoName", "Parameter Two") )) ) .respond( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withReasonPhrase(HttpStatusCode.ACCEPTED_202.reasonPhrase()) .withBody("some_body_response") .withHeaders(header("headerNameResponse", "headerValueResponse")) .withCookies(cookie("cookieNameResponse", "cookieValueResponse")) ); // then // - in http - body string assertEquals( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withReasonPhrase(HttpStatusCode.ACCEPTED_202.reasonPhrase()) .withBody("some_body_response") .withCookies(cookie("cookieNameResponse", "cookieValueResponse")) .withHeaders( header("headerNameResponse", "headerValueResponse"), header(SET_COOKIE.toString(), "cookieNameResponse=cookieValueResponse") ), makeRequest( request() .withMethod("POST") .withPath(calculatePath("some_pathRequest")) .withBody(new StringBody("bodyParameterOneName=Parameter+One+Value+One" + "&bodyParameterOneName=Parameter+One+Value+Two" + "&bodyParameterTwoName=Parameter+Two")) .withHeaders(header("headerNameRequest", "headerValueRequest")) .withCookies(cookie("cookieNameRequest", "cookieValueRequest")), headersToIgnore) ); // - in http - body parameter objects assertEquals( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withReasonPhrase(HttpStatusCode.ACCEPTED_202.reasonPhrase()) .withBody("some_body_response") .withCookies(cookie("cookieNameResponse", "cookieValueResponse")) .withHeaders( header("headerNameResponse", "headerValueResponse"), header(SET_COOKIE.toString(), "cookieNameResponse=cookieValueResponse") ), makeRequest( request() .withMethod("POST") .withPath(calculatePath("some_pathRequest")) .withBody(params( param("bodyParameterOneName", "Parameter One Value One", "Parameter One Value Two"), param("bodyParameterTwoName", "Parameter Two") )) .withHeaders(header("headerNameRequest", "headerValueRequest")) .withCookies(cookie("cookieNameRequest", "cookieValueRequest")), headersToIgnore) ); // - in https - url string and query string parameter objects assertEquals( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withReasonPhrase(HttpStatusCode.ACCEPTED_202.reasonPhrase()) .withBody("some_body_response") .withCookies(cookie("cookieNameResponse", "cookieValueResponse")) .withHeaders( header("headerNameResponse", "headerValueResponse"), header(SET_COOKIE.toString(), "cookieNameResponse=cookieValueResponse") ), makeRequest( request() .withMethod("POST") .withPath(calculatePath("some_pathRequest")) .withBody(params( param("bodyParameterOneName", "Parameter One Value One", "Parameter One Value Two"), param("bodyParameterTwoName", "Parameter Two") )) .withHeaders(header("headerNameRequest", "headerValueRequest")) .withCookies(cookie("cookieNameRequest", "cookieValueRequest")), headersToIgnore) ); } @Test public void shouldReturnResponseByMatchingPathAndMethodAndParametersAndHeadersAndCookies() { // when mockServerClient .when( request() .withMethod("PUT") .withPath(calculatePath("some_pathRequest")) .withBody(new StringBody("bodyParameterOneName=Parameter+One+Value+One" + "&bodyParameterOneName=Parameter+One+Value+Two" + "&bodyParameterTwoName=Parameter+Two")) .withHeaders(header("headerNameRequest", "headerValueRequest")) .withCookies(cookie("cookieNameRequest", "cookieValueRequest")) ) .respond( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withReasonPhrase(HttpStatusCode.ACCEPTED_202.reasonPhrase()) .withBody("some_body_response") .withHeaders(header("headerNameResponse", "headerValueResponse")) .withCookies(cookie("cookieNameResponse", "cookieValueResponse")) ); // then // - in http - body string assertEquals( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withReasonPhrase(HttpStatusCode.ACCEPTED_202.reasonPhrase()) .withBody("some_body_response") .withCookies(cookie("cookieNameResponse", "cookieValueResponse")) .withHeaders( header("headerNameResponse", "headerValueResponse"), header(SET_COOKIE.toString(), "cookieNameResponse=cookieValueResponse") ), makeRequest( request() .withMethod("PUT") .withPath(calculatePath("some_pathRequest")) .withBody(new StringBody("bodyParameterOneName=Parameter+One+Value+One" + "&bodyParameterOneName=Parameter+One+Value+Two" + "&bodyParameterTwoName=Parameter+Two")) .withHeaders( header("headerNameRequest", "headerValueRequest"), header("Cookie", "cookieNameRequest=cookieValueRequest") ), headersToIgnore) ); // - in http - body parameter objects assertEquals( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withReasonPhrase(HttpStatusCode.ACCEPTED_202.reasonPhrase()) .withBody("some_body_response") .withCookies(cookie("cookieNameResponse", "cookieValueResponse")) .withHeaders( header("headerNameResponse", "headerValueResponse"), header(SET_COOKIE.toString(), "cookieNameResponse=cookieValueResponse") ), makeRequest( request() .withMethod("PUT") .withPath(calculatePath("some_pathRequest")) .withBody(params( param("bodyParameterOneName", "Parameter One Value One", "Parameter One Value Two"), param("bodyParameterTwoName", "Parameter Two") )) .withHeaders(header("headerNameRequest", "headerValueRequest")) .withCookies(cookie("cookieNameRequest", "cookieValueRequest")), headersToIgnore) ); } @Test public void shouldReturnResponseByNotMatchingBodyParameterWithNotOperatorForNameAndValue() { // when mockServerClient .when( request() .withMethod("POST") .withPath(calculatePath("some_pathRequest")) .withBody(params( param(not("bodyParameterOneName"), not("Parameter One Value One"), not("Parameter One Value Two")), param("bodyParameterTwoName", "Parameter Two") )) ) .respond( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withReasonPhrase(HttpStatusCode.ACCEPTED_202.reasonPhrase()) .withBody("some_body_response") ); // then // wrong query string parameter name assertEquals( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withReasonPhrase(HttpStatusCode.ACCEPTED_202.reasonPhrase()) .withBody("some_body_response"), makeRequest( request() .withMethod("POST") .withPath(calculatePath("some_pathRequest")) .withBody(params( param("OTHERBodyParameterOneName", "Parameter One Value One", "Parameter One Value Two"), param("bodyParameterTwoName", "Parameter Two") )) .withHeaders(header("headerNameRequest", "headerValueRequest")) .withCookies(cookie("cookieNameRequest", "cookieValueRequest")), headersToIgnore) ); // wrong query string parameter name assertEquals( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withReasonPhrase(HttpStatusCode.ACCEPTED_202.reasonPhrase()) .withBody("some_body_response"), makeRequest( request() .withMethod("POST") .withPath(calculatePath("some_pathRequest")) .withBody(new StringBody("OTHERBodyParameterOneName=Parameter+One+Value+One" + "&OTHERBodyParameterOneName=Parameter+One+Value+Two" + "&bodyParameterTwoName=Parameter+Two")) .withHeaders(header("headerNameRequest", "headerValueRequest")) .withCookies(cookie("cookieNameRequest", "cookieValueRequest")), headersToIgnore) ); // wrong query string parameter value assertEquals( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withReasonPhrase(HttpStatusCode.ACCEPTED_202.reasonPhrase()) .withBody("some_body_response"), makeRequest( request() .withMethod("POST") .withPath(calculatePath("some_pathRequest")) .withBody(params( param("bodyParameterOneName", "OTHER Parameter One Value One", "OTHER Parameter One Value Two"), param("bodyParameterTwoName", "Parameter Two") )) .withHeaders(header("headerNameRequest", "headerValueRequest")) .withCookies(cookie("cookieNameRequest", "cookieValueRequest")), headersToIgnore) ); // wrong query string parameter value assertEquals( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withReasonPhrase(HttpStatusCode.ACCEPTED_202.reasonPhrase()) .withBody("some_body_response"), makeRequest( request() .withMethod("POST") .withPath(calculatePath("some_pathRequest")) .withBody(new StringBody("bodyParameterOneName=OTHER Parameter+One+Value+One" + "&bodyParameterOneName=OTHER Parameter+One+Value+Two" + "&bodyParameterTwoName=Parameter+Two")) .withHeaders(header("headerNameRequest", "headerValueRequest")) .withCookies(cookie("cookieNameRequest", "cookieValueRequest")), headersToIgnore) ); } @Test public void shouldReturnResponseByNotMatchingBodyParameterWithNotOperatorForName() { // when mockServerClient .when( request() .withMethod("POST") .withPath(calculatePath("some_pathRequest")) .withBody(params( param(not("bodyParameterOneName"), string("Parameter One Value One"), string("Parameter One Value Two")), param("bodyParameterTwoName", "Parameter Two") )) ) .respond( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withReasonPhrase(HttpStatusCode.ACCEPTED_202.reasonPhrase()) .withBody("some_body_response") ); // then // wrong query string parameter name assertEquals( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withReasonPhrase(HttpStatusCode.ACCEPTED_202.reasonPhrase()) .withBody("some_body_response"), makeRequest( request() .withMethod("POST") .withPath(calculatePath("some_pathRequest")) .withBody(params( param("OTHERBodyParameterOneName", "Parameter One Value One", "Parameter One Value Two"), param("bodyParameterTwoName", "Parameter Two") )) .withHeaders(header("headerNameRequest", "headerValueRequest")) .withCookies(cookie("cookieNameRequest", "cookieValueRequest")), headersToIgnore) ); // wrong query string parameter name assertEquals( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withReasonPhrase(HttpStatusCode.ACCEPTED_202.reasonPhrase()) .withBody("some_body_response"), makeRequest( request() .withMethod("POST") .withPath(calculatePath("some_pathRequest")) .withBody(new StringBody("OTHERBodyParameterOneName=Parameter+One+Value+One" + "&OTHERBodyParameterOneName=Parameter+One+Value+Two" + "&bodyParameterTwoName=Parameter+Two")) .withHeaders(header("headerNameRequest", "headerValueRequest")) .withCookies(cookie("cookieNameRequest", "cookieValueRequest")), headersToIgnore) ); } @Test public void shouldReturnResponseByNotMatchingBodyParameterWithNotOperatorForValue() { // when mockServerClient .when( request() .withMethod("POST") .withPath(calculatePath("some_pathRequest")) .withBody(params( param(string("bodyParameterOneName"), not("Parameter One Value One"), not("Parameter One Value Two")), param("bodyParameterTwoName", "Parameter Two") )) ) .respond( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withReasonPhrase(HttpStatusCode.ACCEPTED_202.reasonPhrase()) .withBody("some_body_response") ); // then // wrong query string parameter value assertEquals( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withReasonPhrase(HttpStatusCode.ACCEPTED_202.reasonPhrase()) .withBody("some_body_response"), makeRequest( request() .withMethod("POST") .withPath(calculatePath("some_pathRequest")) .withBody(params( param("bodyParameterOneName", "OTHER Parameter One Value One", "OTHER Parameter One Value Two"), param("bodyParameterTwoName", "Parameter Two") )) .withHeaders(header("headerNameRequest", "headerValueRequest")) .withCookies(cookie("cookieNameRequest", "cookieValueRequest")), headersToIgnore) ); // wrong query string parameter value assertEquals( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withReasonPhrase(HttpStatusCode.ACCEPTED_202.reasonPhrase()) .withBody("some_body_response"), makeRequest( request() .withMethod("POST") .withPath(calculatePath("some_pathRequest")) .withBody(new StringBody("bodyParameterOneName=OTHER Parameter+One+Value+One" + "&bodyParameterOneName=OTHER Parameter+One+Value+Two" + "&bodyParameterTwoName=Parameter+Two")) .withHeaders(header("headerNameRequest", "headerValueRequest")) .withCookies(cookie("cookieNameRequest", "cookieValueRequest")), headersToIgnore) ); } @Test public void shouldReturnResponseByNotMatchingQueryStringParameterWithNotOperatorForNameAndValue() { // when mockServerClient .when( request() .withMethod("POST") .withPath(calculatePath("some_pathRequest")) .withQueryStringParameters( param(not("queryStringParameterOneName"), not("Parameter One Value One"), not("Parameter One Value Two")), param("queryStringParameterTwoName", "Parameter Two") ) ) .respond( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withReasonPhrase(HttpStatusCode.ACCEPTED_202.reasonPhrase()) .withBody("some_body_response") ); // then // wrong query string parameter name assertEquals( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withReasonPhrase(HttpStatusCode.ACCEPTED_202.reasonPhrase()) .withBody("some_body_response"), makeRequest( request() .withMethod("POST") .withPath(calculatePath("some_pathRequest")) .withQueryStringParameters( param("OTHERQueryStringParameterOneName", "Parameter One Value One", "Parameter One Value Two"), param("queryStringParameterTwoName", "Parameter Two") ), headersToIgnore) ); // wrong query string parameter value assertEquals( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withReasonPhrase(HttpStatusCode.ACCEPTED_202.reasonPhrase()) .withBody("some_body_response"), makeRequest( request() .withMethod("POST") .withPath(calculatePath("some_pathRequest")) .withQueryStringParameters( param("queryStringParameterOneName", "OTHER Parameter One Value One", "OTHER Parameter One Value Two"), param("queryStringParameterTwoName", "Parameter Two") ), headersToIgnore) ); } @Test public void shouldReturnResponseByNotMatchingQueryStringParameterWithNotOperatorForName() { // when mockServerClient .when( request() .withMethod("POST") .withPath(calculatePath("some_pathRequest")) .withQueryStringParameters( param(not("queryStringParameterOneName"), string("Parameter One Value One"), string("Parameter One Value Two")), param("queryStringParameterTwoName", "Parameter Two") ) ) .respond( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withReasonPhrase(HttpStatusCode.ACCEPTED_202.reasonPhrase()) .withBody("some_body_response") ); // then // wrong query string parameter name assertEquals( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withReasonPhrase(HttpStatusCode.ACCEPTED_202.reasonPhrase()) .withBody("some_body_response"), makeRequest( request() .withMethod("POST") .withPath(calculatePath("some_pathRequest")) .withQueryStringParameters( param("OTHERQueryStringParameterOneName", "Parameter One Value One", "Parameter One Value Two"), param("queryStringParameterTwoName", "Parameter Two") ), headersToIgnore) ); } @Test public void shouldReturnResponseByNotMatchingQueryStringParameterWithNotOperatorForValue() { // when mockServerClient .when( request() .withMethod("POST") .withPath(calculatePath("some_pathRequest")) .withQueryStringParameters( param(string("queryStringParameterOneName"), not("Parameter One Value One"), not("Parameter One Value Two")), param("queryStringParameterTwoName", "Parameter Two") ) ) .respond( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withReasonPhrase(HttpStatusCode.ACCEPTED_202.reasonPhrase()) .withBody("some_body_response") ); // then // wrong query string parameter value assertEquals( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withReasonPhrase(HttpStatusCode.ACCEPTED_202.reasonPhrase()) .withBody("some_body_response"), makeRequest( request() .withMethod("POST") .withPath(calculatePath("some_pathRequest")) .withQueryStringParameters( param("queryStringParameterOneName", "OTHER Parameter One Value One", "OTHER Parameter One Value Two"), param("queryStringParameterTwoName", "Parameter Two") ), headersToIgnore) ); } @Test public void shouldReturnResponseByNotMatchingCookieWithNotOperatorForNameAndValue() { // when mockServerClient .when( request() .withMethod("GET") .withPath(calculatePath("some_pathRequest")) .withCookies( cookie(not("requestCookieNameOne"), not("requestCookieValueOne")), cookie("requestCookieNameTwo", "requestCookieValueTwo") ) ) .respond( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withReasonPhrase(HttpStatusCode.ACCEPTED_202.reasonPhrase()) .withBody("some_body_response") ); // then // wrong query string cookie name assertEquals( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withReasonPhrase(HttpStatusCode.ACCEPTED_202.reasonPhrase()) .withBody("some_body_response"), makeRequest( request() .withMethod("GET") .withPath(calculatePath("some_pathRequest")) .withCookies( cookie("OTHERrequestCookieNameOne", "requestCookieValueOne"), cookie("requestCookieNameTwo", "requestCookieValueTwo") ), headersToIgnore) ); // wrong query string cookie value assertEquals( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withReasonPhrase(HttpStatusCode.ACCEPTED_202.reasonPhrase()) .withBody("some_body_response"), makeRequest( request() .withMethod("GET") .withPath(calculatePath("some_pathRequest")) .withCookies( cookie("requestCookieNameOne", "OTHERrequestCookieValueOne"), cookie("requestCookieNameTwo", "requestCookieValueTwo") ), headersToIgnore) ); } @Test public void shouldReturnResponseByNotMatchingCookieWithNotOperatorForName() { // when mockServerClient .when( request() .withMethod("GET") .withPath(calculatePath("some_pathRequest")) .withCookies( cookie(not("requestCookieNameOne"), string("requestCookieValueOne")), cookie("requestCookieNameTwo", "requestCookieValueTwo") ) ) .respond( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withReasonPhrase(HttpStatusCode.ACCEPTED_202.reasonPhrase()) .withBody("some_body_response") ); // then // wrong query string cookie name assertEquals( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withReasonPhrase(HttpStatusCode.ACCEPTED_202.reasonPhrase()) .withBody("some_body_response"), makeRequest( request() .withMethod("GET") .withPath(calculatePath("some_pathRequest")) .withCookies( cookie("OTHERrequestCookieNameOne", "requestCookieValueOne"), cookie("requestCookieNameTwo", "requestCookieValueTwo") ), headersToIgnore) ); } @Test public void shouldReturnResponseByNotMatchingCookieWithNotOperatorForValue() { // when mockServerClient .when( request() .withMethod("GET") .withPath(calculatePath("some_pathRequest")) .withCookies( cookie(string("requestCookieNameOne"), not("requestCookieValueOne")), cookie("requestCookieNameTwo", "requestCookieValueTwo") ) ) .respond( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withReasonPhrase(HttpStatusCode.ACCEPTED_202.reasonPhrase()) .withBody("some_body_response") ); // then // wrong query string cookie value assertEquals( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withReasonPhrase(HttpStatusCode.ACCEPTED_202.reasonPhrase()) .withBody("some_body_response"), makeRequest( request() .withMethod("GET") .withPath(calculatePath("some_pathRequest")) .withCookies( cookie("requestCookieNameOne", "OTHERrequestCookieValueOne"), cookie("requestCookieNameTwo", "requestCookieValueTwo") ), headersToIgnore) ); } @Test public void shouldReturnResponseByNotMatchingHeaderWithNotOperatorForNameAndValue() { // when mockServerClient .when( request() .withMethod("GET") .withPath(calculatePath("some_pathRequest")) .withHeaders( header(not("requestHeaderNameOne"), not("requestHeaderValueOne")), header("requestHeaderNameTwo", "requestHeaderValueTwo") ) ) .respond( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withReasonPhrase(HttpStatusCode.ACCEPTED_202.reasonPhrase()) .withBody("some_body_response") ); // then // wrong query string header name assertEquals( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withReasonPhrase(HttpStatusCode.ACCEPTED_202.reasonPhrase()) .withBody("some_body_response"), makeRequest( request() .withMethod("GET") .withPath(calculatePath("some_pathRequest")) .withHeaders( header("OTHERrequestHeaderNameOne", "requestHeaderValueOne"), header("requestHeaderNameTwo", "requestHeaderValueTwo") ), headersToIgnore) ); // wrong query string header value assertEquals( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withReasonPhrase(HttpStatusCode.ACCEPTED_202.reasonPhrase()) .withBody("some_body_response"), makeRequest( request() .withMethod("GET") .withPath(calculatePath("some_pathRequest")) .withHeaders( header("requestHeaderNameOne", "OTHERrequestHeaderValueOne"), header("requestHeaderNameTwo", "requestHeaderValueTwo") ), headersToIgnore) ); } @Test public void shouldReturnResponseByNotMatchingHeaderWithNotOperatorForName() { // when mockServerClient .when( request() .withMethod("GET") .withPath(calculatePath("some_pathRequest")) .withHeaders( header(not("requestHeaderNameOne"), string("requestHeaderValueOne")), header("requestHeaderNameTwo", "requestHeaderValueTwo") ) ) .respond( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withReasonPhrase(HttpStatusCode.ACCEPTED_202.reasonPhrase()) .withBody("some_body_response") ); // then // wrong query string header name assertEquals( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withReasonPhrase(HttpStatusCode.ACCEPTED_202.reasonPhrase()) .withBody("some_body_response"), makeRequest( request() .withMethod("GET") .withPath(calculatePath("some_pathRequest")) .withHeaders( header("OTHERrequestHeaderNameOne", "requestHeaderValueOne"), header("requestHeaderNameTwo", "requestHeaderValueTwo") ), headersToIgnore) ); } @Test public void shouldReturnResponseByNotMatchingHeaderWithNotOperatorForValue() { // when mockServerClient .when( request() .withMethod("GET") .withPath(calculatePath("some_pathRequest")) .withHeaders( header(string("requestHeaderNameOne"), not("requestHeaderValueOne")), header("requestHeaderNameTwo", "requestHeaderValueTwo") ) ) .respond( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withReasonPhrase(HttpStatusCode.ACCEPTED_202.reasonPhrase()) .withBody("some_body_response") ); // then // wrong query string header value assertEquals( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withReasonPhrase(HttpStatusCode.ACCEPTED_202.reasonPhrase()) .withBody("some_body_response"), makeRequest( request() .withMethod("GET") .withPath(calculatePath("some_pathRequest")) .withHeaders( header("requestHeaderNameOne", "OTHERrequestHeaderValueOne"), header("requestHeaderNameTwo", "requestHeaderValueTwo") ), headersToIgnore) ); } @Test public void shouldNotReturnResponseForWhenTimeToLiveExpired() { // when mockServerClient .when( request().withPath(calculatePath("some_path")), exactly(2), TimeToLive.exactly(TimeUnit.SECONDS, 3L) ) .respond( response().withBody("some_body").withDelay(TimeUnit.SECONDS, 3L) ); // then assertEquals( response() .withStatusCode(OK_200.code()) .withReasonPhrase(OK_200.reasonPhrase()) .withBody("some_body"), makeRequest( request() .withPath(calculatePath("some_path")), headersToIgnore) ); // - in http assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()) .withReasonPhrase(HttpStatusCode.NOT_FOUND_404.reasonPhrase()), makeRequest( request() .withPath(calculatePath("some_path")), headersToIgnore) ); // - in https assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()) .withReasonPhrase(HttpStatusCode.NOT_FOUND_404.reasonPhrase()), makeRequest( request() .withSecure(true) .withPath(calculatePath("some_path")), headersToIgnore) ); } @Test public void shouldNotReturnResponseForMatchingBodyWithNotOperator() { // when mockServerClient .when( request() .withBody(Not.not(json("{" + NEW_LINE + " \"id\": 1," + NEW_LINE + " \"name\": \"A green door\"," + NEW_LINE + " \"price\": 12.50," + NEW_LINE + " \"tags\": [\"home\", \"green\"]" + NEW_LINE + "}"))), exactly(2) ) .respond( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withReasonPhrase(HttpStatusCode.ACCEPTED_202.reasonPhrase()) .withBody("some_body") ); // then // - in http assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()) .withReasonPhrase(HttpStatusCode.NOT_FOUND_404.reasonPhrase()), makeRequest( request() .withPath(calculatePath("some_path")) .withMethod("POST") .withBody("{" + NEW_LINE + " \"id\": 1," + NEW_LINE + " \"extra_ignored_field\": \"some value\"," + NEW_LINE + " \"name\": \"A green door\"," + NEW_LINE + " \"price\": 12.50," + NEW_LINE + " \"tags\": [\"home\", \"green\"]" + NEW_LINE + "}"), headersToIgnore) ); // - in https assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()) .withReasonPhrase(HttpStatusCode.NOT_FOUND_404.reasonPhrase()), makeRequest( request() .withSecure(true) .withPath(calculatePath("some_path")) .withMethod("POST") .withBody("{" + NEW_LINE + " \"id\": 1," + NEW_LINE + " \"extra_ignored_array\": [\"one\", \"two\"]," + NEW_LINE + " \"name\": \"A green door\"," + NEW_LINE + " \"price\": 12.50," + NEW_LINE + " \"tags\": [\"home\", \"green\"]" + NEW_LINE + "}"), headersToIgnore) ); } @Test public void shouldNotReturnResponseForNonMatchingXPathBody() { // when mockServerClient.when(request().withBody(new XPathBody("/bookstore/book[price>35]/price")), exactly(2)).respond(response().withBody("some_body")); // then // - in http assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()) .withReasonPhrase(HttpStatusCode.NOT_FOUND_404.reasonPhrase()), makeRequest( request() .withSecure(true) .withPath(calculatePath("some_path")) .withMethod("POST") .withBody(new StringBody("" + "<?xml version=\"1.0\" encoding=\"ISO-8859-1\"?>" + NEW_LINE + "<bookstore>" + NEW_LINE + " <book category=\"COOKING\">" + NEW_LINE + " <title lang=\"en\">Everyday Italian</title>" + NEW_LINE + " <author>Giada De Laurentiis</author>" + NEW_LINE + " <year>2005</year>" + NEW_LINE + " <price>30.00</price>" + NEW_LINE + " </book>" + NEW_LINE + " <book category=\"CHILDREN\">" + NEW_LINE + " <title lang=\"en\">Harry Potter</title>" + NEW_LINE + " <author>J K. Rowling</author>" + NEW_LINE + " <year>2005</year>" + NEW_LINE + " <price>29.99</price>" + NEW_LINE + " </book>" + NEW_LINE + " <book category=\"WEB\">" + NEW_LINE + " <title lang=\"en\">Learning XML</title>" + NEW_LINE + " <author>Erik T. Ray</author>" + NEW_LINE + " <year>2003</year>" + NEW_LINE + " <price>31.95</price>" + NEW_LINE + " </book>" + NEW_LINE + "</bookstore>")), headersToIgnore) ); // - in https assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()) .withReasonPhrase(HttpStatusCode.NOT_FOUND_404.reasonPhrase()), makeRequest( request() .withSecure(true) .withPath(calculatePath("some_path")) .withMethod("POST") .withBody(new StringBody("" + "<?xml version=\"1.0\" encoding=\"ISO-8859-1\"?>" + NEW_LINE + "<bookstore>" + NEW_LINE + " <book category=\"COOKING\">" + NEW_LINE + " <title lang=\"en\">Everyday Italian</title>" + NEW_LINE + " <author>Giada De Laurentiis</author>" + NEW_LINE + " <year>2005</year>" + NEW_LINE + " <price>30.00</price>" + NEW_LINE + " </book>" + NEW_LINE + " <book category=\"CHILDREN\">" + NEW_LINE + " <title lang=\"en\">Harry Potter</title>" + NEW_LINE + " <author>J K. Rowling</author>" + NEW_LINE + " <year>2005</year>" + NEW_LINE + " <price>29.99</price>" + NEW_LINE + " </book>" + NEW_LINE + " <book category=\"WEB\">" + NEW_LINE + " <title lang=\"en\">Learning XML</title>" + NEW_LINE + " <author>Erik T. Ray</author>" + NEW_LINE + " <year>2003</year>" + NEW_LINE + " <price>31.95</price>" + NEW_LINE + " </book>" + NEW_LINE + "</bookstore>")), headersToIgnore) ); } @Test public void shouldNotReturnResponseForNonMatchingXmlBody() { // when mockServerClient.when(request().withBody(xml("" + "<?xml version=\"1.0\" encoding=\"ISO-8859-1\"?>" + NEW_LINE + "<bookstore>" + NEW_LINE + " <book category=\"COOKING\" nationality=\"ITALIAN\">" + NEW_LINE + " <title lang=\"en\">Everyday Italian</title>" + NEW_LINE + " <author>Giada De Laurentiis</author>" + NEW_LINE + " <year>2005</year>" + NEW_LINE + " <price>30.00</price>" + NEW_LINE + " </book>" + NEW_LINE + "</bookstore>")), exactly(2)).respond(response().withBody("some_body")); // then // - in http assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()) .withReasonPhrase(HttpStatusCode.NOT_FOUND_404.reasonPhrase()), makeRequest( request() .withSecure(true) .withPath(calculatePath("some_path")) .withMethod("POST") .withBody(new StringBody("" + "<?xml version=\"1.0\" encoding=\"ISO-8859-1\"?>" + NEW_LINE + "<bookstore>" + NEW_LINE + " <book category=\"COOKING\">" + NEW_LINE + " <title lang=\"en\">Everyday Italian</title>" + NEW_LINE + " <author>Giada De Laurentiis</author>" + NEW_LINE + " <year>2005</year>" + NEW_LINE + " <price>30.00</price>" + NEW_LINE + " </book>" + NEW_LINE + "</bookstore>")), headersToIgnore) ); // - in https assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()) .withReasonPhrase(HttpStatusCode.NOT_FOUND_404.reasonPhrase()), makeRequest( request() .withSecure(true) .withPath(calculatePath("some_path")) .withMethod("POST") .withBody(new StringBody("" + "<?xml version=\"1.0\" encoding=\"ISO-8859-1\"?>" + NEW_LINE + "<bookstore>" + NEW_LINE + " <book category=\"COOKING\">" + NEW_LINE + " <title lang=\"en\">Everyday Italian</title>" + NEW_LINE + " <author>Giada De Laurentiis</author>" + NEW_LINE + " <year>2005</year>" + NEW_LINE + " <price>30.00</price>" + NEW_LINE + " </book>" + NEW_LINE + "</bookstore>")), headersToIgnore) ); } @Test public void shouldNotReturnResponseForNonMatchingJsonBody() { // when mockServerClient.when(request().withBody(json("{" + NEW_LINE + " \"id\": 1," + NEW_LINE + " \"name\": \"A green door\"," + NEW_LINE + " \"price\": 12.50," + NEW_LINE + " \"tags\": [\"home\", \"green\"]" + NEW_LINE + "}")), exactly(2)).respond(response().withBody("some_body")); // then // - in http assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()) .withReasonPhrase(HttpStatusCode.NOT_FOUND_404.reasonPhrase()), makeRequest( request() .withPath(calculatePath("some_path")) .withMethod("POST") .withBody("{" + NEW_LINE + " \"id\": 1," + NEW_LINE + " \"name\": \"---- XXXX WRONG VALUE XXXX ----\"," + NEW_LINE + " \"price\": 12.50," + NEW_LINE + " \"tags\": [\"home\", \"green\"]" + NEW_LINE + "}"), headersToIgnore) ); // - in https assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()) .withReasonPhrase(HttpStatusCode.NOT_FOUND_404.reasonPhrase()), makeRequest( request() .withSecure(true) .withPath(calculatePath("some_path")) .withMethod("POST") .withBody("{" + NEW_LINE + " \"id\": 1," + NEW_LINE + " \"name\": \"---- XXXX WRONG VALUE XXXX ----\"," + NEW_LINE + " \"price\": 12.50," + NEW_LINE + " \"tags\": [\"home\", \"green\"]" + NEW_LINE + "}"), headersToIgnore) ); } @Test public void shouldNotReturnResponseForNonMatchingJsonBodyWithMatchType() { // when mockServerClient .when( request() .withBody(json("{" + NEW_LINE + " \"id\": 1," + NEW_LINE + " \"name\": \"A green door\"," + NEW_LINE + " \"price\": 12.50," + NEW_LINE + " \"tags\": [\"home\", \"green\"]" + NEW_LINE + "}", MatchType.STRICT)), exactly(2)) .respond( response() .withBody("some_body") ); // then // - in http assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()) .withReasonPhrase(HttpStatusCode.NOT_FOUND_404.reasonPhrase()), makeRequest( request() .withPath(calculatePath("some_path")) .withMethod("POST") .withBody("{" + NEW_LINE + " \"id\": 1," + NEW_LINE + " \"extra field\": \"some value\"," + NEW_LINE + " \"name\": \"A green door\"," + NEW_LINE + " \"price\": 12.50," + NEW_LINE + " \"tags\": [\"home\", \"green\"]" + NEW_LINE + "}"), headersToIgnore) ); // - in https assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()) .withReasonPhrase(HttpStatusCode.NOT_FOUND_404.reasonPhrase()), makeRequest( request() .withSecure(true) .withPath(calculatePath("some_path")) .withMethod("POST") .withBody("{" + NEW_LINE + " \"id\": 1," + NEW_LINE + " \"extra field\": \"some value\"," + NEW_LINE + " \"name\": \"A green door\"," + NEW_LINE + " \"price\": 12.50," + NEW_LINE + " \"tags\": [\"home\", \"green\"]" + NEW_LINE + "}"), headersToIgnore) ); } @Test public void shouldNotReturnResponseForNonMatchingJsonSchema() { // when mockServerClient.when(request().withBody(jsonSchema("{" + NEW_LINE + " \"$schema\": \"http://json-schema.org/draft-04/schema#\"," + NEW_LINE + " \"title\": \"Product\"," + NEW_LINE + " \"description\": \"A product from Acme's catalog\"," + NEW_LINE + " \"type\": \"object\"," + NEW_LINE + " \"properties\": {" + NEW_LINE + " \"id\": {" + NEW_LINE + " \"description\": \"The unique identifier for a product\"," + NEW_LINE + " \"type\": \"integer\"" + NEW_LINE + " }," + NEW_LINE + " \"name\": {" + NEW_LINE + " \"description\": \"Name of the product\"," + NEW_LINE + " \"type\": \"string\"" + NEW_LINE + " }," + NEW_LINE + " \"price\": {" + NEW_LINE + " \"type\": \"number\"," + NEW_LINE + " \"minimum\": 0," + NEW_LINE + " \"exclusiveMinimum\": true" + NEW_LINE + " }," + NEW_LINE + " \"tags\": {" + NEW_LINE + " \"type\": \"array\"," + NEW_LINE + " \"items\": {" + NEW_LINE + " \"type\": \"string\"" + NEW_LINE + " }," + NEW_LINE + " \"minItems\": 1," + NEW_LINE + " \"uniqueItems\": true" + NEW_LINE + " }" + NEW_LINE + " }," + NEW_LINE + " \"required\": [\"id\", \"name\", \"price\"]" + NEW_LINE + "}")), exactly(2)).respond(response().withBody("some_body")); // then // - in http assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()) .withReasonPhrase(HttpStatusCode.NOT_FOUND_404.reasonPhrase()), makeRequest( request() .withPath(calculatePath("some_path")) .withMethod("POST") .withBody("{" + NEW_LINE + " \"id\": 1," + NEW_LINE + " \"wrong field name\": \"A green door\"," + NEW_LINE + " \"price\": 12.50," + NEW_LINE + " \"tags\": [\"home\", \"green\"]" + NEW_LINE + "}"), headersToIgnore) ); // - in https assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()) .withReasonPhrase(HttpStatusCode.NOT_FOUND_404.reasonPhrase()), makeRequest( request() .withSecure(true) .withPath(calculatePath("some_path")) .withMethod("POST") .withBody("{" + NEW_LINE + " \"id\": 1," + NEW_LINE + " \"name\": \"A green door\"," + NEW_LINE + " \"wrong field name\": 12.50," + NEW_LINE + " \"tags\": [\"home\", \"green\"]" + NEW_LINE + "}"), headersToIgnore) ); } @Test public void shouldNotReturnResponseForNonMatchingJsonPathBody() { // when mockServerClient.when(request().withBody(new JsonPathBody("$..book[?(@.price > $['expensive'])]")), exactly(2)).respond(response().withBody("some_body")); // then // - in http assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()) .withReasonPhrase(HttpStatusCode.NOT_FOUND_404.reasonPhrase()), makeRequest( request() .withSecure(true) .withPath(calculatePath("some_path")) .withMethod("POST") .withBody(new StringBody("" + "{\n" + " \"store\": {\n" + " \"book\": [\n" + " {\n" + " \"category\": \"reference\",\n" + " \"author\": \"Nigel Rees\",\n" + " \"title\": \"Sayings of the Century\",\n" + " \"price\": 8.95\n" + " },\n" + " {\n" + " \"category\": \"fiction\",\n" + " \"author\": \"Herman Melville\",\n" + " \"title\": \"Moby Dick\",\n" + " \"isbn\": \"0-553-21311-3\",\n" + " \"price\": 8.99\n" + " }\n" + " ],\n" + " \"bicycle\": {\n" + " \"color\": \"red\",\n" + " \"price\": 19.95\n" + " }\n" + " },\n" + " \"expensive\": 10\n" + "}")), headersToIgnore) ); // - in https assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()) .withReasonPhrase(HttpStatusCode.NOT_FOUND_404.reasonPhrase()), makeRequest( request() .withSecure(true) .withPath(calculatePath("some_path")) .withMethod("POST") .withBody(new StringBody("" + "{\n" + " \"store\": {\n" + " \"book\": [\n" + " {\n" + " \"category\": \"reference\",\n" + " \"author\": \"Nigel Rees\",\n" + " \"title\": \"Sayings of the Century\",\n" + " \"price\": 8.95\n" + " },\n" + " {\n" + " \"category\": \"fiction\",\n" + " \"author\": \"Herman Melville\",\n" + " \"title\": \"Moby Dick\",\n" + " \"isbn\": \"0-553-21311-3\",\n" + " \"price\": 8.99\n" + " }\n" + " ],\n" + " \"bicycle\": {\n" + " \"color\": \"red\",\n" + " \"price\": 19.95\n" + " }\n" + " },\n" + " \"expensive\": 10\n" + "}")), headersToIgnore) ); } @Test public void shouldNotReturnResponseForMatchingPathWithNotOperator() { // when mockServerClient .when( request() .withPath(not(calculatePath("some_path"))) ) .respond( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withReasonPhrase(HttpStatusCode.ACCEPTED_202.reasonPhrase()) .withBody("some_body_response") ); // then // - in http assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()) .withReasonPhrase(HttpStatusCode.NOT_FOUND_404.reasonPhrase()), makeRequest( request() .withPath(calculatePath("some_path")), headersToIgnore) ); // - in https assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()) .withReasonPhrase(HttpStatusCode.NOT_FOUND_404.reasonPhrase()), makeRequest( request() .withPath(calculatePath("some_path")), headersToIgnore) ); } @Test public void shouldNotReturnResponseForMatchingMethodWithNotOperator() { // when mockServerClient .when( request() .withMethod(not("GET")) ) .respond( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withReasonPhrase(HttpStatusCode.ACCEPTED_202.reasonPhrase()) .withBody("some_body_response") ); // then // - in http assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()) .withReasonPhrase(HttpStatusCode.NOT_FOUND_404.reasonPhrase()), makeRequest( request() .withMethod("GET"), headersToIgnore) ); // - in https assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()) .withReasonPhrase(HttpStatusCode.NOT_FOUND_404.reasonPhrase()), makeRequest( request() .withMethod("GET"), headersToIgnore) ); } @Test public void shouldNotReturnResponseForNonMatchingBodyParameterName() { // when mockServerClient .when( request() .withMethod("POST") .withPath(calculatePath("some_pathRequest")) .withBody(params( param("bodyParameterOneName", "Parameter One Value One", "Parameter One Value Two"), param("bodyParameterTwoName", "Parameter Two") )) ) .respond( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withReasonPhrase(HttpStatusCode.ACCEPTED_202.reasonPhrase()) .withBody("some_body_response") .withHeaders(header("headerNameResponse", "headerValueResponse")) .withCookies(cookie("cookieNameResponse", "cookieValueResponse")) ); // then // wrong query string parameter name assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()) .withReasonPhrase(HttpStatusCode.NOT_FOUND_404.reasonPhrase()), makeRequest( request() .withMethod("POST") .withPath(calculatePath("some_pathRequest")) .withBody(params( param("OTHERBodyParameterOneName", "Parameter One Value One", "Parameter One Value Two"), param("bodyParameterTwoName", "Parameter Two") )) .withHeaders(header("headerNameRequest", "headerValueRequest")) .withCookies(cookie("cookieNameRequest", "cookieValueRequest")), headersToIgnore) ); // wrong query string parameter name assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()) .withReasonPhrase(HttpStatusCode.NOT_FOUND_404.reasonPhrase()), makeRequest( request() .withMethod("POST") .withPath(calculatePath("some_pathRequest")) .withBody(new StringBody("OTHERBodyParameterOneName=Parameter+One+Value+One" + "&bodyParameterOneName=Parameter+One+Value+Two" + "&bodyParameterTwoName=Parameter+Two")) .withHeaders(header("headerNameRequest", "headerValueRequest")) .withCookies(cookie("cookieNameRequest", "cookieValueRequest")), headersToIgnore) ); } @Test public void shouldNotReturnResponseForMatchingBodyParameterWithNotOperator() { // when mockServerClient .when( request() .withMethod("POST") .withPath(calculatePath("some_pathRequest")) .withBody(params( param(not("bodyParameterOneName"), not("Parameter One Value One"), not("Parameter One Value Two")), param("bodyParameterTwoName", "Parameter Two") )) ) .respond( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withReasonPhrase(HttpStatusCode.ACCEPTED_202.reasonPhrase()) .withBody("some_body_response") ); // then // wrong query string parameter name assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()) .withReasonPhrase(HttpStatusCode.NOT_FOUND_404.reasonPhrase()), makeRequest( request() .withMethod("POST") .withPath(calculatePath("some_pathRequest")) .withBody(params( param("bodyParameterOneName", "Parameter One Value One", "Parameter One Value Two"), param("bodyParameterTwoName", "Parameter Two") )) .withHeaders(header("headerNameRequest", "headerValueRequest")) .withCookies(cookie("cookieNameRequest", "cookieValueRequest")), headersToIgnore) ); // wrong query string parameter name assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()) .withReasonPhrase(HttpStatusCode.NOT_FOUND_404.reasonPhrase()), makeRequest( request() .withMethod("POST") .withPath(calculatePath("some_pathRequest")) .withBody(new StringBody("bodyParameterOneName=Other Parameter+One+Value+One" + "&bodyParameterOneName=Parameter+One+Value+Two" + "&bodyParameterTwoName=Parameter+Two")) .withHeaders(header("headerNameRequest", "headerValueRequest")) .withCookies(cookie("cookieNameRequest", "cookieValueRequest")), headersToIgnore) ); } @Test public void shouldNotReturnResponseForNonMatchingBodyParameterValue() { // when mockServerClient .when( request() .withMethod("POST") .withPath(calculatePath("some_pathRequest")) .withBody(params( param("bodyParameterOneName", "Parameter One Value One", "Parameter One Value Two"), param("bodyParameterTwoName", "Parameter Two") )) ) .respond( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withReasonPhrase(HttpStatusCode.ACCEPTED_202.reasonPhrase()) .withBody("some_body_response") .withHeaders(header("headerNameResponse", "headerValueResponse")) .withCookies(cookie("cookieNameResponse", "cookieValueResponse")) ); // then // wrong body parameter value assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()) .withReasonPhrase(HttpStatusCode.NOT_FOUND_404.reasonPhrase()), makeRequest( request() .withMethod("POST") .withPath(calculatePath("some_pathRequest")) .withBody(params( param("bodyParameterOneName", "Other Parameter One Value One", "Parameter One Value Two"), param("bodyParameterTwoName", "Parameter Two") )) .withHeaders(header("headerNameRequest", "headerValueRequest")) .withCookies(cookie("cookieNameRequest", "cookieValueRequest")), headersToIgnore) ); // wrong body parameter value assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()) .withReasonPhrase(HttpStatusCode.NOT_FOUND_404.reasonPhrase()), makeRequest( request() .withMethod("POST") .withPath(calculatePath("some_pathRequest")) .withBody(new StringBody("bodyParameterOneName=Other Parameter+One+Value+One" + "&bodyParameterOneName=Parameter+One+Value+Two" + "&bodyParameterTwoName=Parameter+Two")) .withHeaders(header("headerNameRequest", "headerValueRequest")) .withCookies(cookie("cookieNameRequest", "cookieValueRequest")), headersToIgnore) ); } @Test public void shouldNotReturnResponseForNonMatchingQueryStringParameterName() { // when mockServerClient .when( request() .withMethod("POST") .withPath(calculatePath("some_pathRequest")) .withQueryStringParameters( param("queryStringParameterOneName", "queryStringParameterOneValueOne", "queryStringParameterOneValueTwo"), param("queryStringParameterTwoName", "queryStringParameterTwoValue") ) .withBody("some_bodyRequest") ) .respond( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withReasonPhrase(HttpStatusCode.ACCEPTED_202.reasonPhrase()) .withBody("some_body_response") .withHeaders(header("headerNameResponse", "headerValueResponse")) .withCookies(cookie("cookieNameResponse", "cookieValueResponse")) ); // then // wrong query string parameter name assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()) .withReasonPhrase(HttpStatusCode.NOT_FOUND_404.reasonPhrase()), makeRequest( request() .withMethod("POST") .withPath(calculatePath("some_pathRequest")) .withQueryStringParameters( param("OTHERQueryStringParameterOneName", "queryStringParameterOneValueOne", "queryStringParameterOneValueTwo"), param("queryStringParameterTwoName", "queryStringParameterTwoValue") ) .withBody("some_bodyRequest") .withHeaders( header("headerNameRequest", "headerValueRequest") ) .withCookies(cookie("cookieNameRequest", "cookieValueRequest")), headersToIgnore) ); } @Test public void shouldNotReturnResponseForNonMatchingQueryStringParameterValue() { // when mockServerClient .when( request() .withMethod("POST") .withPath(calculatePath("some_pathRequest")) .withQueryStringParameters( param("queryStringParameterOneName", "queryStringParameterOneValueOne", "queryStringParameterOneValueTwo"), param("queryStringParameterTwoName", "queryStringParameterTwoValue") ) .withBody("some_bodyRequest") ) .respond( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withReasonPhrase(HttpStatusCode.ACCEPTED_202.reasonPhrase()) .withBody("some_body_response") .withHeaders(header("headerNameResponse", "headerValueResponse")) .withCookies(cookie("cookieNameResponse", "cookieValueResponse")) ); // then // wrong query string parameter value assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()) .withReasonPhrase(HttpStatusCode.NOT_FOUND_404.reasonPhrase()), makeRequest( request() .withMethod("POST") .withPath(calculatePath("some_pathRequest")) .withQueryStringParameters( param("queryStringParameterOneName", "OTHERqueryStringParameterOneValueOne", "queryStringParameterOneValueTwo"), param("queryStringParameterTwoName", "queryStringParameterTwoValue") ) .withBody("some_bodyRequest") .withHeaders(header("headerNameRequest", "headerValueRequest")) .withCookies(cookie("cookieNameRequest", "cookieValueRequest")), headersToIgnore) ); } @Test public void shouldNotReturnResponseForMatchingQueryStringParameterWithNotOperator() { // when mockServerClient .when( request() .withMethod("POST") .withPath(calculatePath("some_pathRequest")) .withQueryStringParameters( param(not("queryStringParameterOneName"), not("Parameter One Value One"), not("Parameter One Value Two")), param("queryStringParameterTwoName", "Parameter Two") ) ) .respond( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withReasonPhrase(HttpStatusCode.ACCEPTED_202.reasonPhrase()) .withBody("some_body_response") ); // then // wrong query string parameter name assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()) .withReasonPhrase(HttpStatusCode.NOT_FOUND_404.reasonPhrase()), makeRequest( request() .withMethod("POST") .withPath(calculatePath("some_pathRequest")) .withQueryStringParameters( param("queryStringParameterOneName", "Parameter One Value One", "Parameter One Value Two"), param("queryStringParameterTwoName", "Parameter Two") ), headersToIgnore) ); // wrong query string parameter name assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()) .withReasonPhrase(HttpStatusCode.NOT_FOUND_404.reasonPhrase()), makeRequest( request() .withMethod("POST") .withPath(calculatePath("some_pathRequest")) .withQueryStringParameters( param("queryStringParameterOneName", "Parameter One Value One", "Parameter One Value Two"), param("queryStringParameterTwoName", "Parameter Two") ), headersToIgnore) ); } @Test public void shouldNotReturnResponseForNonMatchingCookieName() { // when mockServerClient .when( request() .withMethod("GET") .withPath(calculatePath("some_path")) .withQueryStringParameters( param("queryStringParameterOneName", "queryStringParameterOneValue"), param("queryStringParameterTwoName", "queryStringParameterTwoValue") ) .withBody(exact("some_body")) .withHeaders(header("headerName", "headerValue")) .withCookies(cookie("cookieName", "cookieValue")) ) .respond( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withReasonPhrase(HttpStatusCode.ACCEPTED_202.reasonPhrase()) .withBody("some_body") .withHeaders(header("headerName", "headerValue")) .withCookies(cookie("cookieName", "cookieValue")) ); // then // - in http assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()) .withReasonPhrase(HttpStatusCode.NOT_FOUND_404.reasonPhrase()), makeRequest( request() .withMethod("GET") .withPath(calculatePath("some_path")) .withQueryStringParameters( param("queryStringParameterOneName", "queryStringParameterOneValue"), param("queryStringParameterTwoName", "queryStringParameterTwoValue") ) .withBody(exact("some_body")) .withHeaders(header("headerName", "headerValue")) .withCookies(cookie("cookieOtherName", "cookieValue")), headersToIgnore) ); // - in https assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()) .withReasonPhrase(HttpStatusCode.NOT_FOUND_404.reasonPhrase()), makeRequest( request() .withMethod("GET") .withSecure(true) .withPath(calculatePath("some_path")) .withQueryStringParameters( param("queryStringParameterOneName", "queryStringParameterOneValue"), param("queryStringParameterTwoName", "queryStringParameterTwoValue") ) .withBody(exact("some_body")) .withHeaders(header("headerName", "headerValue")) .withCookies(cookie("cookieOtherName", "cookieValue")), headersToIgnore) ); } @Test public void shouldNotReturnResponseForNonMatchingCookieValue() { // when mockServerClient .when( request() .withMethod("GET") .withPath(calculatePath("some_path")) .withQueryStringParameters( param("queryStringParameterOneName", "queryStringParameterOneValue"), param("queryStringParameterTwoName", "queryStringParameterTwoValue") ) .withBody(exact("some_body")) .withHeaders(header("headerName", "headerValue")) .withCookies(cookie("cookieName", "cookieValue")) ) .respond( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withReasonPhrase(HttpStatusCode.ACCEPTED_202.reasonPhrase()) .withBody("some_body") .withHeaders(header("headerName", "headerValue")) .withCookies(cookie("cookieName", "cookieValue")) ); // then // - in http assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()) .withReasonPhrase(HttpStatusCode.NOT_FOUND_404.reasonPhrase()), makeRequest( request() .withMethod("GET") .withPath(calculatePath("some_path")) .withQueryStringParameters( param("queryStringParameterOneName", "queryStringParameterOneValue"), param("queryStringParameterTwoName", "queryStringParameterTwoValue") ) .withBody(exact("some_body")) .withHeaders(header("headerName", "headerValue")) .withCookies(cookie("cookieName", "cookieOtherValue")), headersToIgnore) ); // - in https assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()) .withReasonPhrase(HttpStatusCode.NOT_FOUND_404.reasonPhrase()), makeRequest( request() .withMethod("GET") .withSecure(true) .withPath(calculatePath("some_path")) .withQueryStringParameters( param("queryStringParameterOneName", "queryStringParameterOneValue"), param("queryStringParameterTwoName", "queryStringParameterTwoValue") ) .withBody(exact("some_body")) .withHeaders(header("headerName", "headerValue")) .withCookies(cookie("cookieName", "cookieOtherValue")), headersToIgnore) ); } @Test public void shouldNotReturnResponseForMatchingCookieWithNotOperator() { // when mockServerClient .when( request() .withMethod("GET") .withPath(calculatePath("some_pathRequest")) .withCookies( cookie(not("requestCookieNameOne"), not("requestCookieValueOne")), cookie("requestCookieNameTwo", "requestCookieValueTwo") ) ) .respond( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withReasonPhrase(HttpStatusCode.ACCEPTED_202.reasonPhrase()) .withBody("some_body_response") ); // then // wrong query string parameter name assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()) .withReasonPhrase(HttpStatusCode.NOT_FOUND_404.reasonPhrase()), makeRequest( request() .withMethod("GET") .withPath(calculatePath("some_pathRequest")) .withCookies( cookie("requestCookieNameOne", "requestCookieValueOne"), cookie("requestCookieNameTwo", "requestCookieValueTwo") ), headersToIgnore) ); // wrong query string parameter name assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()) .withReasonPhrase(HttpStatusCode.NOT_FOUND_404.reasonPhrase()), makeRequest( request() .withMethod("GET") .withPath(calculatePath("some_pathRequest")) .withCookies( cookie("requestCookieNameOne", "requestCookieValueOne"), cookie("requestCookieNameTwo", "requestCookieValueTwo") ), headersToIgnore) ); } @Test public void shouldNotReturnResponseForNonMatchingHeaderName() { // when mockServerClient .when( request() .withMethod("GET") .withPath(calculatePath("some_path")) .withQueryStringParameters( param("queryStringParameterOneName", "queryStringParameterOneValue"), param("queryStringParameterTwoName", "queryStringParameterTwoValue") ) .withBody(exact("some_body")) .withHeaders(header("headerName", "headerValue")) .withCookies(cookie("cookieName", "cookieValue")) ) .respond( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withReasonPhrase(HttpStatusCode.ACCEPTED_202.reasonPhrase()) .withBody("some_body") .withHeaders(header("headerName", "headerValue")) .withCookies(cookie("cookieName", "cookieValue")) ); // then // - in http assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()) .withReasonPhrase(HttpStatusCode.NOT_FOUND_404.reasonPhrase()), makeRequest( request() .withMethod("GET") .withPath(calculatePath("some_path")) .withQueryStringParameters( param("queryStringParameterOneName", "queryStringParameterOneValue"), param("queryStringParameterTwoName", "queryStringParameterTwoValue") ) .withBody(exact("some_body")) .withHeaders(header("headerOtherName", "headerValue")) .withCookies(cookie("cookieName", "cookieValue")), headersToIgnore) ); // - in https assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()) .withReasonPhrase(HttpStatusCode.NOT_FOUND_404.reasonPhrase()), makeRequest( request() .withMethod("GET") .withSecure(true) .withPath(calculatePath("some_path")) .withQueryStringParameters( param("queryStringParameterOneName", "queryStringParameterOneValue"), param("queryStringParameterTwoName", "queryStringParameterTwoValue") ) .withBody(exact("some_body")) .withHeaders(header("headerOtherName", "headerValue")) .withCookies(cookie("cookieName", "cookieValue")), headersToIgnore) ); } @Test public void shouldNotReturnResponseForNonMatchingHeaderValue() { // when mockServerClient .when( request() .withMethod("GET") .withPath(calculatePath("some_path")) .withQueryStringParameters( param("queryStringParameterOneName", "queryStringParameterOneValue"), param("queryStringParameterTwoName", "queryStringParameterTwoValue") ) .withBody(exact("some_body")) .withHeaders(header("headerName", "headerValue")) .withCookies(cookie("cookieName", "cookieValue")) ) .respond( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withReasonPhrase(HttpStatusCode.ACCEPTED_202.reasonPhrase()) .withBody("some_body") .withHeaders(header("headerName", "headerValue")) .withCookies(cookie("cookieName", "cookieValue")) ); // then // - in http assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()) .withReasonPhrase(HttpStatusCode.NOT_FOUND_404.reasonPhrase()), makeRequest( request() .withMethod("GET") .withPath(calculatePath("some_path")) .withQueryStringParameters( param("queryStringParameterOneName", "queryStringParameterOneValue"), param("queryStringParameterTwoName", "queryStringParameterTwoValue") ) .withBody(exact("some_body")) .withHeaders(header("headerName", "headerOtherValue")) .withCookies(cookie("cookieName", "cookieValue")), headersToIgnore) ); // - in https assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()) .withReasonPhrase(HttpStatusCode.NOT_FOUND_404.reasonPhrase()), makeRequest( request() .withMethod("GET") .withSecure(true) .withPath(calculatePath("some_path")) .withQueryStringParameters( param("queryStringParameterOneName", "queryStringParameterOneValue"), param("queryStringParameterTwoName", "queryStringParameterTwoValue") ) .withBody(exact("some_body")) .withHeaders(header("headerName", "headerOtherValue")) .withCookies(cookie("cookieName", "cookieValue")), headersToIgnore) ); } @Test public void shouldNotReturnResponseForMatchingHeaderWithNotOperator() { // when mockServerClient .when( request() .withMethod("GET") .withPath(calculatePath("some_pathRequest")) .withHeaders( header(not("requestHeaderNameOne"), not("requestHeaderValueOne")), header("requestHeaderNameTwo", "requestHeaderValueTwo") ) ) .respond( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withReasonPhrase(HttpStatusCode.ACCEPTED_202.reasonPhrase()) .withBody("some_body_response") ); // then // wrong query string parameter name assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()) .withReasonPhrase(HttpStatusCode.NOT_FOUND_404.reasonPhrase()), makeRequest( request() .withMethod("GET") .withPath(calculatePath("some_pathRequest")) .withHeaders( header("requestHeaderNameOne", "requestHeaderValueOne"), header("requestHeaderNameTwo", "requestHeaderValueTwo") ), headersToIgnore) ); // wrong query string parameter name assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()) .withReasonPhrase(HttpStatusCode.NOT_FOUND_404.reasonPhrase()), makeRequest( request() .withMethod("GET") .withPath(calculatePath("some_pathRequest")) .withHeaders( header("requestHeaderNameOne", "requestHeaderValueOne"), header("requestHeaderNameTwo", "requestHeaderValueTwo") ), headersToIgnore) ); } @Test public void shouldVerifyReceivedRequestInSsl() { // when mockServerClient .when( request() .withPath(calculatePath("some.*path")), exactly(2) ) .respond( response() .withBody("some_body") ); // then // - in http assertEquals( response() .withStatusCode(OK_200.code()) .withReasonPhrase(OK_200.reasonPhrase()) .withBody("some_body"), makeRequest( request() .withPath(calculatePath("some_path")), headersToIgnore) ); mockServerClient.verify(request() .withPath(calculatePath("some_path")) .withSecure(false)); mockServerClient.verify(request() .withPath(calculatePath("some_path")) .withSecure(false), VerificationTimes.exactly(1)); // - in https assertEquals( response() .withStatusCode(OK_200.code()) .withReasonPhrase(OK_200.reasonPhrase()) .withBody("some_body"), makeRequest( request() .withPath(calculatePath("some_secure_path")) .withSecure(true), headersToIgnore) ); mockServerClient.verify(request() .withPath(calculatePath("some_secure_path")) .withSecure(true)); mockServerClient.verify(request() .withPath(calculatePath("some_secure_path")) .withSecure(true), VerificationTimes.exactly(1)); } @Test public void shouldVerifyReceivedRequestsWithRegexBody() { // when mockServerClient .when( request() .withMethod("POST") .withPath(calculatePath("some_path")) .withBody("{type: 'some_random_type', value: 'some_random_value'}"), exactly(2) ) .respond( response() .withBody("some_response") ); // then // - in http assertEquals( response() .withStatusCode(OK_200.code()) .withReasonPhrase(OK_200.reasonPhrase()) .withBody("some_response"), makeRequest( request() .withMethod("POST") .withPath(calculatePath("some_path")) .withBody("{type: 'some_random_type', value: 'some_random_value'}"), headersToIgnore) ); mockServerClient.verify( request() .withBody(regex("\\{type\\: \\'some_random_type\\'\\, value\\: \\'some_random_value\\'\\}")) ); mockServerClient.verify( request() .withBody(regex("\\{type\\: \\'some_random_type\\'\\, value\\: \\'some_random_value\\'\\}")), VerificationTimes.exactly(1) ); // - in https assertEquals( response() .withStatusCode(OK_200.code()) .withReasonPhrase(OK_200.reasonPhrase()) .withBody("some_response"), makeRequest( request() .withSecure(true) .withMethod("POST") .withPath(calculatePath("some_path")) .withBody("{type: 'some_random_type', value: 'some_random_value'}"), headersToIgnore) ); mockServerClient.verify( request() .withSecure(true) .withBody(regex("\\{type\\: \\'some_random_type\\'\\, value\\: \\'some_random_value\\'\\}")) ); mockServerClient.verify( request() .withSecure(true) .withBody(regex("\\{type\\: \\'some_random_type\\'\\, value\\: \\'some_random_value\\'\\}")), VerificationTimes.atLeast(1) ); } @Test public void shouldVerifyReceivedRequestsWithNoBody() { // when mockServerClient.when(request().withPath(calculatePath("some_path")), exactly(2)).respond(response()); // then // - in http assertEquals( response() .withStatusCode(OK_200.code()) .withReasonPhrase(OK_200.reasonPhrase()), makeRequest( request() .withPath(calculatePath("some_path")), headersToIgnore) ); mockServerClient.verify(request() .withPath(calculatePath("some_path"))); mockServerClient.verify(request() .withPath(calculatePath("some_path")), VerificationTimes.exactly(1)); } @Test public void shouldVerifyTooManyRequestsReceived() { // when mockServerClient.when(request().withPath(calculatePath("some_path")), exactly(2)).respond(response().withBody("some_body")); // then assertEquals( response() .withStatusCode(OK_200.code()) .withReasonPhrase(OK_200.reasonPhrase()) .withBody("some_body"), makeRequest( request() .withPath(calculatePath("some_path")), headersToIgnore) ); try { mockServerClient.verify(request() .withPath(calculatePath("some_path")), VerificationTimes.exactly(0)); fail(); } catch (AssertionError ae) { assertThat(ae.getMessage(), startsWith("Request not found exactly 0 times, expected:<{" + NEW_LINE + " \"path\" : \"" + calculatePath("some_path") + "\"" + NEW_LINE + "}> but was:<{" + NEW_LINE + " \"method\" : \"GET\"," + NEW_LINE + " \"path\" : \"" + calculatePath("some_path") + "\"," + NEW_LINE)); } } @Test public void shouldVerifyNoMatchingRequestsReceived() { // when mockServerClient.when(request().withPath(calculatePath("some_path")), exactly(2)).respond(response().withBody("some_body")); // then assertEquals( response() .withStatusCode(OK_200.code()) .withReasonPhrase(OK_200.reasonPhrase()) .withBody("some_body"), makeRequest( request() .withPath(calculatePath("some_path")), headersToIgnore) ); try { mockServerClient.verify(request() .withPath(calculatePath("some_other_path")), VerificationTimes.exactly(2)); fail(); } catch (AssertionError ae) { assertThat(ae.getMessage(), startsWith("Request not found exactly 2 times, expected:<{" + NEW_LINE + " \"path\" : \"" + calculatePath("some_other_path") + "\"" + NEW_LINE + "}> but was:<{" + NEW_LINE + " \"method\" : \"GET\"," + NEW_LINE + " \"path\" : \"" + calculatePath("some_path") + "\"," + NEW_LINE)); } } @Test public void shouldNotVerifyNoRequestsReceived() { // when mockServerClient.when(request().withPath(calculatePath("some_path")), exactly(2)).respond(response().withBody("some_body")); // then assertEquals( response() .withStatusCode(OK_200.code()) .withReasonPhrase(OK_200.reasonPhrase()) .withBody("some_body"), makeRequest( request() .withPath(calculatePath("some_path")), headersToIgnore) ); try { mockServerClient.verifyZeroInteractions(); fail(); } catch (AssertionError ae) { assertThat(ae.getMessage(), startsWith("Request not found exactly 0 times, expected:<{ }> but was:<{" + NEW_LINE + " \"method\" : \"GET\"," + NEW_LINE + " \"path\" : \"" + calculatePath("some_path") + "\"," + NEW_LINE)); } } @Test public void shouldVerifyNoMatchingRequestsReceivedInSsl() { // when mockServerClient.when(request().withPath(calculatePath("some.*path")), exactly(2)).respond(response().withBody("some_body")); // then // - in http assertEquals( response() .withStatusCode(OK_200.code()) .withReasonPhrase(OK_200.reasonPhrase()) .withBody("some_body"), makeRequest( request() .withPath(calculatePath("some_path")), headersToIgnore) ); try { mockServerClient.verify( request() .withPath(calculatePath("some_path")) .withSecure(true), VerificationTimes.atLeast(1) ); fail(); } catch (AssertionError ae) { assertThat(ae.getMessage(), startsWith("Request not found at least once, expected:<{" + NEW_LINE + " \"path\" : \"" + calculatePath("some_path") + "\"," + NEW_LINE + " \"secure\" : true" + NEW_LINE + "}> but was:<{" + NEW_LINE + " \"method\" : \"GET\"," + NEW_LINE + " \"path\" : \"" + calculatePath("some_path") + "\"," + NEW_LINE)); } // - in https assertEquals( response() .withStatusCode(OK_200.code()) .withReasonPhrase(OK_200.reasonPhrase()) .withBody("some_body"), makeRequest( request() .withPath(calculatePath("some_secure_path")) .withSecure(true), headersToIgnore) ); try { mockServerClient.verify( request() .withPath(calculatePath("some_secure_path")) .withSecure(false), VerificationTimes.atLeast(1) ); fail(); } catch (AssertionError ae) { assertThat(ae.getMessage(), startsWith("Request not found at least once, expected:<{" + NEW_LINE + " \"path\" : \"" + calculatePath("some_secure_path") + "\"," + NEW_LINE + " \"secure\" : false" + NEW_LINE + "}> but was:<[ {" + NEW_LINE + " \"method\" : \"GET\"," + NEW_LINE + " \"path\" : \"" + calculatePath("some_path") + "\"," + NEW_LINE)); } } @Test public void shouldVerifySequenceOfRequestsReceivedIncludingThoseNotMatchingAnException() { // when mockServerClient.when(request().withPath(calculatePath("some_path.*")), exactly(4)).respond(response().withBody("some_body")); // then assertEquals( response("some_body"), makeRequest( request().withPath(calculatePath("some_path_one")), headersToIgnore) ); assertEquals( notFoundResponse(), makeRequest( request().withPath(calculatePath("not_found")), headersToIgnore) ); assertEquals( response("some_body"), makeRequest( request().withPath(calculatePath("some_path_three")), headersToIgnore) ); mockServerClient.verify(request(calculatePath("some_path_one")), request(calculatePath("some_path_three"))); mockServerClient.verify(request(calculatePath("some_path_one")), request(calculatePath("not_found"))); mockServerClient.verify(request(calculatePath("some_path_one")), request(calculatePath("not_found")), request(calculatePath("some_path_three"))); mockServerClient.verify(request(calculatePath("some_path_one")), request(calculatePath("not_found")), request(calculatePath("some_path_three"))); } @Test public void shouldVerifySequenceOfRequestsNotReceived() { // when mockServerClient.when(request().withPath(calculatePath("some_path.*")), exactly(6)).respond(response().withBody("some_body")); // then assertEquals( response("some_body"), makeRequest( request().withPath(calculatePath("some_path_one")), headersToIgnore) ); assertEquals( response("some_body"), makeRequest( request().withPath(calculatePath("some_path_two")), headersToIgnore) ); assertEquals( response("some_body"), makeRequest( request().withPath(calculatePath("some_path_three")), headersToIgnore) ); try { mockServerClient.verify(request(calculatePath("some_path_two")), request(calculatePath("some_path_one"))); fail(); } catch (AssertionError ae) { assertThat(ae.getMessage(), startsWith("Request sequence not found, expected:<[ {" + NEW_LINE + " \"path\" : \"" + calculatePath("some_path_two") + "\"" + NEW_LINE + "}, {" + NEW_LINE + " \"path\" : \"" + calculatePath("some_path_one") + "\"" + NEW_LINE + "} ]> but was:<[ {" + NEW_LINE + " \"method\" : \"GET\"," + NEW_LINE + " \"path\" : \"" + calculatePath("some_path_one") + "\"," + NEW_LINE)); } try { mockServerClient.verify(request(calculatePath("some_path_three")), request(calculatePath("some_path_two"))); fail(); } catch (AssertionError ae) { assertThat(ae.getMessage(), startsWith("Request sequence not found, expected:<[ {" + NEW_LINE + " \"path\" : \"" + calculatePath("some_path_three") + "\"" + NEW_LINE + "}, {" + NEW_LINE + " \"path\" : \"" + calculatePath("some_path_two") + "\"" + NEW_LINE + "} ]> but was:<[ {" + NEW_LINE + " \"method\" : \"GET\"," + NEW_LINE + " \"path\" : \"" + calculatePath("some_path_one") + "\"," + NEW_LINE)); } try { mockServerClient.verify(request(calculatePath("some_path_four"))); fail(); } catch (AssertionError ae) { assertThat(ae.getMessage(), startsWith("Request sequence not found, expected:<[ {" + NEW_LINE + " \"path\" : \"" + calculatePath("some_path_four") + "\"" + NEW_LINE + "} ]> but was:<[ {" + NEW_LINE + " \"method\" : \"GET\"," + NEW_LINE + " \"path\" : \"" + calculatePath("some_path_one") + "\"," + NEW_LINE)); } } @Test public void shouldRetrieveRecordedRequestsAsJson() { // when mockServerClient.when(request().withPath(calculatePath("some_path.*")), exactly(4)).respond(response().withBody("some_body")); assertEquals( response("some_body"), makeRequest( request().withPath(calculatePath("some_path_one")), headersToIgnore) ); assertEquals( notFoundResponse(), makeRequest( request().withPath(calculatePath("not_found")), headersToIgnore) ); assertEquals( response("some_body"), makeRequest( request().withPath(calculatePath("some_path_three")), headersToIgnore) ); // then verifyRequestsMatches( new HttpRequestSerializer(new MockServerLogger()).deserializeArray(mockServerClient.retrieveRecordedRequests(request().withPath(calculatePath("some_path.*")), Format.JSON)), request(calculatePath("some_path_one")), request(calculatePath("some_path_three")) ); verifyRequestsMatches( new HttpRequestSerializer(new MockServerLogger()).deserializeArray(mockServerClient.retrieveRecordedRequests(request(), Format.JSON)), request(calculatePath("some_path_one")), request(calculatePath("not_found")), request(calculatePath("some_path_three")) ); verifyRequestsMatches( new HttpRequestSerializer(new MockServerLogger()).deserializeArray(mockServerClient.retrieveRecordedRequests(null, Format.JSON)), request(calculatePath("some_path_one")), request(calculatePath("not_found")), request(calculatePath("some_path_three")) ); } @Test public void shouldRetrieveRecordedRequestsAsLogEntries() throws IOException { // when mockServerClient.when(request().withPath(calculatePath("some_path.*")), exactly(4)).respond(response().withBody("some_body")); assertEquals( response("some_body"), makeRequest( request().withPath(calculatePath("some_path_one")), headersToIgnore) ); assertEquals( notFoundResponse(), makeRequest( request().withPath(calculatePath("not_found")), headersToIgnore) ); assertEquals( response("some_body"), makeRequest( request().withPath(calculatePath("some_path_three")), headersToIgnore) ); final ObjectMapper objectMapper = ObjectMapperFactory.createObjectMapper(); final JsonArraySerializer jsonArraySerializer = new JsonArraySerializer(); // then List<String> logEntries = jsonArraySerializer.returnJSONObjects(mockServerClient.retrieveRecordedRequests(request().withPath(calculatePath("some_path.*")), Format.LOG_ENTRIES)); assertThat(logEntries.size(), is(2)); HashMap itemOne = objectMapper.readValue(logEntries.get(0), HashMap.class); assertThat(new ArrayList<String>(itemOne.keySet()), containsInAnyOrder("httpRequest", "timestamp", "expectation")); assertThat(String.valueOf(((LinkedHashMap) itemOne.get("httpRequest")).get("path")), is(calculatePath("some_path_one"))); HashMap itemTwo = objectMapper.readValue(logEntries.get(1), HashMap.class); assertThat(new ArrayList<String>(itemTwo.keySet()), containsInAnyOrder("httpRequest", "timestamp", "expectation")); assertThat(String.valueOf(((LinkedHashMap) itemTwo.get("httpRequest")).get("path")), is(calculatePath("some_path_three"))); logEntries = jsonArraySerializer.returnJSONObjects(mockServerClient.retrieveRecordedRequests(request(), Format.LOG_ENTRIES)); assertThat(logEntries.size(), is(3)); itemOne = objectMapper.readValue(logEntries.get(0), HashMap.class); assertThat(new ArrayList<String>(itemOne.keySet()), containsInAnyOrder("httpRequest", "timestamp", "expectation")); assertThat(String.valueOf(((LinkedHashMap) itemOne.get("httpRequest")).get("path")), is(calculatePath("some_path_one"))); itemTwo = objectMapper.readValue(logEntries.get(1), HashMap.class); assertThat(itemTwo.containsKey("expectation"), is(false)); assertThat(new ArrayList<String>(itemTwo.keySet()), containsInAnyOrder("httpRequest", "timestamp")); assertThat(String.valueOf(((LinkedHashMap) itemTwo.get("httpRequest")).get("path")), is(calculatePath("not_found"))); HashMap itemThree = objectMapper.readValue(logEntries.get(2), HashMap.class); assertThat(new ArrayList<String>(itemThree.keySet()), containsInAnyOrder("httpRequest", "timestamp", "expectation")); assertThat(String.valueOf(((LinkedHashMap) itemThree.get("httpRequest")).get("path")), is(calculatePath("some_path_three"))); logEntries = jsonArraySerializer.returnJSONObjects(mockServerClient.retrieveRecordedRequests(null, Format.LOG_ENTRIES)); assertThat(logEntries.size(), is(3)); itemOne = objectMapper.readValue(logEntries.get(0), HashMap.class); assertThat(new ArrayList<String>(itemOne.keySet()), containsInAnyOrder("httpRequest", "timestamp", "expectation")); assertThat(String.valueOf(((LinkedHashMap) itemOne.get("httpRequest")).get("path")), is(calculatePath("some_path_one"))); itemTwo = objectMapper.readValue(logEntries.get(1), HashMap.class); assertThat(itemTwo.containsKey("expectation"), is(false)); assertThat(new ArrayList<String>(itemTwo.keySet()), containsInAnyOrder("httpRequest", "timestamp")); assertThat(String.valueOf(((LinkedHashMap) itemTwo.get("httpRequest")).get("path")), is(calculatePath("not_found"))); itemThree = objectMapper.readValue(logEntries.get(2), HashMap.class); assertThat(new ArrayList<String>(itemThree.keySet()), containsInAnyOrder("httpRequest", "timestamp", "expectation")); assertThat(String.valueOf(((LinkedHashMap) itemThree.get("httpRequest")).get("path")), is(calculatePath("some_path_three"))); } @Test public void shouldRetrieveActiveExpectationsAsJson() { // when mockServerClient.when(request().withPath(calculatePath("some_path.*")), exactly(4)) .respond(response().withBody("some_body")); mockServerClient.when(request().withPath(calculatePath("some_path.*"))) .respond(response().withBody("some_body")); mockServerClient.when(request().withPath(calculatePath("some_other_path"))) .respond(response().withBody("some_other_body")); mockServerClient.when(request().withPath(calculatePath("some_forward_path"))) .forward(forward()); // then assertThat( mockServerClient.retrieveActiveExpectations(request().withPath(calculatePath("some_path.*")), Format.JSON), is(new ExpectationSerializer(new MockServerLogger()).serialize(Arrays.asList( new Expectation(request().withPath(calculatePath("some_path.*")), exactly(4), TimeToLive.unlimited()) .thenRespond(response().withBody("some_body")), new Expectation(request().withPath(calculatePath("some_path.*"))) .thenRespond(response().withBody("some_body")) ))) ); assertThat( mockServerClient.retrieveActiveExpectations(null, Format.JSON), is(new ExpectationSerializer(new MockServerLogger()).serialize(Arrays.asList( new Expectation(request().withPath(calculatePath("some_path.*")), exactly(4), TimeToLive.unlimited()) .thenRespond(response().withBody("some_body")), new Expectation(request().withPath(calculatePath("some_path.*"))) .thenRespond(response().withBody("some_body")), new Expectation(request().withPath(calculatePath("some_other_path"))) .thenRespond(response().withBody("some_other_body")), new Expectation(request().withPath(calculatePath("some_forward_path"))) .thenForward(forward()) ))) ); assertThat( mockServerClient.retrieveActiveExpectations(request(), Format.JSON), is(new ExpectationSerializer(new MockServerLogger()).serialize(Arrays.asList( new Expectation(request().withPath(calculatePath("some_path.*")), exactly(4), TimeToLive.unlimited()) .thenRespond(response().withBody("some_body")), new Expectation(request().withPath(calculatePath("some_path.*"))) .thenRespond(response().withBody("some_body")), new Expectation(request().withPath(calculatePath("some_other_path"))) .thenRespond(response().withBody("some_other_body")), new Expectation(request().withPath(calculatePath("some_forward_path"))) .thenForward(forward()) ))) ); } @Test public void shouldRetrieveActiveExpectationsAsJava() { // when mockServerClient.when(request().withPath(calculatePath("some_path.*")), exactly(4)) .respond(response().withBody("some_body")); mockServerClient.when(request().withPath(calculatePath("some_path.*"))) .respond(response().withBody("some_body")); mockServerClient.when(request().withPath(calculatePath("some_other_path"))) .respond(response().withBody("some_other_body")); mockServerClient.when(request().withPath(calculatePath("some_forward_path"))) .forward(forward()); // then assertThat( mockServerClient.retrieveActiveExpectations(request().withPath(calculatePath("some_path.*")), Format.JAVA), is(new ExpectationToJavaSerializer().serialize(Arrays.asList( new Expectation(request().withPath(calculatePath("some_path.*")), exactly(4), TimeToLive.unlimited()) .thenRespond(response().withBody("some_body")), new Expectation(request().withPath(calculatePath("some_path.*"))) .thenRespond(response().withBody("some_body")) ))) ); assertThat( mockServerClient.retrieveActiveExpectations(null, Format.JAVA), is(new ExpectationToJavaSerializer().serialize(Arrays.asList( new Expectation(request().withPath(calculatePath("some_path.*")), exactly(4), TimeToLive.unlimited()) .thenRespond(response().withBody("some_body")), new Expectation(request().withPath(calculatePath("some_path.*"))) .thenRespond(response().withBody("some_body")), new Expectation(request().withPath(calculatePath("some_other_path"))) .thenRespond(response().withBody("some_other_body")), new Expectation(request().withPath(calculatePath("some_forward_path"))) .thenForward(forward()) ))) ); assertThat( mockServerClient.retrieveActiveExpectations(request(), Format.JAVA), is(new ExpectationToJavaSerializer().serialize(Arrays.asList( new Expectation(request().withPath(calculatePath("some_path.*")), exactly(4), TimeToLive.unlimited()) .thenRespond(response().withBody("some_body")), new Expectation(request().withPath(calculatePath("some_path.*"))) .thenRespond(response().withBody("some_body")), new Expectation(request().withPath(calculatePath("some_other_path"))) .thenRespond(response().withBody("some_other_body")), new Expectation(request().withPath(calculatePath("some_forward_path"))) .thenForward(forward()) ))) ); } @Test public void shouldRetrieveRecordedExpectationsAsJson() { // when mockServerClient.when(request().withPath(calculatePath("some_path.*")), exactly(4)).forward( forward() .withHost("127.0.0.1") .withPort(insecureEchoServer.getPort()) ); assertEquals( response("some_body_one"), makeRequest( request().withPath(calculatePath("some_path_one")).withBody("some_body_one"), headersToIgnore ) ); assertEquals( response("some_body_three"), makeRequest( request().withPath(calculatePath("some_path_three")).withBody("some_body_three"), headersToIgnore ) ); // then Expectation[] recordedExpectations = new ExpectationSerializer(new MockServerLogger()).deserializeArray( mockServerClient.retrieveRecordedExpectations(request().withPath(calculatePath("some_path_one")), Format.JSON) ); assertThat(recordedExpectations.length, is(1)); verifyRequestsMatches( new HttpRequest[]{ recordedExpectations[0].getHttpRequest() }, request(calculatePath("some_path_one")).withBody("some_body_one") ); assertThat(recordedExpectations[0].getHttpResponse().getBodyAsString(), is("some_body_one")); // and recordedExpectations = new ExpectationSerializer(new MockServerLogger()).deserializeArray( mockServerClient.retrieveRecordedExpectations(request(), Format.JSON) ); assertThat(recordedExpectations.length, is(2)); verifyRequestsMatches( new HttpRequest[]{ recordedExpectations[0].getHttpRequest(), recordedExpectations[1].getHttpRequest() }, request(calculatePath("some_path_one")).withBody("some_body_one"), request(calculatePath("some_path_three")).withBody("some_body_three") ); assertThat(recordedExpectations[0].getHttpResponse().getBodyAsString(), is("some_body_one")); assertThat(recordedExpectations[1].getHttpResponse().getBodyAsString(), is("some_body_three")); // and recordedExpectations = new ExpectationSerializer(new MockServerLogger()).deserializeArray( mockServerClient.retrieveRecordedExpectations(null, Format.JSON) ); assertThat(recordedExpectations.length, is(2)); verifyRequestsMatches( new HttpRequest[]{ recordedExpectations[0].getHttpRequest(), recordedExpectations[1].getHttpRequest() }, request(calculatePath("some_path_one")).withBody("some_body_one"), request(calculatePath("some_path_three")).withBody("some_body_three") ); assertThat(recordedExpectations[0].getHttpResponse().getBodyAsString(), is("some_body_one")); assertThat(recordedExpectations[1].getHttpResponse().getBodyAsString(), is("some_body_three")); } @Test public void shouldClearExpectationsOnly() { // given - some expectations mockServerClient .when( request() .withPath(calculatePath("some_path1")) ) .respond( response() .withBody("some_body1") ); mockServerClient .when( request() .withPath(calculatePath("some_path2")) ) .respond( response() .withBody("some_body2") ); // and - some matching requests assertEquals( response() .withStatusCode(OK_200.code()) .withReasonPhrase(OK_200.reasonPhrase()) .withBody("some_body1"), makeRequest( request() .withPath(calculatePath("some_path1")), headersToIgnore) ); assertEquals( response() .withStatusCode(OK_200.code()) .withReasonPhrase(OK_200.reasonPhrase()) .withBody("some_body2"), makeRequest( request() .withPath(calculatePath("some_path2")), headersToIgnore) ); // when mockServerClient .clear( request() .withPath(calculatePath("some_path1")), ClearType.EXPECTATIONS ); // then - expectations cleared assertThat( mockServerClient.retrieveActiveExpectations(null), arrayContaining( new Expectation(request() .withPath(calculatePath("some_path2"))) .thenRespond( response() .withBody("some_body2") ) ) ); // and then - request log not cleared verifyRequestsMatches( mockServerClient.retrieveRecordedRequests(null), request(calculatePath("some_path1")), request(calculatePath("some_path2")) ); } @Test public void shouldClearLogsOnly() { // given - some expectations mockServerClient .when( request() .withPath(calculatePath("some_path1")) ) .respond( response() .withBody("some_body1") ); mockServerClient .when( request() .withPath(calculatePath("some_path2")) ) .respond( response() .withBody("some_body2") ); // and - some matching requests assertEquals( response() .withStatusCode(OK_200.code()) .withReasonPhrase(OK_200.reasonPhrase()) .withBody("some_body1"), makeRequest( request() .withPath(calculatePath("some_path1")), headersToIgnore) ); assertEquals( response() .withStatusCode(OK_200.code()) .withReasonPhrase(OK_200.reasonPhrase()) .withBody("some_body2"), makeRequest( request() .withPath(calculatePath("some_path2")), headersToIgnore) ); // when mockServerClient .clear( request() .withPath(calculatePath("some_path1")), ClearType.LOG ); // then - expectations cleared assertThat( mockServerClient.retrieveActiveExpectations(null), arrayContaining( new Expectation(request() .withPath(calculatePath("some_path1"))) .thenRespond( response() .withBody("some_body1") ), new Expectation(request() .withPath(calculatePath("some_path2"))) .thenRespond( response() .withBody("some_body2") ) ) ); // and then - request log cleared verifyRequestsMatches( mockServerClient.retrieveRecordedRequests(null), request(calculatePath("some_path2")) ); } @Test public void shouldClearAllExpectationsWithNull() { // given mockServerClient .when( request() .withPath(calculatePath("some_path1")) ) .respond( response() .withBody("some_body1") ); mockServerClient .when( request() .withPath(calculatePath("some_path2")) ) .respond( response() .withBody("some_body2") ); assertEquals( response() .withStatusCode(OK_200.code()) .withReasonPhrase(OK_200.reasonPhrase()) .withBody("some_body2"), makeRequest( request() .withPath(calculatePath("some_path2")), headersToIgnore) ); // when mockServerClient.clear(null); // then assertThat(mockServerClient.retrieveActiveExpectations(null), emptyArray()); assertThat(mockServerClient.retrieveRecordedRequests(null), emptyArray()); } @Test public void shouldClearAllExpectationsWithEmptyRequest() { // given mockServerClient .when( request() .withPath(calculatePath("some_path1")) ) .respond( response() .withBody("some_body1") ); mockServerClient .when( request() .withPath(calculatePath("some_path2")) ) .respond( response() .withBody("some_body2") ); assertEquals( response() .withStatusCode(OK_200.code()) .withReasonPhrase(OK_200.reasonPhrase()) .withBody("some_body2"), makeRequest( request() .withPath(calculatePath("some_path2")), headersToIgnore) ); // when mockServerClient.clear(request()); // then assertThat(mockServerClient.retrieveActiveExpectations(null), emptyArray()); assertThat(mockServerClient.retrieveRecordedRequests(null), emptyArray()); } @Test public void shouldClearExpectationsWithXPathBody() { // given mockServerClient .when( request() .withBody(xpath("/bookstore/book[year=2005]/price")) ) .respond( response() .withBody("some_body1") ); mockServerClient .when( request() .withBody(xpath("/bookstore/book[year=2006]/price")) ) .respond( response() .withBody("some_body2") ); // and StringBody xmlBody = new StringBody("" + "<?xml version=\"1.0\" encoding=\"ISO-8859-1\"?>" + NEW_LINE + "<bookstore>" + NEW_LINE + " <book category=\"COOKING\">" + NEW_LINE + " <title lang=\"en\">Everyday Italian</title>" + NEW_LINE + " <author>Giada De Laurentiis</author>" + NEW_LINE + " <year>2005</year>" + NEW_LINE + " <price>30.00</price>" + NEW_LINE + " </book>" + NEW_LINE + " <book category=\"CHILDREN\">" + NEW_LINE + " <title lang=\"en\">Harry Potter</title>" + NEW_LINE + " <author>J K. Rowling</author>" + NEW_LINE + " <year>2006</year>" + NEW_LINE + " <price>29.99</price>" + NEW_LINE + " </book>" + NEW_LINE + " <book category=\"WEB\">" + NEW_LINE + " <title lang=\"en\">Learning XML</title>" + NEW_LINE + " <author>Erik T. Ray</author>" + NEW_LINE + " <year>2003</year>" + NEW_LINE + " <price>31.95</price>" + NEW_LINE + " </book>" + NEW_LINE + "</bookstore>"); // then assertEquals( response() .withStatusCode(OK_200.code()) .withReasonPhrase(OK_200.reasonPhrase()) .withBody("some_body1"), makeRequest( request() .withBody(xmlBody), headersToIgnore) ); // when mockServerClient .clear( request() .withBody(xpath("/bookstore/book[year=2005]/price")) ); // then assertThat( mockServerClient.retrieveActiveExpectations(null), arrayContaining( new Expectation(request() .withBody(xpath("/bookstore/book[year=2006]/price"))) .thenRespond( response() .withBody("some_body2") ) ) ); // - in http assertEquals( response() .withStatusCode(OK_200.code()) .withReasonPhrase(OK_200.reasonPhrase()) .withBody("some_body2"), makeRequest( request() .withBody(xmlBody), headersToIgnore) ); // - in https assertEquals( response() .withStatusCode(OK_200.code()) .withReasonPhrase(OK_200.reasonPhrase()) .withBody("some_body2"), makeRequest( request() .withSecure(true) .withBody(xmlBody), headersToIgnore) ); } @Test public void shouldClearExpectationsWithJsonSchemaBody() { // given JsonSchemaBody jsonSchemaBodyOne = jsonSchema("{" + NEW_LINE + " \"$schema\": \"http://json-schema.org/draft-04/schema#\"," + NEW_LINE + " \"title\": \"Product\"," + NEW_LINE + " \"description\": \"A product from Acme's catalog\"," + NEW_LINE + " \"type\": \"object\"," + NEW_LINE + " \"properties\": {" + NEW_LINE + " \"id\": {" + NEW_LINE + " \"description\": \"The unique identifier for a product\"," + NEW_LINE + " \"type\": \"integer\"" + NEW_LINE + " }," + NEW_LINE + " \"name\": {" + NEW_LINE + " \"description\": \"Name of the product\"," + NEW_LINE + " \"type\": \"string\"" + NEW_LINE + " }," + NEW_LINE + " \"price\": {" + NEW_LINE + " \"type\": \"number\"," + NEW_LINE + " \"minimum\": 0," + NEW_LINE + " \"exclusiveMinimum\": true" + NEW_LINE + " }," + NEW_LINE + " \"tags\": {" + NEW_LINE + " \"type\": \"array\"," + NEW_LINE + " \"items\": {" + NEW_LINE + " \"type\": \"string\"" + NEW_LINE + " }," + NEW_LINE + " \"minItems\": 1," + NEW_LINE + " \"uniqueItems\": true" + NEW_LINE + " }" + NEW_LINE + " }," + NEW_LINE + " \"required\": [\"id\", \"name\", \"price\"]" + NEW_LINE + "}"); JsonSchemaBody jsonSchemaBodyTwo = jsonSchema("{" + NEW_LINE + " \"$schema\": \"http://json-schema.org/draft-04/schema#\"," + NEW_LINE + " \"title\": \"Product\"," + NEW_LINE + " \"description\": \"A product from Acme's catalog\"," + NEW_LINE + " \"type\": \"object\"," + NEW_LINE + " \"properties\": {" + NEW_LINE + " \"id\": {" + NEW_LINE + " \"description\": \"The unique identifier for a product\"," + NEW_LINE + " \"type\": \"integer\"" + NEW_LINE + " }," + NEW_LINE + " \"name\": {" + NEW_LINE + " \"description\": \"Name of the product\"," + NEW_LINE + " \"type\": \"string\"" + NEW_LINE + " }," + NEW_LINE + " \"price\": {" + NEW_LINE + " \"type\": \"number\"," + NEW_LINE + " \"minimum\": 10," + NEW_LINE + " \"exclusiveMinimum\": true" + NEW_LINE + " }," + NEW_LINE + " \"tags\": {" + NEW_LINE + " \"type\": \"array\"," + NEW_LINE + " \"items\": {" + NEW_LINE + " \"type\": \"string\"" + NEW_LINE + " }," + NEW_LINE + " \"minItems\": 1," + NEW_LINE + " \"uniqueItems\": true" + NEW_LINE + " }" + NEW_LINE + " }," + NEW_LINE + " \"required\": [\"id\", \"name\", \"price\"]" + NEW_LINE + "}"); mockServerClient .when( request() .withBody(jsonSchemaBodyOne) ) .respond( response() .withBody("some_body1") ); mockServerClient .when( request() .withBody(jsonSchemaBodyTwo) ) .respond( response() .withBody("some_body2") ); // then assertEquals( response() .withStatusCode(OK_200.code()) .withReasonPhrase(OK_200.reasonPhrase()) .withBody("some_body1"), makeRequest( request() .withBody("{" + NEW_LINE + " \"id\": 1," + NEW_LINE + " \"name\": \"A green door\"," + NEW_LINE + " \"price\": 12.50," + NEW_LINE + " \"tags\": [\"home\", \"green\"]" + NEW_LINE + "}"), headersToIgnore) ); // when mockServerClient .clear( request() .withBody(jsonSchemaBodyOne) ); // then assertThat( mockServerClient.retrieveActiveExpectations(null), arrayContaining( new Expectation(request() .withBody(jsonSchemaBodyTwo)) .thenRespond( response() .withBody("some_body2") ) ) ); // - in http assertEquals( response() .withStatusCode(OK_200.code()) .withReasonPhrase(OK_200.reasonPhrase()) .withBody("some_body2"), makeRequest( request() .withBody("{" + NEW_LINE + " \"id\": 1," + NEW_LINE + " \"name\": \"A green door\"," + NEW_LINE + " \"price\": 12.50," + NEW_LINE + " \"tags\": [\"home\", \"green\"]" + NEW_LINE + "}"), headersToIgnore) ); // - in https assertEquals( response() .withStatusCode(OK_200.code()) .withReasonPhrase(OK_200.reasonPhrase()) .withBody("some_body2"), makeRequest( request() .withSecure(true) .withBody("{" + NEW_LINE + " \"id\": 1," + NEW_LINE + " \"name\": \"A green door\"," + NEW_LINE + " \"price\": 12.50," + NEW_LINE + " \"tags\": [\"home\", \"green\"]" + NEW_LINE + "}"), headersToIgnore) ); } @Test public void shouldClearExpectationsWithParameterBody() { // given mockServerClient .when( request() .withBody(params(param("bodyParameterNameOne", "bodyParameterValueOne"))) ) .respond( response() .withBody("some_body1") ); mockServerClient .when( request() .withBody(params(param("bodyParameterNameTwo", "bodyParameterValueTwo"))) ) .respond( response() .withBody("some_body2") ); // then assertEquals( response() .withStatusCode(OK_200.code()) .withReasonPhrase(OK_200.reasonPhrase()) .withBody("some_body1"), makeRequest( request() .withBody(params(param("bodyParameterName.*", "bodyParameterValue.*"))), headersToIgnore) ); // when mockServerClient .clear( request() .withBody(params(param("bodyParameterNameOne", "bodyParameterValueOne"))) ); // then assertThat( mockServerClient.retrieveActiveExpectations(null), arrayContaining( new Expectation(request() .withBody(params(param("bodyParameterNameTwo", "bodyParameterValueTwo")))) .thenRespond( response() .withBody("some_body2") ) ) ); // - in http assertEquals( response() .withStatusCode(OK_200.code()) .withReasonPhrase(OK_200.reasonPhrase()) .withBody("some_body2"), makeRequest( request() .withBody(params(param("bodyParameterName.*", "bodyParameterValue.*"))), headersToIgnore) ); // - in https assertEquals( response() .withStatusCode(OK_200.code()) .withReasonPhrase(OK_200.reasonPhrase()) .withBody("some_body2"), makeRequest( request() .withSecure(true) .withBody(params(param("bodyParameterName.*", "bodyParameterValue.*"))), headersToIgnore) ); } @Test public void shouldEnsureThatInterruptedRequestsAreVerifiable() throws Exception { mockServerClient .when( request(calculatePath("delayed")) ) .respond( response("delayed data") .withDelay(new Delay(TimeUnit.SECONDS, 3)) ); Future<HttpResponse> delayedFuture = Executors.newSingleThreadExecutor().submit(new Callable<HttpResponse>() { @Override public HttpResponse call() throws Exception { return httpClient.sendRequest( request(addContextToPath(calculatePath("delayed"))) .withHeader(HOST.toString(), "localhost:" + getServerPort()) ).get(10, TimeUnit.SECONDS); } }); Uninterruptibles.sleepUninterruptibly(1, TimeUnit.SECONDS); // Let request reach server delayedFuture.cancel(true); // Then interrupt requesting thread mockServerClient.verify(request(calculatePath("delayed"))); // We should be able to verify request that reached server even though its later interrupted } @Test public void shouldEnsureThatRequestDelaysDoNotAffectOtherRequests() throws Exception { mockServerClient .when( request("/slow") ) .respond( response("super slow") .withDelay(new Delay(TimeUnit.SECONDS, 5)) ); mockServerClient .when( request("/fast") ) .respond( response("quite fast") ); ExecutorService executorService = Executors.newFixedThreadPool(2); Future<Long> slowFuture = executorService.submit(new Callable<Long>() { @Override public Long call() throws Exception { long start = System.currentTimeMillis(); makeRequest(request("/slow"), Collections.<String>emptySet()); return System.currentTimeMillis() - start; } }); // Let fast request come to the server slightly after slow request Uninterruptibles.sleepUninterruptibly(1, TimeUnit.SECONDS); Future<Long> fastFuture = executorService.submit(new Callable<Long>() { @Override public Long call() throws Exception { long start = System.currentTimeMillis(); makeRequest(request("/fast"), Collections.<String>emptySet()); return System.currentTimeMillis() - start; } }); Long slowRequestElapsedMillis = slowFuture.get(); Long fastRequestElapsedMillis = fastFuture.get(); assertThat("Slow request takes less than expected", slowRequestElapsedMillis, is(greaterThan(5 * 1000L))); assertThat("Fast request takes longer than expected", fastRequestElapsedMillis, is(lessThan(5 * 1000L))); } }
mathewjoy/mockserver
mockserver-integration-testing/src/main/java/org/mockserver/integration/server/AbstractExtendedMockingIntegrationTest.java
936
package org.mockserver.integration.server; import com.fasterxml.jackson.databind.ObjectMapper; import com.google.common.net.MediaType; import com.google.common.util.concurrent.Uninterruptibles; import io.netty.util.CharsetUtil; import org.apache.commons.io.IOUtils; import org.junit.Test; import org.mockserver.logging.MockServerLogger; import org.mockserver.matchers.MatchType; import org.mockserver.matchers.TimeToLive; import org.mockserver.mock.Expectation; import org.mockserver.model.*; import org.mockserver.serialization.ExpectationSerializer; import org.mockserver.serialization.HttpRequestSerializer; import org.mockserver.serialization.JsonArraySerializer; import org.mockserver.serialization.ObjectMapperFactory; import org.mockserver.serialization.java.ExpectationToJavaSerializer; import org.mockserver.verify.VerificationTimes; import java.io.IOException; import java.nio.charset.StandardCharsets; import java.util.*; import java.util.concurrent.*; import static io.netty.handler.codec.http.HttpHeaderNames.*; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.*; import static org.hamcrest.core.Is.is; import static org.hamcrest.core.StringStartsWith.startsWith; import static org.hamcrest.number.OrderingComparison.greaterThan; import static org.junit.Assert.assertEquals; import static org.junit.Assert.fail; import static org.mockserver.character.Character.NEW_LINE; import static org.mockserver.matchers.Times.exactly; import static org.mockserver.model.BinaryBody.binary; import static org.mockserver.model.Cookie.cookie; import static org.mockserver.model.Header.header; import static org.mockserver.model.HttpForward.forward; import static org.mockserver.model.HttpRequest.request; import static org.mockserver.model.HttpResponse.notFoundResponse; import static org.mockserver.model.HttpResponse.response; import static org.mockserver.model.HttpStatusCode.NOT_FOUND_404; import static org.mockserver.model.HttpStatusCode.OK_200; import static org.mockserver.model.JsonBody.json; import static org.mockserver.model.JsonPathBody.jsonPath; import static org.mockserver.model.JsonSchemaBody.jsonSchema; import static org.mockserver.model.NottableString.not; import static org.mockserver.model.NottableString.string; import static org.mockserver.model.Parameter.param; import static org.mockserver.model.ParameterBody.params; import static org.mockserver.model.RegexBody.regex; import static org.mockserver.model.StringBody.exact; import static org.mockserver.model.StringBody.subString; import static org.mockserver.model.XPathBody.xpath; import static org.mockserver.model.XmlBody.xml; import static org.mockserver.model.XmlSchemaBody.xmlSchema; import static org.mockserver.model.XmlSchemaBody.xmlSchemaFromResource; /** * @author jamesdbloom */ public abstract class AbstractExtendedMockingIntegrationTest extends AbstractBasicMockingIntegrationTest { @Test public void shouldReturnResponseForRequestInSsl() { // when mockServerClient.when(request().withSecure(true)).respond(response().withBody("some_body")); // then // - in http assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()) .withReasonPhrase(HttpStatusCode.NOT_FOUND_404.reasonPhrase()), makeRequest( request() .withPath(calculatePath("")), headersToIgnore) ); // - in https assertEquals( response() .withStatusCode(OK_200.code()) .withReasonPhrase(OK_200.reasonPhrase()) .withBody("some_body"), makeRequest( request() .withSecure(true) .withPath(calculatePath("")), headersToIgnore) ); } @Test public void shouldReturnResponseForRequestNotInSsl() { // when mockServerClient.when(request().withSecure(false)).respond(response().withBody("some_body")); // then // - in http assertEquals( response() .withStatusCode(OK_200.code()) .withReasonPhrase(OK_200.reasonPhrase()) .withBody("some_body"), makeRequest( request() .withPath(calculatePath("")), headersToIgnore) ); // - in https assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()) .withReasonPhrase(HttpStatusCode.NOT_FOUND_404.reasonPhrase()), makeRequest( request() .withSecure(true) .withPath(calculatePath("")), headersToIgnore) ); } @Test public void shouldReturnResponseByMatchingPath() { // when mockServerClient .when( request() .withPath(calculatePath("some_path1")) ) .respond( response() .withBody("some_body1") ); mockServerClient .when( request() .withPath(calculatePath("some_path2")) ) .respond( response() .withBody("some_body2") ); // then // - in http assertEquals( response() .withStatusCode(OK_200.code()) .withReasonPhrase(OK_200.reasonPhrase()) .withBody("some_body2"), makeRequest( request() .withPath(calculatePath("some_path2")), headersToIgnore) ); assertEquals( response() .withStatusCode(OK_200.code()) .withReasonPhrase(OK_200.reasonPhrase()) .withBody("some_body1"), makeRequest( request() .withPath(calculatePath("some_path1")), headersToIgnore) ); // - in https assertEquals( response() .withStatusCode(OK_200.code()) .withReasonPhrase(OK_200.reasonPhrase()) .withBody("some_body2"), makeRequest( request() .withSecure(true) .withPath(calculatePath("some_path2")), headersToIgnore) ); assertEquals( response() .withStatusCode(OK_200.code()) .withReasonPhrase(OK_200.reasonPhrase()) .withBody("some_body1"), makeRequest( request() .withSecure(true) .withPath(calculatePath("some_path1")), headersToIgnore) ); } @Test public void shouldReturnResponseByMatchingPathExactTimes() { // when mockServerClient .when( request() .withPath(calculatePath("some_path")), exactly(2) ) .respond( response() .withBody("some_body") ); // then // - in http assertEquals( response() .withStatusCode(OK_200.code()) .withReasonPhrase(OK_200.reasonPhrase()) .withBody("some_body"), makeRequest( request() .withPath(calculatePath("some_path")), headersToIgnore) ); // - in https assertEquals( response() .withStatusCode(OK_200.code()) .withReasonPhrase(OK_200.reasonPhrase()) .withBody("some_body"), makeRequest( request() .withSecure(true) .withPath(calculatePath("some_path")), headersToIgnore) ); // - in http assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()) .withReasonPhrase(HttpStatusCode.NOT_FOUND_404.reasonPhrase()), makeRequest( request() .withPath(calculatePath("some_path")), headersToIgnore) ); // - in https assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()) .withReasonPhrase(HttpStatusCode.NOT_FOUND_404.reasonPhrase()), makeRequest( request() .withSecure(true) .withPath(calculatePath("some_path")), headersToIgnore) ); } @Test public void shouldReturnResponseWhenTimeToLiveHasNotExpired() { // when mockServerClient .when( request().withPath(calculatePath("some_path")), exactly(2), TimeToLive.exactly(TimeUnit.HOURS, 1L) ) .respond( response().withBody("some_body") ); // then // - in http assertEquals( response() .withStatusCode(OK_200.code()) .withReasonPhrase(OK_200.reasonPhrase()) .withBody("some_body"), makeRequest( request() .withPath(calculatePath("some_path")), headersToIgnore) ); // - in https assertEquals( response() .withStatusCode(OK_200.code()) .withReasonPhrase(OK_200.reasonPhrase()) .withBody("some_body"), makeRequest( request() .withSecure(true) .withPath(calculatePath("some_path")), headersToIgnore) ); // - in http assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()) .withReasonPhrase(HttpStatusCode.NOT_FOUND_404.reasonPhrase()), makeRequest( request() .withPath(calculatePath("some_path")), headersToIgnore) ); // - in https assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()) .withReasonPhrase(HttpStatusCode.NOT_FOUND_404.reasonPhrase()), makeRequest( request() .withSecure(true) .withPath(calculatePath("some_path")), headersToIgnore) ); } @Test public void shouldReturnMatchRequestWithBodyInUTF16() { // when String body = "我说中国话"; mockServerClient .when( request() .withBody(body, StandardCharsets.UTF_16) ) .respond( response() .withBody(body, StandardCharsets.UTF_8) ); // then // - in http assertEquals( response() .withStatusCode(OK_200.code()) .withReasonPhrase(OK_200.reasonPhrase()) .withHeader(CONTENT_TYPE.toString(), MediaType.PLAIN_TEXT_UTF_8.toString()) .withBody(body, MediaType.PLAIN_TEXT_UTF_8), makeRequest( request() .withPath(calculatePath("")) .withBody(body, StandardCharsets.UTF_16), headersToIgnore) ); // - in https assertEquals( response() .withStatusCode(OK_200.code()) .withReasonPhrase(OK_200.reasonPhrase()) .withHeader(CONTENT_TYPE.toString(), MediaType.PLAIN_TEXT_UTF_8.toString()) .withBody(body, MediaType.PLAIN_TEXT_UTF_8), makeRequest( request() .withSecure(true) .withPath(calculatePath("")) .withBody(body, StandardCharsets.UTF_16), headersToIgnore) ); } @Test public void shouldReturnMatchRequestWithBodyInUTF8WithContentTypeHeader() { // when String body = "我说中国话"; mockServerClient .when( request() .withHeader(CONTENT_TYPE.toString(), MediaType.PLAIN_TEXT_UTF_8.toString()) .withBody(body) ) .respond( response() .withBody(body, StandardCharsets.UTF_8) ); // then // - in http assertEquals( response() .withStatusCode(OK_200.code()) .withReasonPhrase(OK_200.reasonPhrase()) .withHeader(CONTENT_TYPE.toString(), MediaType.PLAIN_TEXT_UTF_8.toString()) .withBody(body, MediaType.PLAIN_TEXT_UTF_8), makeRequest( request() .withHeader(CONTENT_TYPE.toString(), MediaType.PLAIN_TEXT_UTF_8.toString()) .withPath(calculatePath("")) .withBody(body, StandardCharsets.UTF_8), headersToIgnore) ); // - in https assertEquals( response() .withStatusCode(OK_200.code()) .withReasonPhrase(OK_200.reasonPhrase()) .withHeader(CONTENT_TYPE.toString(), MediaType.PLAIN_TEXT_UTF_8.toString()) .withBody(body, MediaType.PLAIN_TEXT_UTF_8), makeRequest( request() .withHeader(CONTENT_TYPE.toString(), MediaType.PLAIN_TEXT_UTF_8.toString()) .withSecure(true) .withPath(calculatePath("")) .withBody(body, StandardCharsets.UTF_8), headersToIgnore) ); } @Test public void shouldReturnResponseWithBodyInUTF16() { // when String body = "我说中国话"; mockServerClient .when( request() .withHeader(CONTENT_TYPE.toString(), MediaType.create("text", "plain").withCharset(StandardCharsets.UTF_16).toString()) .withBody(body) ) .respond( response() .withHeader(CONTENT_TYPE.toString(), MediaType.create("text", "plain").withCharset(StandardCharsets.UTF_16).toString()) .withBody(body, StandardCharsets.UTF_16) ); // then // - in http assertEquals( response() .withStatusCode(OK_200.code()) .withReasonPhrase(OK_200.reasonPhrase()) .withHeader(CONTENT_TYPE.toString(), MediaType.create("text", "plain").withCharset(StandardCharsets.UTF_16).toString()) .withBody(body, StandardCharsets.UTF_16), makeRequest( request() .withHeader(CONTENT_TYPE.toString(), MediaType.create("text", "plain").withCharset(StandardCharsets.UTF_16).toString()) .withPath(calculatePath("")) .withBody(body), headersToIgnore) ); // - in https assertEquals( response() .withStatusCode(OK_200.code()) .withReasonPhrase(OK_200.reasonPhrase()) .withHeader(CONTENT_TYPE.toString(), MediaType.create("text", "plain").withCharset(StandardCharsets.UTF_16).toString()) .withBody(body, StandardCharsets.UTF_16), makeRequest( request() .withHeader(CONTENT_TYPE.toString(), MediaType.create("text", "plain").withCharset(StandardCharsets.UTF_16).toString()) .withSecure(true) .withPath(calculatePath("")) .withBody(body), headersToIgnore) ); } @Test public void shouldReturnResponseWithBodyInUTF8WithContentTypeHeader() { // when String body = "我说中国话"; mockServerClient .when( request() ) .respond( response() .withHeader(CONTENT_TYPE.toString(), MediaType.PLAIN_TEXT_UTF_8.toString()) .withBody(body) ); // then // - in http assertEquals( response() .withStatusCode(OK_200.code()) .withReasonPhrase(OK_200.reasonPhrase()) .withHeader(CONTENT_TYPE.toString(), MediaType.PLAIN_TEXT_UTF_8.toString()) .withBody(body, MediaType.PLAIN_TEXT_UTF_8), makeRequest( request() .withPath(calculatePath("")), headersToIgnore) ); // - in https assertEquals( response() .withStatusCode(OK_200.code()) .withReasonPhrase(OK_200.reasonPhrase()) .withHeader(CONTENT_TYPE.toString(), MediaType.PLAIN_TEXT_UTF_8.toString()) .withBody(body, MediaType.PLAIN_TEXT_UTF_8), makeRequest( request() .withSecure(true) .withPath(calculatePath("")), headersToIgnore) ); } @Test public void shouldReturnResponseWithBodyInUTF8WithNoContentTypeHeader() { // when String body = "我说中国话"; mockServerClient .when( request() ) .respond( response() .withBody(body, CharsetUtil.UTF_8) ); // then // - in http assertEquals( response() .withStatusCode(OK_200.code()) .withReasonPhrase(OK_200.reasonPhrase()) .withHeader(CONTENT_TYPE.toString(), MediaType.PLAIN_TEXT_UTF_8.toString()) .withBody(body, CharsetUtil.UTF_8), makeRequest( request() .withPath(calculatePath("")), headersToIgnore) ); // - in https assertEquals( response() .withStatusCode(OK_200.code()) .withReasonPhrase(OK_200.reasonPhrase()) .withHeader(CONTENT_TYPE.toString(), MediaType.PLAIN_TEXT_UTF_8.toString()) .withBody(body, CharsetUtil.UTF_8), makeRequest( request() .withSecure(true) .withPath(calculatePath("")), headersToIgnore) ); } @Test public void shouldReturnResponseByMatchingSubStringBody() { // when mockServerClient .when( request() .withBody( subString("random") ), exactly(2) ) .respond( response() .withBody("some_sub_string_body_response") ); // then // - in http assertEquals( response() .withStatusCode(OK_200.code()) .withReasonPhrase(OK_200.reasonPhrase()) .withBody("some_sub_string_body_response"), makeRequest( request() .withMethod("POST") .withPath(calculatePath("some_path")) .withBody("some_random_body"), headersToIgnore) ); // - in https assertEquals( response() .withStatusCode(OK_200.code()) .withReasonPhrase(OK_200.reasonPhrase()) .withBody("some_sub_string_body_response"), makeRequest( request() .withSecure(true) .withMethod("POST") .withPath(calculatePath("some_path")) .withBody("some_random_body"), headersToIgnore) ); } @Test public void shouldReturnResponseByMatchingNotRegexBody() { // when mockServerClient .when( request() .withMethod("POST") .withBody(Body.not(regex("10\\.\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}"))) ) .respond( response() .withBody("some_not_regex_body_response") ); // then // - in http // should not match (because body matches regex) assertEquals( response() .withStatusCode(NOT_FOUND_404.code()) .withReasonPhrase(NOT_FOUND_404.reasonPhrase()), makeRequest( request() .withMethod("POST") .withBody("10.2.3.123"), headersToIgnore) ); // should match (because body doesn't matches regex) assertEquals( response() .withStatusCode(OK_200.code()) .withReasonPhrase(OK_200.reasonPhrase()) .withBody("some_not_regex_body_response"), makeRequest( request() .withMethod("POST") .withBody("10.2.3.1234"), headersToIgnore) ); // - in https // should not match (because body matches regex) assertEquals( response() .withStatusCode(NOT_FOUND_404.code()) .withReasonPhrase(NOT_FOUND_404.reasonPhrase()), makeRequest( request() .withSecure(true) .withMethod("POST") .withBody("10.2.3.123"), headersToIgnore) ); // should match (because body doesn't matches regex) assertEquals( response() .withStatusCode(OK_200.code()) .withReasonPhrase(OK_200.reasonPhrase()) .withBody("some_not_regex_body_response"), makeRequest( request() .withSecure(true) .withMethod("POST") .withBody("10.2.3.1234"), headersToIgnore) ); } @Test public void shouldReturnResponseByMatchingNotSubStringBody() { // when mockServerClient .when( request() .withMethod("POST") .withBody(Body.not(subString("some_body"))) ) .respond( response() .withBody("some_not_regex_body_response") ); // then // - in http // should not match (because body matches regex) assertEquals( response() .withStatusCode(NOT_FOUND_404.code()) .withReasonPhrase(NOT_FOUND_404.reasonPhrase()), makeRequest( request() .withMethod("POST") .withBody("some_body_full_string"), headersToIgnore) ); // should match (because body doesn't matches regex) assertEquals( response() .withStatusCode(OK_200.code()) .withReasonPhrase(OK_200.reasonPhrase()) .withBody("some_not_regex_body_response"), makeRequest( request() .withMethod("POST") .withBody("some_other_body_full_string"), headersToIgnore) ); // - in https // should not match (because body matches regex) assertEquals( response() .withStatusCode(NOT_FOUND_404.code()) .withReasonPhrase(NOT_FOUND_404.reasonPhrase()), makeRequest( request() .withSecure(true) .withMethod("POST") .withBody("some_body_full_string"), headersToIgnore) ); // should match (because body doesn't matches regex) assertEquals( response() .withStatusCode(OK_200.code()) .withReasonPhrase(OK_200.reasonPhrase()) .withBody("some_not_regex_body_response"), makeRequest( request() .withSecure(true) .withMethod("POST") .withBody("some_other_body_full_string"), headersToIgnore) ); } @Test public void shouldReturnResponseByMatchingNotExactBody() { // when mockServerClient .when( request() .withMethod("POST") .withBody(Body.not(exact("some_body"))) ) .respond( response() .withBody("some_not_regex_body_response") ); // then // - in http // should not match (because body matches regex) assertEquals( response() .withStatusCode(NOT_FOUND_404.code()) .withReasonPhrase(NOT_FOUND_404.reasonPhrase()), makeRequest( request() .withMethod("POST") .withBody("some_body"), headersToIgnore) ); // should match (because body doesn't matches regex) assertEquals( response() .withStatusCode(OK_200.code()) .withReasonPhrase(OK_200.reasonPhrase()) .withBody("some_not_regex_body_response"), makeRequest( request() .withMethod("POST") .withBody("some_other_body"), headersToIgnore) ); // - in https // should not match (because body matches regex) assertEquals( response() .withStatusCode(NOT_FOUND_404.code()) .withReasonPhrase(NOT_FOUND_404.reasonPhrase()), makeRequest( request() .withSecure(true) .withMethod("POST") .withBody("some_body"), headersToIgnore) ); // should match (because body doesn't matches regex) assertEquals( response() .withStatusCode(OK_200.code()) .withReasonPhrase(OK_200.reasonPhrase()) .withBody("some_not_regex_body_response"), makeRequest( request() .withSecure(true) .withMethod("POST") .withBody("some_other_body"), headersToIgnore) ); } @Test public void shouldReturnResponseByMatchingBodyWithXPath() { // when mockServerClient.when(request().withBody(xpath("/bookstore/book[price>30]/price")), exactly(2)).respond(response().withBody("some_body")); // then // - in http assertEquals( response() .withStatusCode(OK_200.code()) .withReasonPhrase(OK_200.reasonPhrase()) .withBody("some_body"), makeRequest( request() .withPath(calculatePath("some_path")) .withMethod("POST") .withBody(new StringBody("" + "<?xml version=\"1.0\" encoding=\"ISO-8859-1\"?>" + NEW_LINE + "<bookstore>" + NEW_LINE + " <book category=\"COOKING\">" + NEW_LINE + " <title lang=\"en\">Everyday Italian</title>" + NEW_LINE + " <author>Giada De Laurentiis</author>" + NEW_LINE + " <year>2005</year>" + NEW_LINE + " <price>30.00</price>" + NEW_LINE + " </book>" + NEW_LINE + " <book category=\"CHILDREN\">" + NEW_LINE + " <title lang=\"en\">Harry Potter</title>" + NEW_LINE + " <author>J K. Rowling</author>" + NEW_LINE + " <year>2005</year>" + NEW_LINE + " <price>29.99</price>" + NEW_LINE + " </book>" + NEW_LINE + " <book category=\"WEB\">" + NEW_LINE + " <title lang=\"en\">Learning XML</title>" + NEW_LINE + " <author>Erik T. Ray</author>" + NEW_LINE + " <year>2003</year>" + NEW_LINE + " <price>31.95</price>" + NEW_LINE + " </book>" + NEW_LINE + "</bookstore>")), headersToIgnore) ); // - in https assertEquals( response() .withStatusCode(OK_200.code()) .withReasonPhrase(OK_200.reasonPhrase()) .withBody("some_body"), makeRequest( request() .withSecure(true) .withPath(calculatePath("some_path")) .withMethod("POST") .withBody(new StringBody("" + "<?xml version=\"1.0\" encoding=\"ISO-8859-1\"?>" + NEW_LINE + "<bookstore>" + NEW_LINE + " <book category=\"COOKING\">" + NEW_LINE + " <title lang=\"en\">Everyday Italian</title>" + NEW_LINE + " <author>Giada De Laurentiis</author>" + NEW_LINE + " <year>2005</year>" + NEW_LINE + " <price>30.00</price>" + NEW_LINE + " </book>" + NEW_LINE + " <book category=\"CHILDREN\">" + NEW_LINE + " <title lang=\"en\">Harry Potter</title>" + NEW_LINE + " <author>J K. Rowling</author>" + NEW_LINE + " <year>2005</year>" + NEW_LINE + " <price>29.99</price>" + NEW_LINE + " </book>" + NEW_LINE + " <book category=\"WEB\">" + NEW_LINE + " <title lang=\"en\">Learning XML</title>" + NEW_LINE + " <author>Erik T. Ray</author>" + NEW_LINE + " <year>2003</year>" + NEW_LINE + " <price>31.95</price>" + NEW_LINE + " </book>" + NEW_LINE + "</bookstore>")), headersToIgnore) ); } @Test public void shouldReturnResponseByMatchingBodyWithXmlSchema() { // when mockServerClient.when(request() .withBody( xmlSchema("<?xml version=\"1.0\" encoding=\"UTF-8\"?>" + NEW_LINE + "<xs:schema xmlns:xs=\"http://www.w3.org/2001/XMLSchema\" elementFormDefault=\"qualified\" attributeFormDefault=\"unqualified\">" + NEW_LINE + " <!-- XML Schema Generated from XML Document on Wed Jun 28 2017 21:52:45 GMT+0100 (BST) -->" + NEW_LINE + " <!-- with XmlGrid.net Free Online Service http://xmlgrid.net -->" + NEW_LINE + " <xs:element name=\"notes\">" + NEW_LINE + " <xs:complexType>" + NEW_LINE + " <xs:sequence>" + NEW_LINE + " <xs:element name=\"note\" maxOccurs=\"unbounded\">" + NEW_LINE + " <xs:complexType>" + NEW_LINE + " <xs:sequence>" + NEW_LINE + " <xs:element name=\"to\" minOccurs=\"1\" maxOccurs=\"1\" type=\"xs:string\"></xs:element>" + NEW_LINE + " <xs:element name=\"from\" minOccurs=\"1\" maxOccurs=\"1\" type=\"xs:string\"></xs:element>" + NEW_LINE + " <xs:element name=\"heading\" minOccurs=\"1\" maxOccurs=\"1\" type=\"xs:string\"></xs:element>" + NEW_LINE + " <xs:element name=\"body\" minOccurs=\"1\" maxOccurs=\"1\" type=\"xs:string\"></xs:element>" + NEW_LINE + " </xs:sequence>" + NEW_LINE + " </xs:complexType>" + NEW_LINE + " </xs:element>" + NEW_LINE + " </xs:sequence>" + NEW_LINE + " </xs:complexType>" + NEW_LINE + " </xs:element>" + NEW_LINE + "</xs:schema>")), exactly(2) ) .respond( response() .withBody("some_body") ); // then // - in http assertEquals( response() .withStatusCode(NOT_FOUND_404.code()) .withReasonPhrase(NOT_FOUND_404.reasonPhrase()), makeRequest( request() .withMethod("POST") .withBody("<?xml version=\"1.0\" encoding=\"utf-8\"?>" + NEW_LINE + "<notes>" + NEW_LINE + " <note>" + NEW_LINE + " <to>Bob</to>" + NEW_LINE + " <heading>Reminder</heading>" + NEW_LINE + " <body>Buy Bread</body>" + NEW_LINE + " </note>" + NEW_LINE + " <note>" + NEW_LINE + " <to>Jack</to>" + NEW_LINE + " <from>Jill</from>" + NEW_LINE + " <heading>Reminder</heading>" + NEW_LINE + " <body>Wash Shirts</body>" + NEW_LINE + " </note>" + NEW_LINE + "</notes>"), headersToIgnore) ); assertEquals( response() .withStatusCode(OK_200.code()) .withReasonPhrase(OK_200.reasonPhrase()) .withBody("some_body"), makeRequest( request() .withPath(calculatePath("some_path")) .withMethod("POST") .withBody("<?xml version=\"1.0\" encoding=\"utf-8\"?>" + NEW_LINE + "<notes>" + NEW_LINE + " <note>" + NEW_LINE + " <to>Bob</to>" + NEW_LINE + " <from>Bill</from>" + NEW_LINE + " <heading>Reminder</heading>" + NEW_LINE + " <body>Buy Bread</body>" + NEW_LINE + " </note>" + NEW_LINE + " <note>" + NEW_LINE + " <to>Jack</to>" + NEW_LINE + " <from>Jill</from>" + NEW_LINE + " <heading>Reminder</heading>" + NEW_LINE + " <body>Wash Shirts</body>" + NEW_LINE + " </note>" + NEW_LINE + "</notes>"), headersToIgnore) ); // - in https assertEquals( response() .withStatusCode(OK_200.code()) .withReasonPhrase(OK_200.reasonPhrase()) .withBody("some_body"), makeRequest( request() .withSecure(true) .withPath(calculatePath("some_path")) .withMethod("POST") .withBody("<?xml version=\"1.0\" encoding=\"utf-8\"?>" + NEW_LINE + "<notes>" + NEW_LINE + " <note>" + NEW_LINE + " <to>Bob</to>" + NEW_LINE + " <from>Bill</from>" + NEW_LINE + " <heading>Reminder</heading>" + NEW_LINE + " <body>Buy Bread</body>" + NEW_LINE + " </note>" + NEW_LINE + " <note>" + NEW_LINE + " <to>Jack</to>" + NEW_LINE + " <from>Jill</from>" + NEW_LINE + " <heading>Reminder</heading>" + NEW_LINE + " <body>Wash Shirts</body>" + NEW_LINE + " </note>" + NEW_LINE + "</notes>"), headersToIgnore) ); } @Test public void shouldReturnResponseByMatchingBodyWithXmlSchemaByClasspath() { // when mockServerClient.when(request() .withBody( xmlSchemaFromResource("org/mockserver/model/testXmlSchema.xsd")), exactly(2) ) .respond( response() .withBody("some_body") ); // then // - in http assertEquals( response() .withStatusCode(NOT_FOUND_404.code()) .withReasonPhrase(NOT_FOUND_404.reasonPhrase()), makeRequest( request() .withMethod("POST") .withBody("<?xml version=\"1.0\" encoding=\"utf-8\"?>" + NEW_LINE + "<notes>" + NEW_LINE + " <note>" + NEW_LINE + " <to>Bob</to>" + NEW_LINE + " <heading>Reminder</heading>" + NEW_LINE + " <body>Buy Bread</body>" + NEW_LINE + " </note>" + NEW_LINE + " <note>" + NEW_LINE + " <to>Jack</to>" + NEW_LINE + " <from>Jill</from>" + NEW_LINE + " <heading>Reminder</heading>" + NEW_LINE + " <body>Wash Shirts</body>" + NEW_LINE + " </note>" + NEW_LINE + "</notes>"), headersToIgnore) ); assertEquals( response() .withStatusCode(OK_200.code()) .withReasonPhrase(OK_200.reasonPhrase()) .withBody("some_body"), makeRequest( request() .withPath(calculatePath("some_path")) .withMethod("POST") .withBody("<?xml version=\"1.0\" encoding=\"utf-8\"?>" + NEW_LINE + "<notes>" + NEW_LINE + " <note>" + NEW_LINE + " <to>Bob</to>" + NEW_LINE + " <from>Bill</from>" + NEW_LINE + " <heading>Reminder</heading>" + NEW_LINE + " <body>Buy Bread</body>" + NEW_LINE + " </note>" + NEW_LINE + " <note>" + NEW_LINE + " <to>Jack</to>" + NEW_LINE + " <from>Jill</from>" + NEW_LINE + " <heading>Reminder</heading>" + NEW_LINE + " <body>Wash Shirts</body>" + NEW_LINE + " </note>" + NEW_LINE + "</notes>"), headersToIgnore) ); // - in https assertEquals( response() .withStatusCode(OK_200.code()) .withReasonPhrase(OK_200.reasonPhrase()) .withBody("some_body"), makeRequest( request() .withSecure(true) .withPath(calculatePath("some_path")) .withMethod("POST") .withBody("<?xml version=\"1.0\" encoding=\"utf-8\"?>" + NEW_LINE + "<notes>" + NEW_LINE + " <note>" + NEW_LINE + " <to>Bob</to>" + NEW_LINE + " <from>Bill</from>" + NEW_LINE + " <heading>Reminder</heading>" + NEW_LINE + " <body>Buy Bread</body>" + NEW_LINE + " </note>" + NEW_LINE + " <note>" + NEW_LINE + " <to>Jack</to>" + NEW_LINE + " <from>Jill</from>" + NEW_LINE + " <heading>Reminder</heading>" + NEW_LINE + " <body>Wash Shirts</body>" + NEW_LINE + " </note>" + NEW_LINE + "</notes>"), headersToIgnore) ); } @Test public void shouldReturnResponseByMatchingBodyWithXml() { // when mockServerClient.when(request().withBody(xml("" + "<bookstore>" + NEW_LINE + " <book nationality=\"ITALIAN\" category=\"COOKING\"><title lang=\"en\">Everyday Italian</title><author>Giada De Laurentiis</author><year>2005</year><price>30.00</price></book>" + NEW_LINE + "</bookstore>")), exactly(2)).respond(response().withBody("some_body")); // then // - in http assertEquals( response() .withStatusCode(OK_200.code()) .withReasonPhrase(OK_200.reasonPhrase()) .withBody("some_body"), makeRequest( request() .withPath(calculatePath("some_path")) .withMethod("POST") .withBody(new StringBody("" + "<?xml version=\"1.0\" encoding=\"ISO-8859-1\"?>" + NEW_LINE + "<bookstore>" + NEW_LINE + " <book category=\"COOKING\" nationality=\"ITALIAN\">" + NEW_LINE + " <title lang=\"en\">Everyday Italian</title>" + NEW_LINE + " <author>Giada De Laurentiis</author>" + NEW_LINE + " <year>2005</year>" + NEW_LINE + " <price>30.00</price>" + NEW_LINE + " </book>" + NEW_LINE + "</bookstore>")), headersToIgnore) ); // - in https assertEquals( response() .withStatusCode(OK_200.code()) .withReasonPhrase(OK_200.reasonPhrase()) .withBody("some_body"), makeRequest( request() .withSecure(true) .withPath(calculatePath("some_path")) .withMethod("POST") .withBody(new StringBody("" + "<?xml version=\"1.0\" encoding=\"ISO-8859-1\"?>" + NEW_LINE + "<bookstore>" + NEW_LINE + " <book category=\"COOKING\" nationality=\"ITALIAN\">" + NEW_LINE + " <title lang=\"en\">Everyday Italian</title>" + NEW_LINE + " <author>Giada De Laurentiis</author>" + NEW_LINE + " <year>2005</year>" + NEW_LINE + " <price>30.00</price>" + NEW_LINE + " </book>" + NEW_LINE + "</bookstore>")), headersToIgnore) ); } @Test public void shouldReturnResponseByMatchingBodyWithJson() { // when mockServerClient .when( request() .withBody(json("{" + NEW_LINE + " \"id\": 1," + NEW_LINE + " \"name\": \"A green door\"," + NEW_LINE + " \"price\": 12.50," + NEW_LINE + " \"tags\": [\"home\", \"green\"]" + NEW_LINE + "}")), exactly(2) ) .respond( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withReasonPhrase(HttpStatusCode.ACCEPTED_202.reasonPhrase()) .withBody("some_body") ); // then // - in http assertEquals( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withReasonPhrase(HttpStatusCode.ACCEPTED_202.reasonPhrase()) .withBody("some_body"), makeRequest( request() .withPath(calculatePath("some_path")) .withMethod("POST") .withBody("{" + NEW_LINE + " \"id\": 1," + NEW_LINE + " \"extra ignored field\": \"some value\"," + NEW_LINE + " \"name\": \"A green door\"," + NEW_LINE + " \"price\": 12.50," + NEW_LINE + " \"tags\": [\"home\", \"green\"]" + NEW_LINE + "}"), headersToIgnore) ); // - in https assertEquals( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withReasonPhrase(HttpStatusCode.ACCEPTED_202.reasonPhrase()) .withBody("some_body"), makeRequest( request() .withSecure(true) .withPath(calculatePath("some_path")) .withMethod("POST") .withBody("{" + NEW_LINE + " \"id\": 1," + NEW_LINE + " \"extra ignored array\": [\"one\", \"two\"]," + NEW_LINE + " \"name\": \"A green door\"," + NEW_LINE + " \"price\": 12.50," + NEW_LINE + " \"tags\": [\"home\", \"green\"]" + NEW_LINE + "}"), headersToIgnore) ); } @Test public void shouldReturnResponseByMatchingBodyWithJsonWithCharsetUTF8() { // when mockServerClient .when( request() .withBody(json("{" + NEW_LINE + " \"ταυτότητα\": 1," + NEW_LINE + " \"όνομα\": \"μια πράσινη πόρτα\"," + NEW_LINE + " \"τιμή\": 12.50," + NEW_LINE + " \"ετικέτες\": [\"σπίτι\", \"πράσινος\"]" + NEW_LINE + "}", StandardCharsets.UTF_16, MatchType.ONLY_MATCHING_FIELDS)), exactly(2) ) .respond( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withReasonPhrase(HttpStatusCode.ACCEPTED_202.reasonPhrase()) .withBody("some_body") ); // then // - in http assertEquals( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withReasonPhrase(HttpStatusCode.ACCEPTED_202.reasonPhrase()) .withBody("some_body"), makeRequest( request() .withPath(calculatePath("some_path")) .withMethod("POST") .withBody(json("{" + NEW_LINE + " \"ταυτότητα\": 1," + NEW_LINE + " \"επιπλέον αγνοούνται τομέα\": \"κάποια αξία\"," + NEW_LINE + " \"όνομα\": \"μια πράσινη πόρτα\"," + NEW_LINE + " \"τιμή\": 12.50," + NEW_LINE + " \"ετικέτες\": [\"σπίτι\", \"πράσινος\"]" + NEW_LINE + "}", StandardCharsets.UTF_16, MatchType.ONLY_MATCHING_FIELDS)), headersToIgnore) ); // - in https assertEquals( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withReasonPhrase(HttpStatusCode.ACCEPTED_202.reasonPhrase()) .withBody("some_body"), makeRequest( request() .withSecure(true) .withPath(calculatePath("some_path")) .withMethod("POST") .withBody(json("{" + NEW_LINE + " \"ταυτότητα\": 1," + NEW_LINE + " \"επιπλέον αγνοούνται σειρά\": [\"ένας\", \"δυο\"]," + NEW_LINE + " \"όνομα\": \"μια πράσινη πόρτα\"," + NEW_LINE + " \"τιμή\": 12.50," + NEW_LINE + " \"ετικέτες\": [\"σπίτι\", \"πράσινος\"]" + NEW_LINE + "}", StandardCharsets.UTF_16, MatchType.ONLY_MATCHING_FIELDS)), headersToIgnore) ); } @Test public void shouldReturnResponseByMatchingBodyWithJsonWithContentTypeHeader() { // when mockServerClient .when( request() .withBody(json("{" + NEW_LINE + " \"ταυτότητα\": 1," + NEW_LINE + " \"όνομα\": \"μια πράσινη πόρτα\"," + NEW_LINE + " \"τιμή\": 12.50," + NEW_LINE + " \"ετικέτες\": [\"σπίτι\", \"πράσινος\"]" + NEW_LINE + "}", StandardCharsets.UTF_16, MatchType.ONLY_MATCHING_FIELDS)), exactly(2) ) .respond( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withReasonPhrase(HttpStatusCode.ACCEPTED_202.reasonPhrase()) .withBody("some_body") ); // then // - in http assertEquals( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withReasonPhrase(HttpStatusCode.ACCEPTED_202.reasonPhrase()) .withBody("some_body"), makeRequest( request() .withHeader(CONTENT_TYPE.toString(), MediaType.create("text", "plain").withCharset(StandardCharsets.UTF_16).toString()) .withPath(calculatePath("some_path")) .withMethod("POST") .withBody(json("{" + NEW_LINE + " \"ταυτότητα\": 1," + NEW_LINE + " \"επιπλέον αγνοούνται τομέα\": \"κάποια αξία\"," + NEW_LINE + " \"όνομα\": \"μια πράσινη πόρτα\"," + NEW_LINE + " \"τιμή\": 12.50," + NEW_LINE + " \"ετικέτες\": [\"σπίτι\", \"πράσινος\"]" + NEW_LINE + "}")), headersToIgnore) ); // - in https assertEquals( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withReasonPhrase(HttpStatusCode.ACCEPTED_202.reasonPhrase()) .withBody("some_body"), makeRequest( request() .withSecure(true) .withHeader(CONTENT_TYPE.toString(), MediaType.create("text", "plain").withCharset(StandardCharsets.UTF_16).toString()) .withPath(calculatePath("some_path")) .withMethod("POST") .withBody(json("{" + NEW_LINE + " \"ταυτότητα\": 1," + NEW_LINE + " \"επιπλέον αγνοούνται σειρά\": [\"ένας\", \"δυο\"]," + NEW_LINE + " \"όνομα\": \"μια πράσινη πόρτα\"," + NEW_LINE + " \"τιμή\": 12.50," + NEW_LINE + " \"ετικέτες\": [\"σπίτι\", \"πράσινος\"]" + NEW_LINE + "}")), headersToIgnore) ); } @Test public void shouldReturnResponseByMatchingBodyWithJsonWithMatchType() { // when mockServerClient .when( request() .withBody(json("{" + NEW_LINE + " \"id\": 1," + NEW_LINE + " \"name\": \"A green door\"," + NEW_LINE + " \"price\": 12.50," + NEW_LINE + " \"tags\": [\"home\", \"green\"]" + NEW_LINE + "}", MatchType.ONLY_MATCHING_FIELDS)), exactly(2) ) .respond( response() .withBody("some_body") ); // then // - in http assertEquals( response("some_body"), makeRequest( request() .withPath(calculatePath("some_path")) .withMethod("POST") .withBody("{" + NEW_LINE + " \"id\": 1," + NEW_LINE + " \"extra field\": \"some value\"," + NEW_LINE + " \"name\": \"A green door\"," + NEW_LINE + " \"price\": 12.50," + NEW_LINE + " \"tags\": [\"home\", \"green\"]" + NEW_LINE + "}"), headersToIgnore) ); // - in https assertEquals( response("some_body"), makeRequest( request() .withSecure(true) .withPath(calculatePath("some_path")) .withMethod("POST") .withBody("{" + NEW_LINE + " \"id\": 1," + NEW_LINE + " \"extra field\": \"some value\"," + NEW_LINE + " \"name\": \"A green door\"," + NEW_LINE + " \"price\": 12.50," + NEW_LINE + " \"tags\": [\"home\", \"green\"]" + NEW_LINE + "}"), headersToIgnore) ); } @Test public void shouldReturnResponseByMatchingBodyWithJsonSchema() { // when mockServerClient.when(request().withBody(jsonSchema("{" + NEW_LINE + " \"$schema\": \"http://json-schema.org/draft-04/schema#\"," + NEW_LINE + " \"title\": \"Product\"," + NEW_LINE + " \"description\": \"A product from Acme's catalog\"," + NEW_LINE + " \"type\": \"object\"," + NEW_LINE + " \"properties\": {" + NEW_LINE + " \"id\": {" + NEW_LINE + " \"description\": \"The unique identifier for a product\"," + NEW_LINE + " \"type\": \"integer\"" + NEW_LINE + " }," + NEW_LINE + " \"name\": {" + NEW_LINE + " \"description\": \"Name of the product\"," + NEW_LINE + " \"type\": \"string\"" + NEW_LINE + " }," + NEW_LINE + " \"price\": {" + NEW_LINE + " \"type\": \"number\"," + NEW_LINE + " \"minimum\": 0," + NEW_LINE + " \"exclusiveMinimum\": true" + NEW_LINE + " }," + NEW_LINE + " \"tags\": {" + NEW_LINE + " \"type\": \"array\"," + NEW_LINE + " \"items\": {" + NEW_LINE + " \"type\": \"string\"" + NEW_LINE + " }," + NEW_LINE + " \"minItems\": 1," + NEW_LINE + " \"uniqueItems\": true" + NEW_LINE + " }" + NEW_LINE + " }," + NEW_LINE + " \"required\": [\"id\", \"name\", \"price\"]" + NEW_LINE + "}")), exactly(2)).respond(response().withBody("some_body")); // then // - in http assertEquals( response() .withStatusCode(OK_200.code()) .withReasonPhrase(OK_200.reasonPhrase()) .withBody("some_body"), makeRequest( request() .withPath(calculatePath("some_path")) .withMethod("POST") .withBody("{" + NEW_LINE + " \"id\": 1," + NEW_LINE + " \"name\": \"A green door\"," + NEW_LINE + " \"price\": 12.50," + NEW_LINE + " \"tags\": [\"home\", \"green\"]" + NEW_LINE + "}"), headersToIgnore) ); // - in https assertEquals( response() .withStatusCode(OK_200.code()) .withReasonPhrase(OK_200.reasonPhrase()) .withBody("some_body"), makeRequest( request() .withSecure(true) .withPath(calculatePath("some_path")) .withMethod("POST") .withBody("{" + NEW_LINE + " \"id\": 1," + NEW_LINE + " \"name\": \"A green door\"," + NEW_LINE + " \"price\": 12.50," + NEW_LINE + " \"tags\": [\"home\", \"green\"]" + NEW_LINE + "}"), headersToIgnore) ); } @Test public void shouldReturnResponseByMatchingBodyWithJsonPath() { // when mockServerClient.when(request().withBody(jsonPath("$..book[?(@.price <= $['expensive'])]")), exactly(2)).respond(response().withBody("some_body")); // then // - in http assertEquals( response() .withStatusCode(OK_200.code()) .withReasonPhrase(OK_200.reasonPhrase()) .withBody("some_body"), makeRequest( request() .withPath(calculatePath("some_path")) .withMethod("POST") .withBody(new StringBody("" + "{\n" + " \"store\": {\n" + " \"book\": [\n" + " {\n" + " \"category\": \"reference\",\n" + " \"author\": \"Nigel Rees\",\n" + " \"title\": \"Sayings of the Century\",\n" + " \"price\": 8.95\n" + " },\n" + " {\n" + " \"category\": \"fiction\",\n" + " \"author\": \"Herman Melville\",\n" + " \"title\": \"Moby Dick\",\n" + " \"isbn\": \"0-553-21311-3\",\n" + " \"price\": 8.99\n" + " }\n" + " ],\n" + " \"bicycle\": {\n" + " \"color\": \"red\",\n" + " \"price\": 19.95\n" + " }\n" + " },\n" + " \"expensive\": 10\n" + "}")), headersToIgnore) ); // - in https assertEquals( response() .withStatusCode(OK_200.code()) .withReasonPhrase(OK_200.reasonPhrase()) .withBody("some_body"), makeRequest( request() .withSecure(true) .withPath(calculatePath("some_path")) .withMethod("POST") .withBody(new StringBody("" + "{\n" + " \"store\": {\n" + " \"book\": [\n" + " {\n" + " \"category\": \"reference\",\n" + " \"author\": \"Nigel Rees\",\n" + " \"title\": \"Sayings of the Century\",\n" + " \"price\": 8.95\n" + " },\n" + " {\n" + " \"category\": \"fiction\",\n" + " \"author\": \"Herman Melville\",\n" + " \"title\": \"Moby Dick\",\n" + " \"isbn\": \"0-553-21311-3\",\n" + " \"price\": 8.99\n" + " }\n" + " ],\n" + " \"bicycle\": {\n" + " \"color\": \"red\",\n" + " \"price\": 19.95\n" + " }\n" + " },\n" + " \"expensive\": 10\n" + "}")), headersToIgnore) ); } @Test public void shouldReturnPDFResponseByMatchingPath() throws IOException { // when byte[] pdfBytes = IOUtils.toByteArray(getClass().getClassLoader().getResourceAsStream("test.pdf")); mockServerClient .when( request() .withPath(calculatePath("ws/rest/user/[0-9]+/document/[0-9]+\\.pdf")) ) .respond( response() .withStatusCode(OK_200.code()) .withReasonPhrase(OK_200.reasonPhrase()) .withHeaders( header(CONTENT_TYPE.toString(), MediaType.PDF.toString()), header(CONTENT_DISPOSITION.toString(), "form-data; name=\"test.pdf\"; filename=\"test.pdf\""), header(CACHE_CONTROL.toString(), "must-revalidate, post-check=0, pre-check=0") ) .withBody(binary(pdfBytes)) ); // then // - in http assertEquals( response() .withStatusCode(OK_200.code()) .withReasonPhrase(OK_200.reasonPhrase()) .withHeaders( header(CONTENT_DISPOSITION.toString(), "form-data; name=\"test.pdf\"; filename=\"test.pdf\""), header(CACHE_CONTROL.toString(), "must-revalidate, post-check=0, pre-check=0"), header(CONTENT_TYPE.toString(), MediaType.PDF.toString()) ) .withBody(binary(pdfBytes)), makeRequest( request() .withPath(calculatePath("ws/rest/user/1/document/2.pdf")) .withMethod("GET"), headersToIgnore) ); // - in https assertEquals( response() .withStatusCode(OK_200.code()) .withReasonPhrase(OK_200.reasonPhrase()) .withHeaders( header(CONTENT_DISPOSITION.toString(), "form-data; name=\"test.pdf\"; filename=\"test.pdf\""), header(CACHE_CONTROL.toString(), "must-revalidate, post-check=0, pre-check=0"), header(CONTENT_TYPE.toString(), MediaType.PDF.toString()) ) .withBody(binary(pdfBytes)), makeRequest( request() .withSecure(true) .withPath(calculatePath("ws/rest/user/1/document/2.pdf")) .withMethod("GET"), headersToIgnore) ); } @Test public void shouldReturnPNGResponseByMatchingPath() throws IOException { // when byte[] pngBytes = IOUtils.toByteArray(getClass().getClassLoader().getResourceAsStream("test.png")); mockServerClient .when( request() .withPath(calculatePath("ws/rest/user/[0-9]+/icon/[0-9]+\\.png")) ) .respond( response() .withStatusCode(OK_200.code()) .withReasonPhrase(OK_200.reasonPhrase()) .withHeaders( header(CONTENT_TYPE.toString(), MediaType.PNG.toString()), header(CONTENT_DISPOSITION.toString(), "form-data; name=\"test.png\"; filename=\"test.png\"") ) .withBody(binary(pngBytes)) ); // then // - in http assertEquals( response() .withStatusCode(OK_200.code()) .withReasonPhrase(OK_200.reasonPhrase()) .withHeaders( header(CONTENT_DISPOSITION.toString(), "form-data; name=\"test.png\"; filename=\"test.png\""), header(CONTENT_TYPE.toString(), MediaType.PNG.toString()) ) .withBody(binary(pngBytes)), makeRequest( request() .withPath(calculatePath("ws/rest/user/1/icon/1.png")) .withMethod("GET"), headersToIgnore) ); // - in https assertEquals( response() .withStatusCode(OK_200.code()) .withReasonPhrase(OK_200.reasonPhrase()) .withHeaders( header(CONTENT_DISPOSITION.toString(), "form-data; name=\"test.png\"; filename=\"test.png\""), header(CONTENT_TYPE.toString(), MediaType.PNG.toString()) ) .withBody(binary(pngBytes)), makeRequest( request() .withSecure(true) .withPath(calculatePath("ws/rest/user/1/icon/1.png")) .withMethod("GET"), headersToIgnore) ); } @Test public void shouldReturnPDFResponseByMatchingBinaryPDFBody() throws IOException { // when byte[] pdfBytes = IOUtils.toByteArray(getClass().getClassLoader().getResourceAsStream("test.pdf")); mockServerClient .when( request() .withBody(binary(pdfBytes, MediaType.PDF)) ) .respond( response() .withStatusCode(OK_200.code()) .withReasonPhrase(OK_200.reasonPhrase()) .withHeaders( header(CONTENT_TYPE.toString(), MediaType.PDF.toString()), header(CONTENT_DISPOSITION.toString(), "form-data; name=\"test.pdf\"; filename=\"test.pdf\""), header(CACHE_CONTROL.toString(), "must-revalidate, post-check=0, pre-check=0") ) .withBody(binary(pdfBytes)) ); // then // - in http assertEquals( response() .withStatusCode(OK_200.code()) .withReasonPhrase(OK_200.reasonPhrase()) .withHeaders( header(CONTENT_DISPOSITION.toString(), "form-data; name=\"test.pdf\"; filename=\"test.pdf\""), header(CACHE_CONTROL.toString(), "must-revalidate, post-check=0, pre-check=0"), header(CONTENT_TYPE.toString(), MediaType.PDF.toString()) ) .withBody(binary(pdfBytes)), makeRequest( request() .withPath(calculatePath("ws/rest/user/1/document/2.pdf")) .withBody(binary(pdfBytes, MediaType.PDF)) .withMethod("POST"), headersToIgnore) ); // - in https assertEquals( response() .withStatusCode(OK_200.code()) .withReasonPhrase(OK_200.reasonPhrase()) .withHeaders( header(CONTENT_DISPOSITION.toString(), "form-data; name=\"test.pdf\"; filename=\"test.pdf\""), header(CACHE_CONTROL.toString(), "must-revalidate, post-check=0, pre-check=0"), header(CONTENT_TYPE.toString(), MediaType.PDF.toString()) ) .withBody(binary(pdfBytes)), makeRequest( request() .withSecure(true) .withPath(calculatePath("ws/rest/user/1/document/2.pdf")) .withBody(binary(pdfBytes, MediaType.PDF)) .withMethod("POST"), headersToIgnore) ); } @Test public void shouldReturnPNGResponseByMatchingBinaryPNGBody() throws IOException { // when byte[] pngBytes = IOUtils.toByteArray(getClass().getClassLoader().getResourceAsStream("test.png")); mockServerClient .when( request() .withBody(binary(pngBytes, MediaType.ANY_IMAGE_TYPE)) ) .respond( response() .withStatusCode(OK_200.code()) .withReasonPhrase(OK_200.reasonPhrase()) .withHeaders( header(CONTENT_TYPE.toString(), MediaType.PNG.toString()), header(CONTENT_DISPOSITION.toString(), "form-data; name=\"test.png\"; filename=\"test.png\"") ) .withBody(binary(pngBytes)) ); // then // - in http assertEquals( response() .withStatusCode(OK_200.code()) .withReasonPhrase(OK_200.reasonPhrase()) .withHeaders( header(CONTENT_DISPOSITION.toString(), "form-data; name=\"test.png\"; filename=\"test.png\""), header(CONTENT_TYPE.toString(), MediaType.PNG.toString()) ) .withBody(binary(pngBytes)), makeRequest( request() .withPath(calculatePath("ws/rest/user/1/icon/1.png")) .withBody(binary(pngBytes, MediaType.ANY_IMAGE_TYPE)) .withMethod("POST"), headersToIgnore) ); // - in https assertEquals( response() .withStatusCode(OK_200.code()) .withReasonPhrase(OK_200.reasonPhrase()) .withHeaders( header(CONTENT_DISPOSITION.toString(), "form-data; name=\"test.png\"; filename=\"test.png\""), header(CONTENT_TYPE.toString(), MediaType.PNG.toString()) ) .withBody(binary(pngBytes)), makeRequest( request() .withSecure(true) .withPath(calculatePath("ws/rest/user/1/icon/1.png")) .withBody(binary(pngBytes, MediaType.ANY_IMAGE_TYPE)) .withMethod("POST"), headersToIgnore) ); } @Test public void shouldReturnResponseByNotMatchingPathWithNotOperator() { // when mockServerClient .when( request() .withPath(not(calculatePath("some_path"))) ) .respond( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withReasonPhrase(HttpStatusCode.ACCEPTED_202.reasonPhrase()) .withBody("some_body_response") ); // then // - in http assertEquals( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withReasonPhrase(HttpStatusCode.ACCEPTED_202.reasonPhrase()) .withBody("some_body_response"), makeRequest( request() .withPath(calculatePath("some_other_path")), headersToIgnore) ); // - in https assertEquals( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withReasonPhrase(HttpStatusCode.ACCEPTED_202.reasonPhrase()) .withBody("some_body_response"), makeRequest( request() .withPath(calculatePath("some_other_path")), headersToIgnore) ); } @Test public void shouldReturnResponseByNotMatchingMethodWithNotOperator() { // when mockServerClient .when( request() .withMethod(not("GET")) ) .respond( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withReasonPhrase(HttpStatusCode.ACCEPTED_202.reasonPhrase()) .withBody("some_body_response") ); // then // - in http assertEquals( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withReasonPhrase(HttpStatusCode.ACCEPTED_202.reasonPhrase()) .withBody("some_body_response"), makeRequest( request() .withMethod("POST"), headersToIgnore) ); // - in https assertEquals( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withReasonPhrase(HttpStatusCode.ACCEPTED_202.reasonPhrase()) .withBody("some_body_response"), makeRequest( request() .withMethod("POST"), headersToIgnore) ); } @Test public void shouldReturnResponseByMatchingPathAndMethodAndBody() { // when mockServerClient .when( request() .withMethod("POST") .withPath(calculatePath("some_pathRequest")) .withBody("some_bodyRequest") ) .respond( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withReasonPhrase(HttpStatusCode.ACCEPTED_202.reasonPhrase()) .withBody("some_body_response") .withHeaders(header("headerNameResponse", "headerValueResponse")) ); // then // - in http assertEquals( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withReasonPhrase(HttpStatusCode.ACCEPTED_202.reasonPhrase()) .withBody("some_body_response") .withHeaders( header("headerNameResponse", "headerValueResponse") ), makeRequest( request() .withMethod("POST") .withPath(calculatePath("some_pathRequest")) .withQueryStringParameters( param("queryStringParameterOneName", "queryStringParameterOneValue"), param("queryStringParameterTwoName", "queryStringParameterTwoValue") ) .withBody("some_bodyRequest") .withHeaders(header("headerNameRequest", "headerValueRequest")) .withCookies(cookie("cookieNameRequest", "cookieValueRequest")), headersToIgnore) ); // - in https assertEquals( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withReasonPhrase(HttpStatusCode.ACCEPTED_202.reasonPhrase()) .withBody("some_body_response") .withHeaders( header("headerNameResponse", "headerValueResponse") ), makeRequest( request() .withMethod("POST") .withSecure(true) .withPath(calculatePath("some_pathRequest")) .withQueryStringParameters( param("queryStringParameterOneName", "queryStringParameterOneValue"), param("queryStringParameterTwoName", "queryStringParameterTwoValue") ) .withBody("some_bodyRequest") .withHeaders(header("headerNameRequest", "headerValueRequest")) .withCookies(cookie("cookieNameRequest", "cookieValueRequest")), headersToIgnore) ); } @Test public void shouldReturnResponseByMatchingPathAndMethodAndQueryStringParameters() { // when mockServerClient .when( request() .withMethod("GET") .withPath(calculatePath("some_pathRequest")) .withQueryStringParameters( param("queryStringParameterOneName", "queryStringParameterOneValue"), param("queryStringParameterTwoName", "queryStringParameterTwoValue") ) ) .respond( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withReasonPhrase(HttpStatusCode.ACCEPTED_202.reasonPhrase()) .withBody("some_body_response") .withCookies(cookie("cookieNameResponse", "cookieValueResponse")) ); // then // - in http assertEquals( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withReasonPhrase(HttpStatusCode.ACCEPTED_202.reasonPhrase()) .withBody("some_body_response") .withCookies(cookie("cookieNameResponse", "cookieValueResponse")) .withHeaders( header(SET_COOKIE.toString(), "cookieNameResponse=cookieValueResponse") ), makeRequest( request() .withMethod("GET") .withPath(calculatePath("some_pathRequest")) .withQueryStringParameters( param("queryStringParameterOneName", "queryStringParameterOneValue"), param("queryStringParameterTwoName", "queryStringParameterTwoValue") ) .withHeaders(header("headerNameRequest", "headerValueRequest")) .withCookies(cookie("cookieNameRequest", "cookieValueRequest")), headersToIgnore) ); // - in https assertEquals( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withReasonPhrase(HttpStatusCode.ACCEPTED_202.reasonPhrase()) .withBody("some_body_response") .withCookies(cookie("cookieNameResponse", "cookieValueResponse")) .withHeaders( header(SET_COOKIE.toString(), "cookieNameResponse=cookieValueResponse") ), makeRequest( request() .withMethod("GET") .withSecure(true) .withPath(calculatePath("some_pathRequest")) .withQueryStringParameters( param("queryStringParameterOneName", "queryStringParameterOneValue"), param("queryStringParameterTwoName", "queryStringParameterTwoValue") ) .withHeaders(header("headerNameRequest", "headerValueRequest")) .withCookies(cookie("cookieNameRequest", "cookieValueRequest")), headersToIgnore) ); } @Test public void shouldReturnResponseByMatchingPathAndMethodAndHeaders() { // when mockServerClient .when( request() .withMethod("GET") .withPath(calculatePath("some_pathRequest")) .withHeaders( header("requestHeaderNameOne", "requestHeaderValueOne_One", "requestHeaderValueOne_Two"), header("requestHeaderNameTwo", "requestHeaderValueTwo") ) ) .respond( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withReasonPhrase(HttpStatusCode.ACCEPTED_202.reasonPhrase()) .withBody("some_body_response") .withCookies(cookie("cookieNameResponse", "cookieValueResponse")) ); // then // - in http assertEquals( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withReasonPhrase(HttpStatusCode.ACCEPTED_202.reasonPhrase()) .withBody("some_body_response") .withCookies(cookie("cookieNameResponse", "cookieValueResponse")) .withHeaders( header(SET_COOKIE.toString(), "cookieNameResponse=cookieValueResponse") ), makeRequest( request() .withMethod("GET") .withPath(calculatePath("some_pathRequest")) .withHeaders( header("requestHeaderNameOne", "requestHeaderValueOne_One", "requestHeaderValueOne_Two"), header("requestHeaderNameTwo", "requestHeaderValueTwo") ) .withCookies(cookie("cookieNameRequest", "cookieValueRequest")), headersToIgnore) ); // - in https assertEquals( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withReasonPhrase(HttpStatusCode.ACCEPTED_202.reasonPhrase()) .withBody("some_body_response") .withCookies(cookie("cookieNameResponse", "cookieValueResponse")) .withHeaders( header(SET_COOKIE.toString(), "cookieNameResponse=cookieValueResponse") ), makeRequest( request() .withMethod("GET") .withSecure(true) .withPath(calculatePath("some_pathRequest")) .withHeaders( header("requestHeaderNameOne", "requestHeaderValueOne_One", "requestHeaderValueOne_Two"), header("requestHeaderNameTwo", "requestHeaderValueTwo") ) .withCookies(cookie("cookieNameRequest", "cookieValueRequest")), headersToIgnore) ); } @Test public void shouldReturnResponseByMatchingPathAndMethodAndCookies() { // when mockServerClient .when( request() .withMethod("GET") .withPath(calculatePath("some_pathRequest")) .withCookies( cookie("requestCookieNameOne", "requestCookieValueOne"), cookie("requestCookieNameTwo", "requestCookieValueTwo") ) ) .respond( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withReasonPhrase(HttpStatusCode.ACCEPTED_202.reasonPhrase()) .withBody("some_body_response") .withCookies( cookie("responseCookieNameOne", "responseCookieValueOne"), cookie("responseCookieNameTwo", "responseCookieValueTwo") ) ); // then // - in http - cookie objects assertEquals( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withReasonPhrase(HttpStatusCode.ACCEPTED_202.reasonPhrase()) .withBody("some_body_response") .withCookies( cookie("responseCookieNameOne", "responseCookieValueOne"), cookie("responseCookieNameTwo", "responseCookieValueTwo") ) .withHeaders( header(SET_COOKIE.toString(), "responseCookieNameOne=responseCookieValueOne", "responseCookieNameTwo=responseCookieValueTwo") ), makeRequest( request() .withMethod("GET") .withPath(calculatePath("some_pathRequest")) .withHeaders( header("headerNameRequest", "headerValueRequest"), header(CONTENT_TYPE.toString(), MediaType.create("text", "plain").toString()) ) .withCookies( cookie("requestCookieNameOne", "requestCookieValueOne"), cookie("requestCookieNameTwo", "requestCookieValueTwo") ), headersToIgnore) ); // - in http - cookie header assertEquals( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withReasonPhrase(HttpStatusCode.ACCEPTED_202.reasonPhrase()) .withBody("some_body_response") .withCookies( cookie("responseCookieNameOne", "responseCookieValueOne"), cookie("responseCookieNameTwo", "responseCookieValueTwo") ) .withHeaders( header(SET_COOKIE.toString(), "responseCookieNameOne=responseCookieValueOne", "responseCookieNameTwo=responseCookieValueTwo") ), makeRequest( request() .withMethod("GET") .withPath(calculatePath("some_pathRequest")) .withHeaders( header("headerNameRequest", "headerValueRequest"), header("Cookie", "requestCookieNameOne=requestCookieValueOne; requestCookieNameTwo=requestCookieValueTwo") ), headersToIgnore) ); // - in https - cookie objects assertEquals( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withReasonPhrase(HttpStatusCode.ACCEPTED_202.reasonPhrase()) .withBody("some_body_response") .withCookies( cookie("responseCookieNameOne", "responseCookieValueOne"), cookie("responseCookieNameTwo", "responseCookieValueTwo") ) .withHeaders( header(SET_COOKIE.toString(), "responseCookieNameOne=responseCookieValueOne", "responseCookieNameTwo=responseCookieValueTwo") ), makeRequest( request() .withMethod("GET") .withSecure(true) .withPath(calculatePath("some_pathRequest")) .withHeaders( header("headerNameRequest", "headerValueRequest") ) .withCookies( cookie("requestCookieNameOne", "requestCookieValueOne"), cookie("requestCookieNameTwo", "requestCookieValueTwo") ), headersToIgnore) ); // - in https - cookie header assertEquals( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withReasonPhrase(HttpStatusCode.ACCEPTED_202.reasonPhrase()) .withBody("some_body_response") .withCookies( cookie("responseCookieNameOne", "responseCookieValueOne"), cookie("responseCookieNameTwo", "responseCookieValueTwo") ) .withHeaders( header(SET_COOKIE.toString(), "responseCookieNameOne=responseCookieValueOne", "responseCookieNameTwo=responseCookieValueTwo") ), makeRequest( request() .withMethod("GET") .withSecure(true) .withPath(calculatePath("some_pathRequest")) .withHeaders( header("headerNameRequest", "headerValueRequest"), header("Cookie", "requestCookieNameOne=requestCookieValueOne; requestCookieNameTwo=requestCookieValueTwo") ), headersToIgnore) ); } @Test public void shouldReturnResponseByMatchingPathAndMethodAndQueryStringParametersAndBodyParameters() { // when mockServerClient .when( request() .withMethod("POST") .withPath(calculatePath("some_pathRequest")) .withQueryStringParameters( param("queryStringParameterOneName", "queryStringParameterOneValueOne", "queryStringParameterOneValueTwo"), param("queryStringParameterTwoName", "queryStringParameterTwoValue") ) .withBody(params(param("bodyParameterName", "bodyParameterValue"))) ) .respond( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withReasonPhrase(HttpStatusCode.ACCEPTED_202.reasonPhrase()) .withBody("some_body") ); // then // - in http - url query string assertEquals( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withReasonPhrase(HttpStatusCode.ACCEPTED_202.reasonPhrase()) .withBody("some_body"), makeRequest( request() .withMethod("POST") .withPath(calculatePath("some_pathRequest")) .withQueryStringParameters( param("queryStringParameterOneName", "queryStringParameterOneValueOne", "queryStringParameterOneValueTwo"), param("queryStringParameterTwoName", "queryStringParameterTwoValue") ) .withBody(params(param("bodyParameterName", "bodyParameterValue"))), headersToIgnore) ); // - in https - query string parameter objects assertEquals( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withReasonPhrase(HttpStatusCode.ACCEPTED_202.reasonPhrase()) .withBody("some_body"), makeRequest( request() .withSecure(true) .withMethod("POST") .withPath(calculatePath("some_pathRequest")) .withQueryStringParameters( param("queryStringParameterOneName", "queryStringParameterOneValueOne", "queryStringParameterOneValueTwo"), param("queryStringParameterTwoName", "queryStringParameterTwoValue") ) .withBody(params(param("bodyParameterName", "bodyParameterValue"))), headersToIgnore) ); } @Test public void shouldReturnResponseByMatchingPathAndMethodAndQueryStringParametersAndBody() { // when mockServerClient .when( request() .withMethod("POST") .withPath(calculatePath("some_pathRequest")) .withQueryStringParameters( param("queryStringParameterOneName", "queryStringParameterOneValueOne", "queryStringParameterOneValueTwo"), param("queryStringParameterTwoName", "queryStringParameterTwoValue") ) .withBody("some_bodyRequest") ) .respond( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withReasonPhrase(HttpStatusCode.ACCEPTED_202.reasonPhrase()) .withBody("some_body_response") .withHeaders(header("headerNameResponse", "headerValueResponse")) .withCookies(cookie("cookieNameResponse", "cookieValueResponse")) ); // then // - in http - url query string assertEquals( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withReasonPhrase(HttpStatusCode.ACCEPTED_202.reasonPhrase()) .withBody("some_body_response") .withCookies(cookie("cookieNameResponse", "cookieValueResponse")) .withHeaders( header("headerNameResponse", "headerValueResponse"), header(SET_COOKIE.toString(), "cookieNameResponse=cookieValueResponse") ), makeRequest( request() .withMethod("POST") .withPath(calculatePath("some_pathRequest")) .withQueryStringParameters( param("queryStringParameterOneName", "queryStringParameterOneValueOne", "queryStringParameterOneValueTwo"), param("queryStringParameterTwoName", "queryStringParameterTwoValue") ) .withBody("some_bodyRequest") .withHeaders(header("headerNameRequest", "headerValueRequest")) .withCookies(cookie("cookieNameRequest", "cookieValueRequest")), headersToIgnore) ); // - in http - query string parameter objects assertEquals( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withReasonPhrase(HttpStatusCode.ACCEPTED_202.reasonPhrase()) .withBody("some_body_response") .withCookies(cookie("cookieNameResponse", "cookieValueResponse")) .withHeaders( header("headerNameResponse", "headerValueResponse"), header(SET_COOKIE.toString(), "cookieNameResponse=cookieValueResponse") ), makeRequest( request() .withMethod("POST") .withPath(calculatePath("some_pathRequest")) .withQueryStringParameters( param("queryStringParameterOneName", "queryStringParameterOneValueOne", "queryStringParameterOneValueTwo"), param("queryStringParameterTwoName", "queryStringParameterTwoValue") ) .withBody("some_bodyRequest") .withHeaders(header("headerNameRequest", "headerValueRequest")) .withCookies(cookie("cookieNameRequest", "cookieValueRequest")), headersToIgnore) ); // - in https - url string and query string parameter objects assertEquals( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withReasonPhrase(HttpStatusCode.ACCEPTED_202.reasonPhrase()) .withBody("some_body_response") .withCookies(cookie("cookieNameResponse", "cookieValueResponse")) .withHeaders( header("headerNameResponse", "headerValueResponse"), header(SET_COOKIE.toString(), "cookieNameResponse=cookieValueResponse") ), makeRequest( request() .withMethod("POST") .withPath(calculatePath("some_pathRequest")) .withQueryStringParameters( param("queryStringParameterOneName", "queryStringParameterOneValueOne", "queryStringParameterOneValueTwo"), param("queryStringParameterTwoName", "queryStringParameterTwoValue") ) .withBody("some_bodyRequest") .withHeaders(header("headerNameRequest", "headerValueRequest")) .withCookies(cookie("cookieNameRequest", "cookieValueRequest")), headersToIgnore) ); } @Test public void shouldReturnResponseByMatchingPathAndMethodAndBodyParameters() { // when mockServerClient .when( request() .withMethod("POST") .withPath(calculatePath("some_pathRequest")) .withBody(params( param("bodyParameterOneName", "Parameter One Value One", "Parameter One Value Two"), param("bodyParameterTwoName", "Parameter Two") )) ) .respond( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withReasonPhrase(HttpStatusCode.ACCEPTED_202.reasonPhrase()) .withBody("some_body_response") .withHeaders(header("headerNameResponse", "headerValueResponse")) .withCookies(cookie("cookieNameResponse", "cookieValueResponse")) ); // then // - in http - body string assertEquals( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withReasonPhrase(HttpStatusCode.ACCEPTED_202.reasonPhrase()) .withBody("some_body_response") .withCookies(cookie("cookieNameResponse", "cookieValueResponse")) .withHeaders( header("headerNameResponse", "headerValueResponse"), header(SET_COOKIE.toString(), "cookieNameResponse=cookieValueResponse") ), makeRequest( request() .withMethod("POST") .withPath(calculatePath("some_pathRequest")) .withBody(new StringBody("bodyParameterOneName=Parameter+One+Value+One" + "&bodyParameterOneName=Parameter+One+Value+Two" + "&bodyParameterTwoName=Parameter+Two")) .withHeaders(header("headerNameRequest", "headerValueRequest")) .withCookies(cookie("cookieNameRequest", "cookieValueRequest")), headersToIgnore) ); // - in http - body parameter objects assertEquals( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withReasonPhrase(HttpStatusCode.ACCEPTED_202.reasonPhrase()) .withBody("some_body_response") .withCookies(cookie("cookieNameResponse", "cookieValueResponse")) .withHeaders( header("headerNameResponse", "headerValueResponse"), header(SET_COOKIE.toString(), "cookieNameResponse=cookieValueResponse") ), makeRequest( request() .withMethod("POST") .withPath(calculatePath("some_pathRequest")) .withBody(params( param("bodyParameterOneName", "Parameter One Value One", "Parameter One Value Two"), param("bodyParameterTwoName", "Parameter Two") )) .withHeaders(header("headerNameRequest", "headerValueRequest")) .withCookies(cookie("cookieNameRequest", "cookieValueRequest")), headersToIgnore) ); // - in https - url string and query string parameter objects assertEquals( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withReasonPhrase(HttpStatusCode.ACCEPTED_202.reasonPhrase()) .withBody("some_body_response") .withCookies(cookie("cookieNameResponse", "cookieValueResponse")) .withHeaders( header("headerNameResponse", "headerValueResponse"), header(SET_COOKIE.toString(), "cookieNameResponse=cookieValueResponse") ), makeRequest( request() .withMethod("POST") .withPath(calculatePath("some_pathRequest")) .withBody(params( param("bodyParameterOneName", "Parameter One Value One", "Parameter One Value Two"), param("bodyParameterTwoName", "Parameter Two") )) .withHeaders(header("headerNameRequest", "headerValueRequest")) .withCookies(cookie("cookieNameRequest", "cookieValueRequest")), headersToIgnore) ); } @Test public void shouldReturnResponseByMatchingPathAndMethodAndParametersAndHeadersAndCookies() { // when mockServerClient .when( request() .withMethod("PUT") .withPath(calculatePath("some_pathRequest")) .withBody(new StringBody("bodyParameterOneName=Parameter+One+Value+One" + "&bodyParameterOneName=Parameter+One+Value+Two" + "&bodyParameterTwoName=Parameter+Two")) .withHeaders(header("headerNameRequest", "headerValueRequest")) .withCookies(cookie("cookieNameRequest", "cookieValueRequest")) ) .respond( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withReasonPhrase(HttpStatusCode.ACCEPTED_202.reasonPhrase()) .withBody("some_body_response") .withHeaders(header("headerNameResponse", "headerValueResponse")) .withCookies(cookie("cookieNameResponse", "cookieValueResponse")) ); // then // - in http - body string assertEquals( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withReasonPhrase(HttpStatusCode.ACCEPTED_202.reasonPhrase()) .withBody("some_body_response") .withCookies(cookie("cookieNameResponse", "cookieValueResponse")) .withHeaders( header("headerNameResponse", "headerValueResponse"), header(SET_COOKIE.toString(), "cookieNameResponse=cookieValueResponse") ), makeRequest( request() .withMethod("PUT") .withPath(calculatePath("some_pathRequest")) .withBody(new StringBody("bodyParameterOneName=Parameter+One+Value+One" + "&bodyParameterOneName=Parameter+One+Value+Two" + "&bodyParameterTwoName=Parameter+Two")) .withHeaders( header("headerNameRequest", "headerValueRequest"), header("Cookie", "cookieNameRequest=cookieValueRequest") ), headersToIgnore) ); // - in http - body parameter objects assertEquals( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withReasonPhrase(HttpStatusCode.ACCEPTED_202.reasonPhrase()) .withBody("some_body_response") .withCookies(cookie("cookieNameResponse", "cookieValueResponse")) .withHeaders( header("headerNameResponse", "headerValueResponse"), header(SET_COOKIE.toString(), "cookieNameResponse=cookieValueResponse") ), makeRequest( request() .withMethod("PUT") .withPath(calculatePath("some_pathRequest")) .withBody(params( param("bodyParameterOneName", "Parameter One Value One", "Parameter One Value Two"), param("bodyParameterTwoName", "Parameter Two") )) .withHeaders(header("headerNameRequest", "headerValueRequest")) .withCookies(cookie("cookieNameRequest", "cookieValueRequest")), headersToIgnore) ); } @Test public void shouldReturnResponseByNotMatchingBodyParameterWithNotOperatorForNameAndValue() { // when mockServerClient .when( request() .withMethod("POST") .withPath(calculatePath("some_pathRequest")) .withBody(params( param(not("bodyParameterOneName"), not("Parameter One Value One"), not("Parameter One Value Two")), param("bodyParameterTwoName", "Parameter Two") )) ) .respond( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withReasonPhrase(HttpStatusCode.ACCEPTED_202.reasonPhrase()) .withBody("some_body_response") ); // then // wrong query string parameter name assertEquals( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withReasonPhrase(HttpStatusCode.ACCEPTED_202.reasonPhrase()) .withBody("some_body_response"), makeRequest( request() .withMethod("POST") .withPath(calculatePath("some_pathRequest")) .withBody(params( param("OTHERBodyParameterOneName", "Parameter One Value One", "Parameter One Value Two"), param("bodyParameterTwoName", "Parameter Two") )) .withHeaders(header("headerNameRequest", "headerValueRequest")) .withCookies(cookie("cookieNameRequest", "cookieValueRequest")), headersToIgnore) ); // wrong query string parameter name assertEquals( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withReasonPhrase(HttpStatusCode.ACCEPTED_202.reasonPhrase()) .withBody("some_body_response"), makeRequest( request() .withMethod("POST") .withPath(calculatePath("some_pathRequest")) .withBody(new StringBody("OTHERBodyParameterOneName=Parameter+One+Value+One" + "&OTHERBodyParameterOneName=Parameter+One+Value+Two" + "&bodyParameterTwoName=Parameter+Two")) .withHeaders(header("headerNameRequest", "headerValueRequest")) .withCookies(cookie("cookieNameRequest", "cookieValueRequest")), headersToIgnore) ); // wrong query string parameter value assertEquals( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withReasonPhrase(HttpStatusCode.ACCEPTED_202.reasonPhrase()) .withBody("some_body_response"), makeRequest( request() .withMethod("POST") .withPath(calculatePath("some_pathRequest")) .withBody(params( param("bodyParameterOneName", "OTHER Parameter One Value One", "OTHER Parameter One Value Two"), param("bodyParameterTwoName", "Parameter Two") )) .withHeaders(header("headerNameRequest", "headerValueRequest")) .withCookies(cookie("cookieNameRequest", "cookieValueRequest")), headersToIgnore) ); // wrong query string parameter value assertEquals( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withReasonPhrase(HttpStatusCode.ACCEPTED_202.reasonPhrase()) .withBody("some_body_response"), makeRequest( request() .withMethod("POST") .withPath(calculatePath("some_pathRequest")) .withBody(new StringBody("bodyParameterOneName=OTHER Parameter+One+Value+One" + "&bodyParameterOneName=OTHER Parameter+One+Value+Two" + "&bodyParameterTwoName=Parameter+Two")) .withHeaders(header("headerNameRequest", "headerValueRequest")) .withCookies(cookie("cookieNameRequest", "cookieValueRequest")), headersToIgnore) ); } @Test public void shouldReturnResponseByNotMatchingBodyParameterWithNotOperatorForName() { // when mockServerClient .when( request() .withMethod("POST") .withPath(calculatePath("some_pathRequest")) .withBody(params( param(not("bodyParameterOneName"), string("Parameter One Value One"), string("Parameter One Value Two")), param("bodyParameterTwoName", "Parameter Two") )) ) .respond( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withReasonPhrase(HttpStatusCode.ACCEPTED_202.reasonPhrase()) .withBody("some_body_response") ); // then // wrong query string parameter name assertEquals( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withReasonPhrase(HttpStatusCode.ACCEPTED_202.reasonPhrase()) .withBody("some_body_response"), makeRequest( request() .withMethod("POST") .withPath(calculatePath("some_pathRequest")) .withBody(params( param("OTHERBodyParameterOneName", "Parameter One Value One", "Parameter One Value Two"), param("bodyParameterTwoName", "Parameter Two") )) .withHeaders(header("headerNameRequest", "headerValueRequest")) .withCookies(cookie("cookieNameRequest", "cookieValueRequest")), headersToIgnore) ); // wrong query string parameter name assertEquals( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withReasonPhrase(HttpStatusCode.ACCEPTED_202.reasonPhrase()) .withBody("some_body_response"), makeRequest( request() .withMethod("POST") .withPath(calculatePath("some_pathRequest")) .withBody(new StringBody("OTHERBodyParameterOneName=Parameter+One+Value+One" + "&OTHERBodyParameterOneName=Parameter+One+Value+Two" + "&bodyParameterTwoName=Parameter+Two")) .withHeaders(header("headerNameRequest", "headerValueRequest")) .withCookies(cookie("cookieNameRequest", "cookieValueRequest")), headersToIgnore) ); } @Test public void shouldReturnResponseByNotMatchingBodyParameterWithNotOperatorForValue() { // when mockServerClient .when( request() .withMethod("POST") .withPath(calculatePath("some_pathRequest")) .withBody(params( param(string("bodyParameterOneName"), not("Parameter One Value One"), not("Parameter One Value Two")), param("bodyParameterTwoName", "Parameter Two") )) ) .respond( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withReasonPhrase(HttpStatusCode.ACCEPTED_202.reasonPhrase()) .withBody("some_body_response") ); // then // wrong query string parameter value assertEquals( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withReasonPhrase(HttpStatusCode.ACCEPTED_202.reasonPhrase()) .withBody("some_body_response"), makeRequest( request() .withMethod("POST") .withPath(calculatePath("some_pathRequest")) .withBody(params( param("bodyParameterOneName", "OTHER Parameter One Value One", "OTHER Parameter One Value Two"), param("bodyParameterTwoName", "Parameter Two") )) .withHeaders(header("headerNameRequest", "headerValueRequest")) .withCookies(cookie("cookieNameRequest", "cookieValueRequest")), headersToIgnore) ); // wrong query string parameter value assertEquals( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withReasonPhrase(HttpStatusCode.ACCEPTED_202.reasonPhrase()) .withBody("some_body_response"), makeRequest( request() .withMethod("POST") .withPath(calculatePath("some_pathRequest")) .withBody(new StringBody("bodyParameterOneName=OTHER Parameter+One+Value+One" + "&bodyParameterOneName=OTHER Parameter+One+Value+Two" + "&bodyParameterTwoName=Parameter+Two")) .withHeaders(header("headerNameRequest", "headerValueRequest")) .withCookies(cookie("cookieNameRequest", "cookieValueRequest")), headersToIgnore) ); } @Test public void shouldReturnResponseByNotMatchingQueryStringParameterWithNotOperatorForNameAndValue() { // when mockServerClient .when( request() .withMethod("POST") .withPath(calculatePath("some_pathRequest")) .withQueryStringParameters( param(not("queryStringParameterOneName"), not("Parameter One Value One"), not("Parameter One Value Two")), param("queryStringParameterTwoName", "Parameter Two") ) ) .respond( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withReasonPhrase(HttpStatusCode.ACCEPTED_202.reasonPhrase()) .withBody("some_body_response") ); // then // wrong query string parameter name assertEquals( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withReasonPhrase(HttpStatusCode.ACCEPTED_202.reasonPhrase()) .withBody("some_body_response"), makeRequest( request() .withMethod("POST") .withPath(calculatePath("some_pathRequest")) .withQueryStringParameters( param("OTHERQueryStringParameterOneName", "Parameter One Value One", "Parameter One Value Two"), param("queryStringParameterTwoName", "Parameter Two") ), headersToIgnore) ); // wrong query string parameter value assertEquals( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withReasonPhrase(HttpStatusCode.ACCEPTED_202.reasonPhrase()) .withBody("some_body_response"), makeRequest( request() .withMethod("POST") .withPath(calculatePath("some_pathRequest")) .withQueryStringParameters( param("queryStringParameterOneName", "OTHER Parameter One Value One", "OTHER Parameter One Value Two"), param("queryStringParameterTwoName", "Parameter Two") ), headersToIgnore) ); } @Test public void shouldReturnResponseByNotMatchingQueryStringParameterWithNotOperatorForName() { // when mockServerClient .when( request() .withMethod("POST") .withPath(calculatePath("some_pathRequest")) .withQueryStringParameters( param(not("queryStringParameterOneName"), string("Parameter One Value One"), string("Parameter One Value Two")), param("queryStringParameterTwoName", "Parameter Two") ) ) .respond( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withReasonPhrase(HttpStatusCode.ACCEPTED_202.reasonPhrase()) .withBody("some_body_response") ); // then // wrong query string parameter name assertEquals( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withReasonPhrase(HttpStatusCode.ACCEPTED_202.reasonPhrase()) .withBody("some_body_response"), makeRequest( request() .withMethod("POST") .withPath(calculatePath("some_pathRequest")) .withQueryStringParameters( param("OTHERQueryStringParameterOneName", "Parameter One Value One", "Parameter One Value Two"), param("queryStringParameterTwoName", "Parameter Two") ), headersToIgnore) ); } @Test public void shouldReturnResponseByNotMatchingQueryStringParameterWithNotOperatorForValue() { // when mockServerClient .when( request() .withMethod("POST") .withPath(calculatePath("some_pathRequest")) .withQueryStringParameters( param(string("queryStringParameterOneName"), not("Parameter One Value One"), not("Parameter One Value Two")), param("queryStringParameterTwoName", "Parameter Two") ) ) .respond( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withReasonPhrase(HttpStatusCode.ACCEPTED_202.reasonPhrase()) .withBody("some_body_response") ); // then // wrong query string parameter value assertEquals( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withReasonPhrase(HttpStatusCode.ACCEPTED_202.reasonPhrase()) .withBody("some_body_response"), makeRequest( request() .withMethod("POST") .withPath(calculatePath("some_pathRequest")) .withQueryStringParameters( param("queryStringParameterOneName", "OTHER Parameter One Value One", "OTHER Parameter One Value Two"), param("queryStringParameterTwoName", "Parameter Two") ), headersToIgnore) ); } @Test public void shouldReturnResponseByNotMatchingCookieWithNotOperatorForNameAndValue() { // when mockServerClient .when( request() .withMethod("GET") .withPath(calculatePath("some_pathRequest")) .withCookies( cookie(not("requestCookieNameOne"), not("requestCookieValueOne")), cookie("requestCookieNameTwo", "requestCookieValueTwo") ) ) .respond( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withReasonPhrase(HttpStatusCode.ACCEPTED_202.reasonPhrase()) .withBody("some_body_response") ); // then // wrong query string cookie name assertEquals( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withReasonPhrase(HttpStatusCode.ACCEPTED_202.reasonPhrase()) .withBody("some_body_response"), makeRequest( request() .withMethod("GET") .withPath(calculatePath("some_pathRequest")) .withCookies( cookie("OTHERrequestCookieNameOne", "requestCookieValueOne"), cookie("requestCookieNameTwo", "requestCookieValueTwo") ), headersToIgnore) ); // wrong query string cookie value assertEquals( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withReasonPhrase(HttpStatusCode.ACCEPTED_202.reasonPhrase()) .withBody("some_body_response"), makeRequest( request() .withMethod("GET") .withPath(calculatePath("some_pathRequest")) .withCookies( cookie("requestCookieNameOne", "OTHERrequestCookieValueOne"), cookie("requestCookieNameTwo", "requestCookieValueTwo") ), headersToIgnore) ); } @Test public void shouldReturnResponseByNotMatchingCookieWithNotOperatorForName() { // when mockServerClient .when( request() .withMethod("GET") .withPath(calculatePath("some_pathRequest")) .withCookies( cookie(not("requestCookieNameOne"), string("requestCookieValueOne")), cookie("requestCookieNameTwo", "requestCookieValueTwo") ) ) .respond( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withReasonPhrase(HttpStatusCode.ACCEPTED_202.reasonPhrase()) .withBody("some_body_response") ); // then // wrong query string cookie name assertEquals( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withReasonPhrase(HttpStatusCode.ACCEPTED_202.reasonPhrase()) .withBody("some_body_response"), makeRequest( request() .withMethod("GET") .withPath(calculatePath("some_pathRequest")) .withCookies( cookie("OTHERrequestCookieNameOne", "requestCookieValueOne"), cookie("requestCookieNameTwo", "requestCookieValueTwo") ), headersToIgnore) ); } @Test public void shouldReturnResponseByNotMatchingCookieWithNotOperatorForValue() { // when mockServerClient .when( request() .withMethod("GET") .withPath(calculatePath("some_pathRequest")) .withCookies( cookie(string("requestCookieNameOne"), not("requestCookieValueOne")), cookie("requestCookieNameTwo", "requestCookieValueTwo") ) ) .respond( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withReasonPhrase(HttpStatusCode.ACCEPTED_202.reasonPhrase()) .withBody("some_body_response") ); // then // wrong query string cookie value assertEquals( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withReasonPhrase(HttpStatusCode.ACCEPTED_202.reasonPhrase()) .withBody("some_body_response"), makeRequest( request() .withMethod("GET") .withPath(calculatePath("some_pathRequest")) .withCookies( cookie("requestCookieNameOne", "OTHERrequestCookieValueOne"), cookie("requestCookieNameTwo", "requestCookieValueTwo") ), headersToIgnore) ); } @Test public void shouldReturnResponseByNotMatchingHeaderWithNotOperatorForNameAndValue() { // when mockServerClient .when( request() .withMethod("GET") .withPath(calculatePath("some_pathRequest")) .withHeaders( header(not("requestHeaderNameOne"), not("requestHeaderValueOne")), header("requestHeaderNameTwo", "requestHeaderValueTwo") ) ) .respond( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withReasonPhrase(HttpStatusCode.ACCEPTED_202.reasonPhrase()) .withBody("some_body_response") ); // then // wrong query string header name assertEquals( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withReasonPhrase(HttpStatusCode.ACCEPTED_202.reasonPhrase()) .withBody("some_body_response"), makeRequest( request() .withMethod("GET") .withPath(calculatePath("some_pathRequest")) .withHeaders( header("OTHERrequestHeaderNameOne", "requestHeaderValueOne"), header("requestHeaderNameTwo", "requestHeaderValueTwo") ), headersToIgnore) ); // wrong query string header value assertEquals( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withReasonPhrase(HttpStatusCode.ACCEPTED_202.reasonPhrase()) .withBody("some_body_response"), makeRequest( request() .withMethod("GET") .withPath(calculatePath("some_pathRequest")) .withHeaders( header("requestHeaderNameOne", "OTHERrequestHeaderValueOne"), header("requestHeaderNameTwo", "requestHeaderValueTwo") ), headersToIgnore) ); } @Test public void shouldReturnResponseByNotMatchingHeaderWithNotOperatorForName() { // when mockServerClient .when( request() .withMethod("GET") .withPath(calculatePath("some_pathRequest")) .withHeaders( header(not("requestHeaderNameOne"), string("requestHeaderValueOne")), header("requestHeaderNameTwo", "requestHeaderValueTwo") ) ) .respond( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withReasonPhrase(HttpStatusCode.ACCEPTED_202.reasonPhrase()) .withBody("some_body_response") ); // then // wrong query string header name assertEquals( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withReasonPhrase(HttpStatusCode.ACCEPTED_202.reasonPhrase()) .withBody("some_body_response"), makeRequest( request() .withMethod("GET") .withPath(calculatePath("some_pathRequest")) .withHeaders( header("OTHERrequestHeaderNameOne", "requestHeaderValueOne"), header("requestHeaderNameTwo", "requestHeaderValueTwo") ), headersToIgnore) ); } @Test public void shouldReturnResponseByNotMatchingHeaderWithNotOperatorForValue() { // when mockServerClient .when( request() .withMethod("GET") .withPath(calculatePath("some_pathRequest")) .withHeaders( header(string("requestHeaderNameOne"), not("requestHeaderValueOne")), header("requestHeaderNameTwo", "requestHeaderValueTwo") ) ) .respond( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withReasonPhrase(HttpStatusCode.ACCEPTED_202.reasonPhrase()) .withBody("some_body_response") ); // then // wrong query string header value assertEquals( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withReasonPhrase(HttpStatusCode.ACCEPTED_202.reasonPhrase()) .withBody("some_body_response"), makeRequest( request() .withMethod("GET") .withPath(calculatePath("some_pathRequest")) .withHeaders( header("requestHeaderNameOne", "OTHERrequestHeaderValueOne"), header("requestHeaderNameTwo", "requestHeaderValueTwo") ), headersToIgnore) ); } @Test public void shouldNotReturnResponseForWhenTimeToLiveExpired() { // when mockServerClient .when( request().withPath(calculatePath("some_path")), exactly(2), TimeToLive.exactly(TimeUnit.SECONDS, 3L) ) .respond( response().withBody("some_body").withDelay(TimeUnit.SECONDS, 3L) ); // then assertEquals( response() .withStatusCode(OK_200.code()) .withReasonPhrase(OK_200.reasonPhrase()) .withBody("some_body"), makeRequest( request() .withPath(calculatePath("some_path")), headersToIgnore) ); // - in http assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()) .withReasonPhrase(HttpStatusCode.NOT_FOUND_404.reasonPhrase()), makeRequest( request() .withPath(calculatePath("some_path")), headersToIgnore) ); // - in https assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()) .withReasonPhrase(HttpStatusCode.NOT_FOUND_404.reasonPhrase()), makeRequest( request() .withSecure(true) .withPath(calculatePath("some_path")), headersToIgnore) ); } @Test public void shouldNotReturnResponseForMatchingBodyWithNotOperator() { // when mockServerClient .when( request() .withBody(Not.not(json("{" + NEW_LINE + " \"id\": 1," + NEW_LINE + " \"name\": \"A green door\"," + NEW_LINE + " \"price\": 12.50," + NEW_LINE + " \"tags\": [\"home\", \"green\"]" + NEW_LINE + "}"))), exactly(2) ) .respond( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withReasonPhrase(HttpStatusCode.ACCEPTED_202.reasonPhrase()) .withBody("some_body") ); // then // - in http assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()) .withReasonPhrase(HttpStatusCode.NOT_FOUND_404.reasonPhrase()), makeRequest( request() .withPath(calculatePath("some_path")) .withMethod("POST") .withBody("{" + NEW_LINE + " \"id\": 1," + NEW_LINE + " \"extra_ignored_field\": \"some value\"," + NEW_LINE + " \"name\": \"A green door\"," + NEW_LINE + " \"price\": 12.50," + NEW_LINE + " \"tags\": [\"home\", \"green\"]" + NEW_LINE + "}"), headersToIgnore) ); // - in https assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()) .withReasonPhrase(HttpStatusCode.NOT_FOUND_404.reasonPhrase()), makeRequest( request() .withSecure(true) .withPath(calculatePath("some_path")) .withMethod("POST") .withBody("{" + NEW_LINE + " \"id\": 1," + NEW_LINE + " \"extra_ignored_array\": [\"one\", \"two\"]," + NEW_LINE + " \"name\": \"A green door\"," + NEW_LINE + " \"price\": 12.50," + NEW_LINE + " \"tags\": [\"home\", \"green\"]" + NEW_LINE + "}"), headersToIgnore) ); } @Test public void shouldNotReturnResponseForNonMatchingXPathBody() { // when mockServerClient.when(request().withBody(new XPathBody("/bookstore/book[price>35]/price")), exactly(2)).respond(response().withBody("some_body")); // then // - in http assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()) .withReasonPhrase(HttpStatusCode.NOT_FOUND_404.reasonPhrase()), makeRequest( request() .withSecure(true) .withPath(calculatePath("some_path")) .withMethod("POST") .withBody(new StringBody("" + "<?xml version=\"1.0\" encoding=\"ISO-8859-1\"?>" + NEW_LINE + "<bookstore>" + NEW_LINE + " <book category=\"COOKING\">" + NEW_LINE + " <title lang=\"en\">Everyday Italian</title>" + NEW_LINE + " <author>Giada De Laurentiis</author>" + NEW_LINE + " <year>2005</year>" + NEW_LINE + " <price>30.00</price>" + NEW_LINE + " </book>" + NEW_LINE + " <book category=\"CHILDREN\">" + NEW_LINE + " <title lang=\"en\">Harry Potter</title>" + NEW_LINE + " <author>J K. Rowling</author>" + NEW_LINE + " <year>2005</year>" + NEW_LINE + " <price>29.99</price>" + NEW_LINE + " </book>" + NEW_LINE + " <book category=\"WEB\">" + NEW_LINE + " <title lang=\"en\">Learning XML</title>" + NEW_LINE + " <author>Erik T. Ray</author>" + NEW_LINE + " <year>2003</year>" + NEW_LINE + " <price>31.95</price>" + NEW_LINE + " </book>" + NEW_LINE + "</bookstore>")), headersToIgnore) ); // - in https assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()) .withReasonPhrase(HttpStatusCode.NOT_FOUND_404.reasonPhrase()), makeRequest( request() .withSecure(true) .withPath(calculatePath("some_path")) .withMethod("POST") .withBody(new StringBody("" + "<?xml version=\"1.0\" encoding=\"ISO-8859-1\"?>" + NEW_LINE + "<bookstore>" + NEW_LINE + " <book category=\"COOKING\">" + NEW_LINE + " <title lang=\"en\">Everyday Italian</title>" + NEW_LINE + " <author>Giada De Laurentiis</author>" + NEW_LINE + " <year>2005</year>" + NEW_LINE + " <price>30.00</price>" + NEW_LINE + " </book>" + NEW_LINE + " <book category=\"CHILDREN\">" + NEW_LINE + " <title lang=\"en\">Harry Potter</title>" + NEW_LINE + " <author>J K. Rowling</author>" + NEW_LINE + " <year>2005</year>" + NEW_LINE + " <price>29.99</price>" + NEW_LINE + " </book>" + NEW_LINE + " <book category=\"WEB\">" + NEW_LINE + " <title lang=\"en\">Learning XML</title>" + NEW_LINE + " <author>Erik T. Ray</author>" + NEW_LINE + " <year>2003</year>" + NEW_LINE + " <price>31.95</price>" + NEW_LINE + " </book>" + NEW_LINE + "</bookstore>")), headersToIgnore) ); } @Test public void shouldNotReturnResponseForNonMatchingXmlBody() { // when mockServerClient.when(request().withBody(xml("" + "<?xml version=\"1.0\" encoding=\"ISO-8859-1\"?>" + NEW_LINE + "<bookstore>" + NEW_LINE + " <book category=\"COOKING\" nationality=\"ITALIAN\">" + NEW_LINE + " <title lang=\"en\">Everyday Italian</title>" + NEW_LINE + " <author>Giada De Laurentiis</author>" + NEW_LINE + " <year>2005</year>" + NEW_LINE + " <price>30.00</price>" + NEW_LINE + " </book>" + NEW_LINE + "</bookstore>")), exactly(2)).respond(response().withBody("some_body")); // then // - in http assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()) .withReasonPhrase(HttpStatusCode.NOT_FOUND_404.reasonPhrase()), makeRequest( request() .withSecure(true) .withPath(calculatePath("some_path")) .withMethod("POST") .withBody(new StringBody("" + "<?xml version=\"1.0\" encoding=\"ISO-8859-1\"?>" + NEW_LINE + "<bookstore>" + NEW_LINE + " <book category=\"COOKING\">" + NEW_LINE + " <title lang=\"en\">Everyday Italian</title>" + NEW_LINE + " <author>Giada De Laurentiis</author>" + NEW_LINE + " <year>2005</year>" + NEW_LINE + " <price>30.00</price>" + NEW_LINE + " </book>" + NEW_LINE + "</bookstore>")), headersToIgnore) ); // - in https assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()) .withReasonPhrase(HttpStatusCode.NOT_FOUND_404.reasonPhrase()), makeRequest( request() .withSecure(true) .withPath(calculatePath("some_path")) .withMethod("POST") .withBody(new StringBody("" + "<?xml version=\"1.0\" encoding=\"ISO-8859-1\"?>" + NEW_LINE + "<bookstore>" + NEW_LINE + " <book category=\"COOKING\">" + NEW_LINE + " <title lang=\"en\">Everyday Italian</title>" + NEW_LINE + " <author>Giada De Laurentiis</author>" + NEW_LINE + " <year>2005</year>" + NEW_LINE + " <price>30.00</price>" + NEW_LINE + " </book>" + NEW_LINE + "</bookstore>")), headersToIgnore) ); } @Test public void shouldNotReturnResponseForNonMatchingJsonBody() { // when mockServerClient.when(request().withBody(json("{" + NEW_LINE + " \"id\": 1," + NEW_LINE + " \"name\": \"A green door\"," + NEW_LINE + " \"price\": 12.50," + NEW_LINE + " \"tags\": [\"home\", \"green\"]" + NEW_LINE + "}")), exactly(2)).respond(response().withBody("some_body")); // then // - in http assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()) .withReasonPhrase(HttpStatusCode.NOT_FOUND_404.reasonPhrase()), makeRequest( request() .withPath(calculatePath("some_path")) .withMethod("POST") .withBody("{" + NEW_LINE + " \"id\": 1," + NEW_LINE + " \"name\": \"---- XXXX WRONG VALUE XXXX ----\"," + NEW_LINE + " \"price\": 12.50," + NEW_LINE + " \"tags\": [\"home\", \"green\"]" + NEW_LINE + "}"), headersToIgnore) ); // - in https assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()) .withReasonPhrase(HttpStatusCode.NOT_FOUND_404.reasonPhrase()), makeRequest( request() .withSecure(true) .withPath(calculatePath("some_path")) .withMethod("POST") .withBody("{" + NEW_LINE + " \"id\": 1," + NEW_LINE + " \"name\": \"---- XXXX WRONG VALUE XXXX ----\"," + NEW_LINE + " \"price\": 12.50," + NEW_LINE + " \"tags\": [\"home\", \"green\"]" + NEW_LINE + "}"), headersToIgnore) ); } @Test public void shouldNotReturnResponseForNonMatchingJsonBodyWithMatchType() { // when mockServerClient .when( request() .withBody(json("{" + NEW_LINE + " \"id\": 1," + NEW_LINE + " \"name\": \"A green door\"," + NEW_LINE + " \"price\": 12.50," + NEW_LINE + " \"tags\": [\"home\", \"green\"]" + NEW_LINE + "}", MatchType.STRICT)), exactly(2)) .respond( response() .withBody("some_body") ); // then // - in http assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()) .withReasonPhrase(HttpStatusCode.NOT_FOUND_404.reasonPhrase()), makeRequest( request() .withPath(calculatePath("some_path")) .withMethod("POST") .withBody("{" + NEW_LINE + " \"id\": 1," + NEW_LINE + " \"extra field\": \"some value\"," + NEW_LINE + " \"name\": \"A green door\"," + NEW_LINE + " \"price\": 12.50," + NEW_LINE + " \"tags\": [\"home\", \"green\"]" + NEW_LINE + "}"), headersToIgnore) ); // - in https assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()) .withReasonPhrase(HttpStatusCode.NOT_FOUND_404.reasonPhrase()), makeRequest( request() .withSecure(true) .withPath(calculatePath("some_path")) .withMethod("POST") .withBody("{" + NEW_LINE + " \"id\": 1," + NEW_LINE + " \"extra field\": \"some value\"," + NEW_LINE + " \"name\": \"A green door\"," + NEW_LINE + " \"price\": 12.50," + NEW_LINE + " \"tags\": [\"home\", \"green\"]" + NEW_LINE + "}"), headersToIgnore) ); } @Test public void shouldNotReturnResponseForNonMatchingJsonSchema() { // when mockServerClient.when(request().withBody(jsonSchema("{" + NEW_LINE + " \"$schema\": \"http://json-schema.org/draft-04/schema#\"," + NEW_LINE + " \"title\": \"Product\"," + NEW_LINE + " \"description\": \"A product from Acme's catalog\"," + NEW_LINE + " \"type\": \"object\"," + NEW_LINE + " \"properties\": {" + NEW_LINE + " \"id\": {" + NEW_LINE + " \"description\": \"The unique identifier for a product\"," + NEW_LINE + " \"type\": \"integer\"" + NEW_LINE + " }," + NEW_LINE + " \"name\": {" + NEW_LINE + " \"description\": \"Name of the product\"," + NEW_LINE + " \"type\": \"string\"" + NEW_LINE + " }," + NEW_LINE + " \"price\": {" + NEW_LINE + " \"type\": \"number\"," + NEW_LINE + " \"minimum\": 0," + NEW_LINE + " \"exclusiveMinimum\": true" + NEW_LINE + " }," + NEW_LINE + " \"tags\": {" + NEW_LINE + " \"type\": \"array\"," + NEW_LINE + " \"items\": {" + NEW_LINE + " \"type\": \"string\"" + NEW_LINE + " }," + NEW_LINE + " \"minItems\": 1," + NEW_LINE + " \"uniqueItems\": true" + NEW_LINE + " }" + NEW_LINE + " }," + NEW_LINE + " \"required\": [\"id\", \"name\", \"price\"]" + NEW_LINE + "}")), exactly(2)).respond(response().withBody("some_body")); // then // - in http assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()) .withReasonPhrase(HttpStatusCode.NOT_FOUND_404.reasonPhrase()), makeRequest( request() .withPath(calculatePath("some_path")) .withMethod("POST") .withBody("{" + NEW_LINE + " \"id\": 1," + NEW_LINE + " \"wrong field name\": \"A green door\"," + NEW_LINE + " \"price\": 12.50," + NEW_LINE + " \"tags\": [\"home\", \"green\"]" + NEW_LINE + "}"), headersToIgnore) ); // - in https assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()) .withReasonPhrase(HttpStatusCode.NOT_FOUND_404.reasonPhrase()), makeRequest( request() .withSecure(true) .withPath(calculatePath("some_path")) .withMethod("POST") .withBody("{" + NEW_LINE + " \"id\": 1," + NEW_LINE + " \"name\": \"A green door\"," + NEW_LINE + " \"wrong field name\": 12.50," + NEW_LINE + " \"tags\": [\"home\", \"green\"]" + NEW_LINE + "}"), headersToIgnore) ); } @Test public void shouldNotReturnResponseForNonMatchingJsonPathBody() { // when mockServerClient.when(request().withBody(new JsonPathBody("$..book[?(@.price > $['expensive'])]")), exactly(2)).respond(response().withBody("some_body")); // then // - in http assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()) .withReasonPhrase(HttpStatusCode.NOT_FOUND_404.reasonPhrase()), makeRequest( request() .withSecure(true) .withPath(calculatePath("some_path")) .withMethod("POST") .withBody(new StringBody("" + "{\n" + " \"store\": {\n" + " \"book\": [\n" + " {\n" + " \"category\": \"reference\",\n" + " \"author\": \"Nigel Rees\",\n" + " \"title\": \"Sayings of the Century\",\n" + " \"price\": 8.95\n" + " },\n" + " {\n" + " \"category\": \"fiction\",\n" + " \"author\": \"Herman Melville\",\n" + " \"title\": \"Moby Dick\",\n" + " \"isbn\": \"0-553-21311-3\",\n" + " \"price\": 8.99\n" + " }\n" + " ],\n" + " \"bicycle\": {\n" + " \"color\": \"red\",\n" + " \"price\": 19.95\n" + " }\n" + " },\n" + " \"expensive\": 10\n" + "}")), headersToIgnore) ); // - in https assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()) .withReasonPhrase(HttpStatusCode.NOT_FOUND_404.reasonPhrase()), makeRequest( request() .withSecure(true) .withPath(calculatePath("some_path")) .withMethod("POST") .withBody(new StringBody("" + "{\n" + " \"store\": {\n" + " \"book\": [\n" + " {\n" + " \"category\": \"reference\",\n" + " \"author\": \"Nigel Rees\",\n" + " \"title\": \"Sayings of the Century\",\n" + " \"price\": 8.95\n" + " },\n" + " {\n" + " \"category\": \"fiction\",\n" + " \"author\": \"Herman Melville\",\n" + " \"title\": \"Moby Dick\",\n" + " \"isbn\": \"0-553-21311-3\",\n" + " \"price\": 8.99\n" + " }\n" + " ],\n" + " \"bicycle\": {\n" + " \"color\": \"red\",\n" + " \"price\": 19.95\n" + " }\n" + " },\n" + " \"expensive\": 10\n" + "}")), headersToIgnore) ); } @Test public void shouldNotReturnResponseForMatchingPathWithNotOperator() { // when mockServerClient .when( request() .withPath(not(calculatePath("some_path"))) ) .respond( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withReasonPhrase(HttpStatusCode.ACCEPTED_202.reasonPhrase()) .withBody("some_body_response") ); // then // - in http assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()) .withReasonPhrase(HttpStatusCode.NOT_FOUND_404.reasonPhrase()), makeRequest( request() .withPath(calculatePath("some_path")), headersToIgnore) ); // - in https assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()) .withReasonPhrase(HttpStatusCode.NOT_FOUND_404.reasonPhrase()), makeRequest( request() .withPath(calculatePath("some_path")), headersToIgnore) ); } @Test public void shouldNotReturnResponseForMatchingMethodWithNotOperator() { // when mockServerClient .when( request() .withMethod(not("GET")) ) .respond( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withReasonPhrase(HttpStatusCode.ACCEPTED_202.reasonPhrase()) .withBody("some_body_response") ); // then // - in http assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()) .withReasonPhrase(HttpStatusCode.NOT_FOUND_404.reasonPhrase()), makeRequest( request() .withMethod("GET"), headersToIgnore) ); // - in https assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()) .withReasonPhrase(HttpStatusCode.NOT_FOUND_404.reasonPhrase()), makeRequest( request() .withMethod("GET"), headersToIgnore) ); } @Test public void shouldNotReturnResponseForNonMatchingBodyParameterName() { // when mockServerClient .when( request() .withMethod("POST") .withPath(calculatePath("some_pathRequest")) .withBody(params( param("bodyParameterOneName", "Parameter One Value One", "Parameter One Value Two"), param("bodyParameterTwoName", "Parameter Two") )) ) .respond( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withReasonPhrase(HttpStatusCode.ACCEPTED_202.reasonPhrase()) .withBody("some_body_response") .withHeaders(header("headerNameResponse", "headerValueResponse")) .withCookies(cookie("cookieNameResponse", "cookieValueResponse")) ); // then // wrong query string parameter name assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()) .withReasonPhrase(HttpStatusCode.NOT_FOUND_404.reasonPhrase()), makeRequest( request() .withMethod("POST") .withPath(calculatePath("some_pathRequest")) .withBody(params( param("OTHERBodyParameterOneName", "Parameter One Value One", "Parameter One Value Two"), param("bodyParameterTwoName", "Parameter Two") )) .withHeaders(header("headerNameRequest", "headerValueRequest")) .withCookies(cookie("cookieNameRequest", "cookieValueRequest")), headersToIgnore) ); // wrong query string parameter name assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()) .withReasonPhrase(HttpStatusCode.NOT_FOUND_404.reasonPhrase()), makeRequest( request() .withMethod("POST") .withPath(calculatePath("some_pathRequest")) .withBody(new StringBody("OTHERBodyParameterOneName=Parameter+One+Value+One" + "&bodyParameterOneName=Parameter+One+Value+Two" + "&bodyParameterTwoName=Parameter+Two")) .withHeaders(header("headerNameRequest", "headerValueRequest")) .withCookies(cookie("cookieNameRequest", "cookieValueRequest")), headersToIgnore) ); } @Test public void shouldNotReturnResponseForMatchingBodyParameterWithNotOperator() { // when mockServerClient .when( request() .withMethod("POST") .withPath(calculatePath("some_pathRequest")) .withBody(params( param(not("bodyParameterOneName"), not("Parameter One Value One"), not("Parameter One Value Two")), param("bodyParameterTwoName", "Parameter Two") )) ) .respond( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withReasonPhrase(HttpStatusCode.ACCEPTED_202.reasonPhrase()) .withBody("some_body_response") ); // then // wrong query string parameter name assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()) .withReasonPhrase(HttpStatusCode.NOT_FOUND_404.reasonPhrase()), makeRequest( request() .withMethod("POST") .withPath(calculatePath("some_pathRequest")) .withBody(params( param("bodyParameterOneName", "Parameter One Value One", "Parameter One Value Two"), param("bodyParameterTwoName", "Parameter Two") )) .withHeaders(header("headerNameRequest", "headerValueRequest")) .withCookies(cookie("cookieNameRequest", "cookieValueRequest")), headersToIgnore) ); // wrong query string parameter name assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()) .withReasonPhrase(HttpStatusCode.NOT_FOUND_404.reasonPhrase()), makeRequest( request() .withMethod("POST") .withPath(calculatePath("some_pathRequest")) .withBody(new StringBody("bodyParameterOneName=Other Parameter+One+Value+One" + "&bodyParameterOneName=Parameter+One+Value+Two" + "&bodyParameterTwoName=Parameter+Two")) .withHeaders(header("headerNameRequest", "headerValueRequest")) .withCookies(cookie("cookieNameRequest", "cookieValueRequest")), headersToIgnore) ); } @Test public void shouldNotReturnResponseForNonMatchingBodyParameterValue() { // when mockServerClient .when( request() .withMethod("POST") .withPath(calculatePath("some_pathRequest")) .withBody(params( param("bodyParameterOneName", "Parameter One Value One", "Parameter One Value Two"), param("bodyParameterTwoName", "Parameter Two") )) ) .respond( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withReasonPhrase(HttpStatusCode.ACCEPTED_202.reasonPhrase()) .withBody("some_body_response") .withHeaders(header("headerNameResponse", "headerValueResponse")) .withCookies(cookie("cookieNameResponse", "cookieValueResponse")) ); // then // wrong body parameter value assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()) .withReasonPhrase(HttpStatusCode.NOT_FOUND_404.reasonPhrase()), makeRequest( request() .withMethod("POST") .withPath(calculatePath("some_pathRequest")) .withBody(params( param("bodyParameterOneName", "Other Parameter One Value One", "Parameter One Value Two"), param("bodyParameterTwoName", "Parameter Two") )) .withHeaders(header("headerNameRequest", "headerValueRequest")) .withCookies(cookie("cookieNameRequest", "cookieValueRequest")), headersToIgnore) ); // wrong body parameter value assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()) .withReasonPhrase(HttpStatusCode.NOT_FOUND_404.reasonPhrase()), makeRequest( request() .withMethod("POST") .withPath(calculatePath("some_pathRequest")) .withBody(new StringBody("bodyParameterOneName=Other Parameter+One+Value+One" + "&bodyParameterOneName=Parameter+One+Value+Two" + "&bodyParameterTwoName=Parameter+Two")) .withHeaders(header("headerNameRequest", "headerValueRequest")) .withCookies(cookie("cookieNameRequest", "cookieValueRequest")), headersToIgnore) ); } @Test public void shouldNotReturnResponseForNonMatchingQueryStringParameterName() { // when mockServerClient .when( request() .withMethod("POST") .withPath(calculatePath("some_pathRequest")) .withQueryStringParameters( param("queryStringParameterOneName", "queryStringParameterOneValueOne", "queryStringParameterOneValueTwo"), param("queryStringParameterTwoName", "queryStringParameterTwoValue") ) .withBody("some_bodyRequest") ) .respond( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withReasonPhrase(HttpStatusCode.ACCEPTED_202.reasonPhrase()) .withBody("some_body_response") .withHeaders(header("headerNameResponse", "headerValueResponse")) .withCookies(cookie("cookieNameResponse", "cookieValueResponse")) ); // then // wrong query string parameter name assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()) .withReasonPhrase(HttpStatusCode.NOT_FOUND_404.reasonPhrase()), makeRequest( request() .withMethod("POST") .withPath(calculatePath("some_pathRequest")) .withQueryStringParameters( param("OTHERQueryStringParameterOneName", "queryStringParameterOneValueOne", "queryStringParameterOneValueTwo"), param("queryStringParameterTwoName", "queryStringParameterTwoValue") ) .withBody("some_bodyRequest") .withHeaders( header("headerNameRequest", "headerValueRequest") ) .withCookies(cookie("cookieNameRequest", "cookieValueRequest")), headersToIgnore) ); } @Test public void shouldNotReturnResponseForNonMatchingQueryStringParameterValue() { // when mockServerClient .when( request() .withMethod("POST") .withPath(calculatePath("some_pathRequest")) .withQueryStringParameters( param("queryStringParameterOneName", "queryStringParameterOneValueOne", "queryStringParameterOneValueTwo"), param("queryStringParameterTwoName", "queryStringParameterTwoValue") ) .withBody("some_bodyRequest") ) .respond( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withReasonPhrase(HttpStatusCode.ACCEPTED_202.reasonPhrase()) .withBody("some_body_response") .withHeaders(header("headerNameResponse", "headerValueResponse")) .withCookies(cookie("cookieNameResponse", "cookieValueResponse")) ); // then // wrong query string parameter value assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()) .withReasonPhrase(HttpStatusCode.NOT_FOUND_404.reasonPhrase()), makeRequest( request() .withMethod("POST") .withPath(calculatePath("some_pathRequest")) .withQueryStringParameters( param("queryStringParameterOneName", "OTHERqueryStringParameterOneValueOne", "queryStringParameterOneValueTwo"), param("queryStringParameterTwoName", "queryStringParameterTwoValue") ) .withBody("some_bodyRequest") .withHeaders(header("headerNameRequest", "headerValueRequest")) .withCookies(cookie("cookieNameRequest", "cookieValueRequest")), headersToIgnore) ); } @Test public void shouldNotReturnResponseForMatchingQueryStringParameterWithNotOperator() { // when mockServerClient .when( request() .withMethod("POST") .withPath(calculatePath("some_pathRequest")) .withQueryStringParameters( param(not("queryStringParameterOneName"), not("Parameter One Value One"), not("Parameter One Value Two")), param("queryStringParameterTwoName", "Parameter Two") ) ) .respond( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withReasonPhrase(HttpStatusCode.ACCEPTED_202.reasonPhrase()) .withBody("some_body_response") ); // then // wrong query string parameter name assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()) .withReasonPhrase(HttpStatusCode.NOT_FOUND_404.reasonPhrase()), makeRequest( request() .withMethod("POST") .withPath(calculatePath("some_pathRequest")) .withQueryStringParameters( param("queryStringParameterOneName", "Parameter One Value One", "Parameter One Value Two"), param("queryStringParameterTwoName", "Parameter Two") ), headersToIgnore) ); // wrong query string parameter name assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()) .withReasonPhrase(HttpStatusCode.NOT_FOUND_404.reasonPhrase()), makeRequest( request() .withMethod("POST") .withPath(calculatePath("some_pathRequest")) .withQueryStringParameters( param("queryStringParameterOneName", "Parameter One Value One", "Parameter One Value Two"), param("queryStringParameterTwoName", "Parameter Two") ), headersToIgnore) ); } @Test public void shouldNotReturnResponseForNonMatchingCookieName() { // when mockServerClient .when( request() .withMethod("GET") .withPath(calculatePath("some_path")) .withQueryStringParameters( param("queryStringParameterOneName", "queryStringParameterOneValue"), param("queryStringParameterTwoName", "queryStringParameterTwoValue") ) .withBody(exact("some_body")) .withHeaders(header("headerName", "headerValue")) .withCookies(cookie("cookieName", "cookieValue")) ) .respond( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withReasonPhrase(HttpStatusCode.ACCEPTED_202.reasonPhrase()) .withBody("some_body") .withHeaders(header("headerName", "headerValue")) .withCookies(cookie("cookieName", "cookieValue")) ); // then // - in http assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()) .withReasonPhrase(HttpStatusCode.NOT_FOUND_404.reasonPhrase()), makeRequest( request() .withMethod("GET") .withPath(calculatePath("some_path")) .withQueryStringParameters( param("queryStringParameterOneName", "queryStringParameterOneValue"), param("queryStringParameterTwoName", "queryStringParameterTwoValue") ) .withBody(exact("some_body")) .withHeaders(header("headerName", "headerValue")) .withCookies(cookie("cookieOtherName", "cookieValue")), headersToIgnore) ); // - in https assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()) .withReasonPhrase(HttpStatusCode.NOT_FOUND_404.reasonPhrase()), makeRequest( request() .withMethod("GET") .withSecure(true) .withPath(calculatePath("some_path")) .withQueryStringParameters( param("queryStringParameterOneName", "queryStringParameterOneValue"), param("queryStringParameterTwoName", "queryStringParameterTwoValue") ) .withBody(exact("some_body")) .withHeaders(header("headerName", "headerValue")) .withCookies(cookie("cookieOtherName", "cookieValue")), headersToIgnore) ); } @Test public void shouldNotReturnResponseForNonMatchingCookieValue() { // when mockServerClient .when( request() .withMethod("GET") .withPath(calculatePath("some_path")) .withQueryStringParameters( param("queryStringParameterOneName", "queryStringParameterOneValue"), param("queryStringParameterTwoName", "queryStringParameterTwoValue") ) .withBody(exact("some_body")) .withHeaders(header("headerName", "headerValue")) .withCookies(cookie("cookieName", "cookieValue")) ) .respond( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withReasonPhrase(HttpStatusCode.ACCEPTED_202.reasonPhrase()) .withBody("some_body") .withHeaders(header("headerName", "headerValue")) .withCookies(cookie("cookieName", "cookieValue")) ); // then // - in http assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()) .withReasonPhrase(HttpStatusCode.NOT_FOUND_404.reasonPhrase()), makeRequest( request() .withMethod("GET") .withPath(calculatePath("some_path")) .withQueryStringParameters( param("queryStringParameterOneName", "queryStringParameterOneValue"), param("queryStringParameterTwoName", "queryStringParameterTwoValue") ) .withBody(exact("some_body")) .withHeaders(header("headerName", "headerValue")) .withCookies(cookie("cookieName", "cookieOtherValue")), headersToIgnore) ); // - in https assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()) .withReasonPhrase(HttpStatusCode.NOT_FOUND_404.reasonPhrase()), makeRequest( request() .withMethod("GET") .withSecure(true) .withPath(calculatePath("some_path")) .withQueryStringParameters( param("queryStringParameterOneName", "queryStringParameterOneValue"), param("queryStringParameterTwoName", "queryStringParameterTwoValue") ) .withBody(exact("some_body")) .withHeaders(header("headerName", "headerValue")) .withCookies(cookie("cookieName", "cookieOtherValue")), headersToIgnore) ); } @Test public void shouldNotReturnResponseForMatchingCookieWithNotOperator() { // when mockServerClient .when( request() .withMethod("GET") .withPath(calculatePath("some_pathRequest")) .withCookies( cookie(not("requestCookieNameOne"), not("requestCookieValueOne")), cookie("requestCookieNameTwo", "requestCookieValueTwo") ) ) .respond( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withReasonPhrase(HttpStatusCode.ACCEPTED_202.reasonPhrase()) .withBody("some_body_response") ); // then // wrong query string parameter name assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()) .withReasonPhrase(HttpStatusCode.NOT_FOUND_404.reasonPhrase()), makeRequest( request() .withMethod("GET") .withPath(calculatePath("some_pathRequest")) .withCookies( cookie("requestCookieNameOne", "requestCookieValueOne"), cookie("requestCookieNameTwo", "requestCookieValueTwo") ), headersToIgnore) ); // wrong query string parameter name assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()) .withReasonPhrase(HttpStatusCode.NOT_FOUND_404.reasonPhrase()), makeRequest( request() .withMethod("GET") .withPath(calculatePath("some_pathRequest")) .withCookies( cookie("requestCookieNameOne", "requestCookieValueOne"), cookie("requestCookieNameTwo", "requestCookieValueTwo") ), headersToIgnore) ); } @Test public void shouldNotReturnResponseForNonMatchingHeaderName() { // when mockServerClient .when( request() .withMethod("GET") .withPath(calculatePath("some_path")) .withQueryStringParameters( param("queryStringParameterOneName", "queryStringParameterOneValue"), param("queryStringParameterTwoName", "queryStringParameterTwoValue") ) .withBody(exact("some_body")) .withHeaders(header("headerName", "headerValue")) .withCookies(cookie("cookieName", "cookieValue")) ) .respond( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withReasonPhrase(HttpStatusCode.ACCEPTED_202.reasonPhrase()) .withBody("some_body") .withHeaders(header("headerName", "headerValue")) .withCookies(cookie("cookieName", "cookieValue")) ); // then // - in http assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()) .withReasonPhrase(HttpStatusCode.NOT_FOUND_404.reasonPhrase()), makeRequest( request() .withMethod("GET") .withPath(calculatePath("some_path")) .withQueryStringParameters( param("queryStringParameterOneName", "queryStringParameterOneValue"), param("queryStringParameterTwoName", "queryStringParameterTwoValue") ) .withBody(exact("some_body")) .withHeaders(header("headerOtherName", "headerValue")) .withCookies(cookie("cookieName", "cookieValue")), headersToIgnore) ); // - in https assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()) .withReasonPhrase(HttpStatusCode.NOT_FOUND_404.reasonPhrase()), makeRequest( request() .withMethod("GET") .withSecure(true) .withPath(calculatePath("some_path")) .withQueryStringParameters( param("queryStringParameterOneName", "queryStringParameterOneValue"), param("queryStringParameterTwoName", "queryStringParameterTwoValue") ) .withBody(exact("some_body")) .withHeaders(header("headerOtherName", "headerValue")) .withCookies(cookie("cookieName", "cookieValue")), headersToIgnore) ); } @Test public void shouldNotReturnResponseForNonMatchingHeaderValue() { // when mockServerClient .when( request() .withMethod("GET") .withPath(calculatePath("some_path")) .withQueryStringParameters( param("queryStringParameterOneName", "queryStringParameterOneValue"), param("queryStringParameterTwoName", "queryStringParameterTwoValue") ) .withBody(exact("some_body")) .withHeaders(header("headerName", "headerValue")) .withCookies(cookie("cookieName", "cookieValue")) ) .respond( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withReasonPhrase(HttpStatusCode.ACCEPTED_202.reasonPhrase()) .withBody("some_body") .withHeaders(header("headerName", "headerValue")) .withCookies(cookie("cookieName", "cookieValue")) ); // then // - in http assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()) .withReasonPhrase(HttpStatusCode.NOT_FOUND_404.reasonPhrase()), makeRequest( request() .withMethod("GET") .withPath(calculatePath("some_path")) .withQueryStringParameters( param("queryStringParameterOneName", "queryStringParameterOneValue"), param("queryStringParameterTwoName", "queryStringParameterTwoValue") ) .withBody(exact("some_body")) .withHeaders(header("headerName", "headerOtherValue")) .withCookies(cookie("cookieName", "cookieValue")), headersToIgnore) ); // - in https assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()) .withReasonPhrase(HttpStatusCode.NOT_FOUND_404.reasonPhrase()), makeRequest( request() .withMethod("GET") .withSecure(true) .withPath(calculatePath("some_path")) .withQueryStringParameters( param("queryStringParameterOneName", "queryStringParameterOneValue"), param("queryStringParameterTwoName", "queryStringParameterTwoValue") ) .withBody(exact("some_body")) .withHeaders(header("headerName", "headerOtherValue")) .withCookies(cookie("cookieName", "cookieValue")), headersToIgnore) ); } @Test public void shouldNotReturnResponseForMatchingHeaderWithNotOperator() { // when mockServerClient .when( request() .withMethod("GET") .withPath(calculatePath("some_pathRequest")) .withHeaders( header(not("requestHeaderNameOne"), not("requestHeaderValueOne")), header("requestHeaderNameTwo", "requestHeaderValueTwo") ) ) .respond( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withReasonPhrase(HttpStatusCode.ACCEPTED_202.reasonPhrase()) .withBody("some_body_response") ); // then // wrong query string parameter name assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()) .withReasonPhrase(HttpStatusCode.NOT_FOUND_404.reasonPhrase()), makeRequest( request() .withMethod("GET") .withPath(calculatePath("some_pathRequest")) .withHeaders( header("requestHeaderNameOne", "requestHeaderValueOne"), header("requestHeaderNameTwo", "requestHeaderValueTwo") ), headersToIgnore) ); // wrong query string parameter name assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()) .withReasonPhrase(HttpStatusCode.NOT_FOUND_404.reasonPhrase()), makeRequest( request() .withMethod("GET") .withPath(calculatePath("some_pathRequest")) .withHeaders( header("requestHeaderNameOne", "requestHeaderValueOne"), header("requestHeaderNameTwo", "requestHeaderValueTwo") ), headersToIgnore) ); } @Test public void shouldVerifyReceivedRequestInSsl() { // when mockServerClient .when( request() .withPath(calculatePath("some.*path")), exactly(2) ) .respond( response() .withBody("some_body") ); // then // - in http assertEquals( response() .withStatusCode(OK_200.code()) .withReasonPhrase(OK_200.reasonPhrase()) .withBody("some_body"), makeRequest( request() .withPath(calculatePath("some_path")), headersToIgnore) ); mockServerClient.verify(request() .withPath(calculatePath("some_path")) .withSecure(false)); mockServerClient.verify(request() .withPath(calculatePath("some_path")) .withSecure(false), VerificationTimes.exactly(1)); // - in https assertEquals( response() .withStatusCode(OK_200.code()) .withReasonPhrase(OK_200.reasonPhrase()) .withBody("some_body"), makeRequest( request() .withPath(calculatePath("some_secure_path")) .withSecure(true), headersToIgnore) ); mockServerClient.verify(request() .withPath(calculatePath("some_secure_path")) .withSecure(true)); mockServerClient.verify(request() .withPath(calculatePath("some_secure_path")) .withSecure(true), VerificationTimes.exactly(1)); } @Test public void shouldVerifyReceivedRequestsWithRegexBody() { // when mockServerClient .when( request() .withMethod("POST") .withPath(calculatePath("some_path")) .withBody("{type: 'some_random_type', value: 'some_random_value'}"), exactly(2) ) .respond( response() .withBody("some_response") ); // then // - in http assertEquals( response() .withStatusCode(OK_200.code()) .withReasonPhrase(OK_200.reasonPhrase()) .withBody("some_response"), makeRequest( request() .withMethod("POST") .withPath(calculatePath("some_path")) .withBody("{type: 'some_random_type', value: 'some_random_value'}"), headersToIgnore) ); mockServerClient.verify( request() .withBody(regex("\\{type\\: \\'some_random_type\\'\\, value\\: \\'some_random_value\\'\\}")) ); mockServerClient.verify( request() .withBody(regex("\\{type\\: \\'some_random_type\\'\\, value\\: \\'some_random_value\\'\\}")), VerificationTimes.exactly(1) ); // - in https assertEquals( response() .withStatusCode(OK_200.code()) .withReasonPhrase(OK_200.reasonPhrase()) .withBody("some_response"), makeRequest( request() .withSecure(true) .withMethod("POST") .withPath(calculatePath("some_path")) .withBody("{type: 'some_random_type', value: 'some_random_value'}"), headersToIgnore) ); mockServerClient.verify( request() .withSecure(true) .withBody(regex("\\{type\\: \\'some_random_type\\'\\, value\\: \\'some_random_value\\'\\}")) ); mockServerClient.verify( request() .withSecure(true) .withBody(regex("\\{type\\: \\'some_random_type\\'\\, value\\: \\'some_random_value\\'\\}")), VerificationTimes.atLeast(1) ); } @Test public void shouldVerifyReceivedRequestsWithNoBody() { // when mockServerClient.when(request().withPath(calculatePath("some_path")), exactly(2)).respond(response()); // then // - in http assertEquals( response() .withStatusCode(OK_200.code()) .withReasonPhrase(OK_200.reasonPhrase()), makeRequest( request() .withPath(calculatePath("some_path")), headersToIgnore) ); mockServerClient.verify(request() .withPath(calculatePath("some_path"))); mockServerClient.verify(request() .withPath(calculatePath("some_path")), VerificationTimes.exactly(1)); } @Test public void shouldVerifyTooManyRequestsReceived() { // when mockServerClient.when(request().withPath(calculatePath("some_path")), exactly(2)).respond(response().withBody("some_body")); // then assertEquals( response() .withStatusCode(OK_200.code()) .withReasonPhrase(OK_200.reasonPhrase()) .withBody("some_body"), makeRequest( request() .withPath(calculatePath("some_path")), headersToIgnore) ); try { mockServerClient.verify(request() .withPath(calculatePath("some_path")), VerificationTimes.exactly(0)); fail(); } catch (AssertionError ae) { assertThat(ae.getMessage(), startsWith("Request not found exactly 0 times, expected:<{" + NEW_LINE + " \"path\" : \"" + calculatePath("some_path") + "\"" + NEW_LINE + "}> but was:<{" + NEW_LINE + " \"method\" : \"GET\"," + NEW_LINE + " \"path\" : \"" + calculatePath("some_path") + "\"," + NEW_LINE)); } } @Test public void shouldVerifyNoMatchingRequestsReceived() { // when mockServerClient.when(request().withPath(calculatePath("some_path")), exactly(2)).respond(response().withBody("some_body")); // then assertEquals( response() .withStatusCode(OK_200.code()) .withReasonPhrase(OK_200.reasonPhrase()) .withBody("some_body"), makeRequest( request() .withPath(calculatePath("some_path")), headersToIgnore) ); try { mockServerClient.verify(request() .withPath(calculatePath("some_other_path")), VerificationTimes.exactly(2)); fail(); } catch (AssertionError ae) { assertThat(ae.getMessage(), startsWith("Request not found exactly 2 times, expected:<{" + NEW_LINE + " \"path\" : \"" + calculatePath("some_other_path") + "\"" + NEW_LINE + "}> but was:<{" + NEW_LINE + " \"method\" : \"GET\"," + NEW_LINE + " \"path\" : \"" + calculatePath("some_path") + "\"," + NEW_LINE)); } } @Test public void shouldNotVerifyNoRequestsReceived() { // when mockServerClient.when(request().withPath(calculatePath("some_path")), exactly(2)).respond(response().withBody("some_body")); // then assertEquals( response() .withStatusCode(OK_200.code()) .withReasonPhrase(OK_200.reasonPhrase()) .withBody("some_body"), makeRequest( request() .withPath(calculatePath("some_path")), headersToIgnore) ); try { mockServerClient.verifyZeroInteractions(); fail(); } catch (AssertionError ae) { assertThat(ae.getMessage(), startsWith("Request not found exactly 0 times, expected:<{ }> but was:<{" + NEW_LINE + " \"method\" : \"GET\"," + NEW_LINE + " \"path\" : \"" + calculatePath("some_path") + "\"," + NEW_LINE)); } } @Test public void shouldVerifyNoMatchingRequestsReceivedInSsl() { // when mockServerClient.when(request().withPath(calculatePath("some.*path")), exactly(2)).respond(response().withBody("some_body")); // then // - in http assertEquals( response() .withStatusCode(OK_200.code()) .withReasonPhrase(OK_200.reasonPhrase()) .withBody("some_body"), makeRequest( request() .withPath(calculatePath("some_path")), headersToIgnore) ); try { mockServerClient.verify( request() .withPath(calculatePath("some_path")) .withSecure(true), VerificationTimes.atLeast(1) ); fail(); } catch (AssertionError ae) { assertThat(ae.getMessage(), startsWith("Request not found at least once, expected:<{" + NEW_LINE + " \"path\" : \"" + calculatePath("some_path") + "\"," + NEW_LINE + " \"secure\" : true" + NEW_LINE + "}> but was:<{" + NEW_LINE + " \"method\" : \"GET\"," + NEW_LINE + " \"path\" : \"" + calculatePath("some_path") + "\"," + NEW_LINE)); } // - in https assertEquals( response() .withStatusCode(OK_200.code()) .withReasonPhrase(OK_200.reasonPhrase()) .withBody("some_body"), makeRequest( request() .withPath(calculatePath("some_secure_path")) .withSecure(true), headersToIgnore) ); try { mockServerClient.verify( request() .withPath(calculatePath("some_secure_path")) .withSecure(false), VerificationTimes.atLeast(1) ); fail(); } catch (AssertionError ae) { assertThat(ae.getMessage(), startsWith("Request not found at least once, expected:<{" + NEW_LINE + " \"path\" : \"" + calculatePath("some_secure_path") + "\"," + NEW_LINE + " \"secure\" : false" + NEW_LINE + "}> but was:<[ {" + NEW_LINE + " \"method\" : \"GET\"," + NEW_LINE + " \"path\" : \"" + calculatePath("some_path") + "\"," + NEW_LINE)); } } @Test public void shouldVerifySequenceOfRequestsReceivedIncludingThoseNotMatchingAnException() { // when mockServerClient.when(request().withPath(calculatePath("some_path.*")), exactly(4)).respond(response().withBody("some_body")); // then assertEquals( response("some_body"), makeRequest( request().withPath(calculatePath("some_path_one")), headersToIgnore) ); assertEquals( notFoundResponse(), makeRequest( request().withPath(calculatePath("not_found")), headersToIgnore) ); assertEquals( response("some_body"), makeRequest( request().withPath(calculatePath("some_path_three")), headersToIgnore) ); mockServerClient.verify(request(calculatePath("some_path_one")), request(calculatePath("some_path_three"))); mockServerClient.verify(request(calculatePath("some_path_one")), request(calculatePath("not_found"))); mockServerClient.verify(request(calculatePath("some_path_one")), request(calculatePath("not_found")), request(calculatePath("some_path_three"))); mockServerClient.verify(request(calculatePath("some_path_one")), request(calculatePath("not_found")), request(calculatePath("some_path_three"))); } @Test public void shouldVerifySequenceOfRequestsNotReceived() { // when mockServerClient.when(request().withPath(calculatePath("some_path.*")), exactly(6)).respond(response().withBody("some_body")); // then assertEquals( response("some_body"), makeRequest( request().withPath(calculatePath("some_path_one")), headersToIgnore) ); assertEquals( response("some_body"), makeRequest( request().withPath(calculatePath("some_path_two")), headersToIgnore) ); assertEquals( response("some_body"), makeRequest( request().withPath(calculatePath("some_path_three")), headersToIgnore) ); try { mockServerClient.verify(request(calculatePath("some_path_two")), request(calculatePath("some_path_one"))); fail(); } catch (AssertionError ae) { assertThat(ae.getMessage(), startsWith("Request sequence not found, expected:<[ {" + NEW_LINE + " \"path\" : \"" + calculatePath("some_path_two") + "\"" + NEW_LINE + "}, {" + NEW_LINE + " \"path\" : \"" + calculatePath("some_path_one") + "\"" + NEW_LINE + "} ]> but was:<[ {" + NEW_LINE + " \"method\" : \"GET\"," + NEW_LINE + " \"path\" : \"" + calculatePath("some_path_one") + "\"," + NEW_LINE)); } try { mockServerClient.verify(request(calculatePath("some_path_three")), request(calculatePath("some_path_two"))); fail(); } catch (AssertionError ae) { assertThat(ae.getMessage(), startsWith("Request sequence not found, expected:<[ {" + NEW_LINE + " \"path\" : \"" + calculatePath("some_path_three") + "\"" + NEW_LINE + "}, {" + NEW_LINE + " \"path\" : \"" + calculatePath("some_path_two") + "\"" + NEW_LINE + "} ]> but was:<[ {" + NEW_LINE + " \"method\" : \"GET\"," + NEW_LINE + " \"path\" : \"" + calculatePath("some_path_one") + "\"," + NEW_LINE)); } try { mockServerClient.verify(request(calculatePath("some_path_four"))); fail(); } catch (AssertionError ae) { assertThat(ae.getMessage(), startsWith("Request sequence not found, expected:<[ {" + NEW_LINE + " \"path\" : \"" + calculatePath("some_path_four") + "\"" + NEW_LINE + "} ]> but was:<[ {" + NEW_LINE + " \"method\" : \"GET\"," + NEW_LINE + " \"path\" : \"" + calculatePath("some_path_one") + "\"," + NEW_LINE)); } } @Test public void shouldRetrieveRecordedRequestsAsJson() { // when mockServerClient.when(request().withPath(calculatePath("some_path.*")), exactly(4)).respond(response().withBody("some_body")); assertEquals( response("some_body"), makeRequest( request().withPath(calculatePath("some_path_one")), headersToIgnore) ); assertEquals( notFoundResponse(), makeRequest( request().withPath(calculatePath("not_found")), headersToIgnore) ); assertEquals( response("some_body"), makeRequest( request().withPath(calculatePath("some_path_three")), headersToIgnore) ); // then verifyRequestsMatches( new HttpRequestSerializer(new MockServerLogger()).deserializeArray(mockServerClient.retrieveRecordedRequests(request().withPath(calculatePath("some_path.*")), Format.JSON)), request(calculatePath("some_path_one")), request(calculatePath("some_path_three")) ); verifyRequestsMatches( new HttpRequestSerializer(new MockServerLogger()).deserializeArray(mockServerClient.retrieveRecordedRequests(request(), Format.JSON)), request(calculatePath("some_path_one")), request(calculatePath("not_found")), request(calculatePath("some_path_three")) ); verifyRequestsMatches( new HttpRequestSerializer(new MockServerLogger()).deserializeArray(mockServerClient.retrieveRecordedRequests(null, Format.JSON)), request(calculatePath("some_path_one")), request(calculatePath("not_found")), request(calculatePath("some_path_three")) ); } @Test public void shouldRetrieveRecordedRequestsAsLogEntries() throws IOException { // when mockServerClient.when(request().withPath(calculatePath("some_path.*")), exactly(4)).respond(response().withBody("some_body")); assertEquals( response("some_body"), makeRequest( request().withPath(calculatePath("some_path_one")), headersToIgnore) ); assertEquals( notFoundResponse(), makeRequest( request().withPath(calculatePath("not_found")), headersToIgnore) ); assertEquals( response("some_body"), makeRequest( request().withPath(calculatePath("some_path_three")), headersToIgnore) ); final ObjectMapper objectMapper = ObjectMapperFactory.createObjectMapper(); final JsonArraySerializer jsonArraySerializer = new JsonArraySerializer(); // then List<String> logEntries = jsonArraySerializer.returnJSONObjects(mockServerClient.retrieveRecordedRequests(request().withPath(calculatePath("some_path.*")), Format.LOG_ENTRIES)); assertThat(logEntries.size(), is(2)); HashMap itemOne = objectMapper.readValue(logEntries.get(0), HashMap.class); assertThat(new ArrayList<String>(itemOne.keySet()), containsInAnyOrder("httpRequest", "timestamp", "expectation")); assertThat(String.valueOf(((LinkedHashMap) itemOne.get("httpRequest")).get("path")), is(calculatePath("some_path_one"))); HashMap itemTwo = objectMapper.readValue(logEntries.get(1), HashMap.class); assertThat(new ArrayList<String>(itemTwo.keySet()), containsInAnyOrder("httpRequest", "timestamp", "expectation")); assertThat(String.valueOf(((LinkedHashMap) itemTwo.get("httpRequest")).get("path")), is(calculatePath("some_path_three"))); logEntries = jsonArraySerializer.returnJSONObjects(mockServerClient.retrieveRecordedRequests(request(), Format.LOG_ENTRIES)); assertThat(logEntries.size(), is(3)); itemOne = objectMapper.readValue(logEntries.get(0), HashMap.class); assertThat(new ArrayList<String>(itemOne.keySet()), containsInAnyOrder("httpRequest", "timestamp", "expectation")); assertThat(String.valueOf(((LinkedHashMap) itemOne.get("httpRequest")).get("path")), is(calculatePath("some_path_one"))); itemTwo = objectMapper.readValue(logEntries.get(1), HashMap.class); assertThat(itemTwo.containsKey("expectation"), is(false)); assertThat(new ArrayList<String>(itemTwo.keySet()), containsInAnyOrder("httpRequest", "timestamp")); assertThat(String.valueOf(((LinkedHashMap) itemTwo.get("httpRequest")).get("path")), is(calculatePath("not_found"))); HashMap itemThree = objectMapper.readValue(logEntries.get(2), HashMap.class); assertThat(new ArrayList<String>(itemThree.keySet()), containsInAnyOrder("httpRequest", "timestamp", "expectation")); assertThat(String.valueOf(((LinkedHashMap) itemThree.get("httpRequest")).get("path")), is(calculatePath("some_path_three"))); logEntries = jsonArraySerializer.returnJSONObjects(mockServerClient.retrieveRecordedRequests(null, Format.LOG_ENTRIES)); assertThat(logEntries.size(), is(3)); itemOne = objectMapper.readValue(logEntries.get(0), HashMap.class); assertThat(new ArrayList<String>(itemOne.keySet()), containsInAnyOrder("httpRequest", "timestamp", "expectation")); assertThat(String.valueOf(((LinkedHashMap) itemOne.get("httpRequest")).get("path")), is(calculatePath("some_path_one"))); itemTwo = objectMapper.readValue(logEntries.get(1), HashMap.class); assertThat(itemTwo.containsKey("expectation"), is(false)); assertThat(new ArrayList<String>(itemTwo.keySet()), containsInAnyOrder("httpRequest", "timestamp")); assertThat(String.valueOf(((LinkedHashMap) itemTwo.get("httpRequest")).get("path")), is(calculatePath("not_found"))); itemThree = objectMapper.readValue(logEntries.get(2), HashMap.class); assertThat(new ArrayList<String>(itemThree.keySet()), containsInAnyOrder("httpRequest", "timestamp", "expectation")); assertThat(String.valueOf(((LinkedHashMap) itemThree.get("httpRequest")).get("path")), is(calculatePath("some_path_three"))); } @Test public void shouldRetrieveActiveExpectationsAsJson() { // when mockServerClient.when(request().withPath(calculatePath("some_path.*")), exactly(4)) .respond(response().withBody("some_body")); mockServerClient.when(request().withPath(calculatePath("some_path.*"))) .respond(response().withBody("some_body")); mockServerClient.when(request().withPath(calculatePath("some_other_path"))) .respond(response().withBody("some_other_body")); mockServerClient.when(request().withPath(calculatePath("some_forward_path"))) .forward(forward()); // then assertThat( mockServerClient.retrieveActiveExpectations(request().withPath(calculatePath("some_path.*")), Format.JSON), is(new ExpectationSerializer(new MockServerLogger()).serialize(Arrays.asList( new Expectation(request().withPath(calculatePath("some_path.*")), exactly(4), TimeToLive.unlimited()) .thenRespond(response().withBody("some_body")), new Expectation(request().withPath(calculatePath("some_path.*"))) .thenRespond(response().withBody("some_body")) ))) ); assertThat( mockServerClient.retrieveActiveExpectations(null, Format.JSON), is(new ExpectationSerializer(new MockServerLogger()).serialize(Arrays.asList( new Expectation(request().withPath(calculatePath("some_path.*")), exactly(4), TimeToLive.unlimited()) .thenRespond(response().withBody("some_body")), new Expectation(request().withPath(calculatePath("some_path.*"))) .thenRespond(response().withBody("some_body")), new Expectation(request().withPath(calculatePath("some_other_path"))) .thenRespond(response().withBody("some_other_body")), new Expectation(request().withPath(calculatePath("some_forward_path"))) .thenForward(forward()) ))) ); assertThat( mockServerClient.retrieveActiveExpectations(request(), Format.JSON), is(new ExpectationSerializer(new MockServerLogger()).serialize(Arrays.asList( new Expectation(request().withPath(calculatePath("some_path.*")), exactly(4), TimeToLive.unlimited()) .thenRespond(response().withBody("some_body")), new Expectation(request().withPath(calculatePath("some_path.*"))) .thenRespond(response().withBody("some_body")), new Expectation(request().withPath(calculatePath("some_other_path"))) .thenRespond(response().withBody("some_other_body")), new Expectation(request().withPath(calculatePath("some_forward_path"))) .thenForward(forward()) ))) ); } @Test public void shouldRetrieveActiveExpectationsAsJava() { // when mockServerClient.when(request().withPath(calculatePath("some_path.*")), exactly(4)) .respond(response().withBody("some_body")); mockServerClient.when(request().withPath(calculatePath("some_path.*"))) .respond(response().withBody("some_body")); mockServerClient.when(request().withPath(calculatePath("some_other_path"))) .respond(response().withBody("some_other_body")); mockServerClient.when(request().withPath(calculatePath("some_forward_path"))) .forward(forward()); // then assertThat( mockServerClient.retrieveActiveExpectations(request().withPath(calculatePath("some_path.*")), Format.JAVA), is(new ExpectationToJavaSerializer().serialize(Arrays.asList( new Expectation(request().withPath(calculatePath("some_path.*")), exactly(4), TimeToLive.unlimited()) .thenRespond(response().withBody("some_body")), new Expectation(request().withPath(calculatePath("some_path.*"))) .thenRespond(response().withBody("some_body")) ))) ); assertThat( mockServerClient.retrieveActiveExpectations(null, Format.JAVA), is(new ExpectationToJavaSerializer().serialize(Arrays.asList( new Expectation(request().withPath(calculatePath("some_path.*")), exactly(4), TimeToLive.unlimited()) .thenRespond(response().withBody("some_body")), new Expectation(request().withPath(calculatePath("some_path.*"))) .thenRespond(response().withBody("some_body")), new Expectation(request().withPath(calculatePath("some_other_path"))) .thenRespond(response().withBody("some_other_body")), new Expectation(request().withPath(calculatePath("some_forward_path"))) .thenForward(forward()) ))) ); assertThat( mockServerClient.retrieveActiveExpectations(request(), Format.JAVA), is(new ExpectationToJavaSerializer().serialize(Arrays.asList( new Expectation(request().withPath(calculatePath("some_path.*")), exactly(4), TimeToLive.unlimited()) .thenRespond(response().withBody("some_body")), new Expectation(request().withPath(calculatePath("some_path.*"))) .thenRespond(response().withBody("some_body")), new Expectation(request().withPath(calculatePath("some_other_path"))) .thenRespond(response().withBody("some_other_body")), new Expectation(request().withPath(calculatePath("some_forward_path"))) .thenForward(forward()) ))) ); } @Test public void shouldRetrieveRecordedExpectationsAsJson() { // when mockServerClient.when(request().withPath(calculatePath("some_path.*")), exactly(4)).forward( forward() .withHost("127.0.0.1") .withPort(insecureEchoServer.getPort()) ); assertEquals( response("some_body_one"), makeRequest( request().withPath(calculatePath("some_path_one")).withBody("some_body_one"), headersToIgnore ) ); assertEquals( response("some_body_three"), makeRequest( request().withPath(calculatePath("some_path_three")).withBody("some_body_three"), headersToIgnore ) ); // then Expectation[] recordedExpectations = new ExpectationSerializer(new MockServerLogger()).deserializeArray( mockServerClient.retrieveRecordedExpectations(request().withPath(calculatePath("some_path_one")), Format.JSON) ); assertThat(recordedExpectations.length, is(1)); verifyRequestsMatches( new HttpRequest[]{ recordedExpectations[0].getHttpRequest() }, request(calculatePath("some_path_one")).withBody("some_body_one") ); assertThat(recordedExpectations[0].getHttpResponse().getBodyAsString(), is("some_body_one")); // and recordedExpectations = new ExpectationSerializer(new MockServerLogger()).deserializeArray( mockServerClient.retrieveRecordedExpectations(request(), Format.JSON) ); assertThat(recordedExpectations.length, is(2)); verifyRequestsMatches( new HttpRequest[]{ recordedExpectations[0].getHttpRequest(), recordedExpectations[1].getHttpRequest() }, request(calculatePath("some_path_one")).withBody("some_body_one"), request(calculatePath("some_path_three")).withBody("some_body_three") ); assertThat(recordedExpectations[0].getHttpResponse().getBodyAsString(), is("some_body_one")); assertThat(recordedExpectations[1].getHttpResponse().getBodyAsString(), is("some_body_three")); // and recordedExpectations = new ExpectationSerializer(new MockServerLogger()).deserializeArray( mockServerClient.retrieveRecordedExpectations(null, Format.JSON) ); assertThat(recordedExpectations.length, is(2)); verifyRequestsMatches( new HttpRequest[]{ recordedExpectations[0].getHttpRequest(), recordedExpectations[1].getHttpRequest() }, request(calculatePath("some_path_one")).withBody("some_body_one"), request(calculatePath("some_path_three")).withBody("some_body_three") ); assertThat(recordedExpectations[0].getHttpResponse().getBodyAsString(), is("some_body_one")); assertThat(recordedExpectations[1].getHttpResponse().getBodyAsString(), is("some_body_three")); } @Test public void shouldClearExpectationsOnly() { // given - some expectations mockServerClient .when( request() .withPath(calculatePath("some_path1")) ) .respond( response() .withBody("some_body1") ); mockServerClient .when( request() .withPath(calculatePath("some_path2")) ) .respond( response() .withBody("some_body2") ); // and - some matching requests assertEquals( response() .withStatusCode(OK_200.code()) .withReasonPhrase(OK_200.reasonPhrase()) .withBody("some_body1"), makeRequest( request() .withPath(calculatePath("some_path1")), headersToIgnore) ); assertEquals( response() .withStatusCode(OK_200.code()) .withReasonPhrase(OK_200.reasonPhrase()) .withBody("some_body2"), makeRequest( request() .withPath(calculatePath("some_path2")), headersToIgnore) ); // when mockServerClient .clear( request() .withPath(calculatePath("some_path1")), ClearType.EXPECTATIONS ); // then - expectations cleared assertThat( mockServerClient.retrieveActiveExpectations(null), arrayContaining( new Expectation(request() .withPath(calculatePath("some_path2"))) .thenRespond( response() .withBody("some_body2") ) ) ); // and then - request log not cleared verifyRequestsMatches( mockServerClient.retrieveRecordedRequests(null), request(calculatePath("some_path1")), request(calculatePath("some_path2")) ); } @Test public void shouldClearLogsOnly() { // given - some expectations mockServerClient .when( request() .withPath(calculatePath("some_path1")) ) .respond( response() .withBody("some_body1") ); mockServerClient .when( request() .withPath(calculatePath("some_path2")) ) .respond( response() .withBody("some_body2") ); // and - some matching requests assertEquals( response() .withStatusCode(OK_200.code()) .withReasonPhrase(OK_200.reasonPhrase()) .withBody("some_body1"), makeRequest( request() .withPath(calculatePath("some_path1")), headersToIgnore) ); assertEquals( response() .withStatusCode(OK_200.code()) .withReasonPhrase(OK_200.reasonPhrase()) .withBody("some_body2"), makeRequest( request() .withPath(calculatePath("some_path2")), headersToIgnore) ); // when mockServerClient .clear( request() .withPath(calculatePath("some_path1")), ClearType.LOG ); // then - expectations cleared assertThat( mockServerClient.retrieveActiveExpectations(null), arrayContaining( new Expectation(request() .withPath(calculatePath("some_path1"))) .thenRespond( response() .withBody("some_body1") ), new Expectation(request() .withPath(calculatePath("some_path2"))) .thenRespond( response() .withBody("some_body2") ) ) ); // and then - request log cleared verifyRequestsMatches( mockServerClient.retrieveRecordedRequests(null), request(calculatePath("some_path2")) ); } @Test public void shouldClearAllExpectationsWithNull() { // given mockServerClient .when( request() .withPath(calculatePath("some_path1")) ) .respond( response() .withBody("some_body1") ); mockServerClient .when( request() .withPath(calculatePath("some_path2")) ) .respond( response() .withBody("some_body2") ); assertEquals( response() .withStatusCode(OK_200.code()) .withReasonPhrase(OK_200.reasonPhrase()) .withBody("some_body2"), makeRequest( request() .withPath(calculatePath("some_path2")), headersToIgnore) ); // when mockServerClient.clear(null); // then assertThat(mockServerClient.retrieveActiveExpectations(null), emptyArray()); assertThat(mockServerClient.retrieveRecordedRequests(null), emptyArray()); } @Test public void shouldClearAllExpectationsWithEmptyRequest() { // given mockServerClient .when( request() .withPath(calculatePath("some_path1")) ) .respond( response() .withBody("some_body1") ); mockServerClient .when( request() .withPath(calculatePath("some_path2")) ) .respond( response() .withBody("some_body2") ); assertEquals( response() .withStatusCode(OK_200.code()) .withReasonPhrase(OK_200.reasonPhrase()) .withBody("some_body2"), makeRequest( request() .withPath(calculatePath("some_path2")), headersToIgnore) ); // when mockServerClient.clear(request()); // then assertThat(mockServerClient.retrieveActiveExpectations(null), emptyArray()); assertThat(mockServerClient.retrieveRecordedRequests(null), emptyArray()); } @Test public void shouldClearExpectationsWithXPathBody() { // given mockServerClient .when( request() .withBody(xpath("/bookstore/book[year=2005]/price")) ) .respond( response() .withBody("some_body1") ); mockServerClient .when( request() .withBody(xpath("/bookstore/book[year=2006]/price")) ) .respond( response() .withBody("some_body2") ); // and StringBody xmlBody = new StringBody("" + "<?xml version=\"1.0\" encoding=\"ISO-8859-1\"?>" + NEW_LINE + "<bookstore>" + NEW_LINE + " <book category=\"COOKING\">" + NEW_LINE + " <title lang=\"en\">Everyday Italian</title>" + NEW_LINE + " <author>Giada De Laurentiis</author>" + NEW_LINE + " <year>2005</year>" + NEW_LINE + " <price>30.00</price>" + NEW_LINE + " </book>" + NEW_LINE + " <book category=\"CHILDREN\">" + NEW_LINE + " <title lang=\"en\">Harry Potter</title>" + NEW_LINE + " <author>J K. Rowling</author>" + NEW_LINE + " <year>2006</year>" + NEW_LINE + " <price>29.99</price>" + NEW_LINE + " </book>" + NEW_LINE + " <book category=\"WEB\">" + NEW_LINE + " <title lang=\"en\">Learning XML</title>" + NEW_LINE + " <author>Erik T. Ray</author>" + NEW_LINE + " <year>2003</year>" + NEW_LINE + " <price>31.95</price>" + NEW_LINE + " </book>" + NEW_LINE + "</bookstore>"); // then assertEquals( response() .withStatusCode(OK_200.code()) .withReasonPhrase(OK_200.reasonPhrase()) .withBody("some_body1"), makeRequest( request() .withBody(xmlBody), headersToIgnore) ); // when mockServerClient .clear( request() .withBody(xpath("/bookstore/book[year=2005]/price")) ); // then assertThat( mockServerClient.retrieveActiveExpectations(null), arrayContaining( new Expectation(request() .withBody(xpath("/bookstore/book[year=2006]/price"))) .thenRespond( response() .withBody("some_body2") ) ) ); // - in http assertEquals( response() .withStatusCode(OK_200.code()) .withReasonPhrase(OK_200.reasonPhrase()) .withBody("some_body2"), makeRequest( request() .withBody(xmlBody), headersToIgnore) ); // - in https assertEquals( response() .withStatusCode(OK_200.code()) .withReasonPhrase(OK_200.reasonPhrase()) .withBody("some_body2"), makeRequest( request() .withSecure(true) .withBody(xmlBody), headersToIgnore) ); } @Test public void shouldClearExpectationsWithJsonSchemaBody() { // given JsonSchemaBody jsonSchemaBodyOne = jsonSchema("{" + NEW_LINE + " \"$schema\": \"http://json-schema.org/draft-04/schema#\"," + NEW_LINE + " \"title\": \"Product\"," + NEW_LINE + " \"description\": \"A product from Acme's catalog\"," + NEW_LINE + " \"type\": \"object\"," + NEW_LINE + " \"properties\": {" + NEW_LINE + " \"id\": {" + NEW_LINE + " \"description\": \"The unique identifier for a product\"," + NEW_LINE + " \"type\": \"integer\"" + NEW_LINE + " }," + NEW_LINE + " \"name\": {" + NEW_LINE + " \"description\": \"Name of the product\"," + NEW_LINE + " \"type\": \"string\"" + NEW_LINE + " }," + NEW_LINE + " \"price\": {" + NEW_LINE + " \"type\": \"number\"," + NEW_LINE + " \"minimum\": 0," + NEW_LINE + " \"exclusiveMinimum\": true" + NEW_LINE + " }," + NEW_LINE + " \"tags\": {" + NEW_LINE + " \"type\": \"array\"," + NEW_LINE + " \"items\": {" + NEW_LINE + " \"type\": \"string\"" + NEW_LINE + " }," + NEW_LINE + " \"minItems\": 1," + NEW_LINE + " \"uniqueItems\": true" + NEW_LINE + " }" + NEW_LINE + " }," + NEW_LINE + " \"required\": [\"id\", \"name\", \"price\"]" + NEW_LINE + "}"); JsonSchemaBody jsonSchemaBodyTwo = jsonSchema("{" + NEW_LINE + " \"$schema\": \"http://json-schema.org/draft-04/schema#\"," + NEW_LINE + " \"title\": \"Product\"," + NEW_LINE + " \"description\": \"A product from Acme's catalog\"," + NEW_LINE + " \"type\": \"object\"," + NEW_LINE + " \"properties\": {" + NEW_LINE + " \"id\": {" + NEW_LINE + " \"description\": \"The unique identifier for a product\"," + NEW_LINE + " \"type\": \"integer\"" + NEW_LINE + " }," + NEW_LINE + " \"name\": {" + NEW_LINE + " \"description\": \"Name of the product\"," + NEW_LINE + " \"type\": \"string\"" + NEW_LINE + " }," + NEW_LINE + " \"price\": {" + NEW_LINE + " \"type\": \"number\"," + NEW_LINE + " \"minimum\": 10," + NEW_LINE + " \"exclusiveMinimum\": true" + NEW_LINE + " }," + NEW_LINE + " \"tags\": {" + NEW_LINE + " \"type\": \"array\"," + NEW_LINE + " \"items\": {" + NEW_LINE + " \"type\": \"string\"" + NEW_LINE + " }," + NEW_LINE + " \"minItems\": 1," + NEW_LINE + " \"uniqueItems\": true" + NEW_LINE + " }" + NEW_LINE + " }," + NEW_LINE + " \"required\": [\"id\", \"name\", \"price\"]" + NEW_LINE + "}"); mockServerClient .when( request() .withBody(jsonSchemaBodyOne) ) .respond( response() .withBody("some_body1") ); mockServerClient .when( request() .withBody(jsonSchemaBodyTwo) ) .respond( response() .withBody("some_body2") ); // then assertEquals( response() .withStatusCode(OK_200.code()) .withReasonPhrase(OK_200.reasonPhrase()) .withBody("some_body1"), makeRequest( request() .withBody("{" + NEW_LINE + " \"id\": 1," + NEW_LINE + " \"name\": \"A green door\"," + NEW_LINE + " \"price\": 12.50," + NEW_LINE + " \"tags\": [\"home\", \"green\"]" + NEW_LINE + "}"), headersToIgnore) ); // when mockServerClient .clear( request() .withBody(jsonSchemaBodyOne) ); // then assertThat( mockServerClient.retrieveActiveExpectations(null), arrayContaining( new Expectation(request() .withBody(jsonSchemaBodyTwo)) .thenRespond( response() .withBody("some_body2") ) ) ); // - in http assertEquals( response() .withStatusCode(OK_200.code()) .withReasonPhrase(OK_200.reasonPhrase()) .withBody("some_body2"), makeRequest( request() .withBody("{" + NEW_LINE + " \"id\": 1," + NEW_LINE + " \"name\": \"A green door\"," + NEW_LINE + " \"price\": 12.50," + NEW_LINE + " \"tags\": [\"home\", \"green\"]" + NEW_LINE + "}"), headersToIgnore) ); // - in https assertEquals( response() .withStatusCode(OK_200.code()) .withReasonPhrase(OK_200.reasonPhrase()) .withBody("some_body2"), makeRequest( request() .withSecure(true) .withBody("{" + NEW_LINE + " \"id\": 1," + NEW_LINE + " \"name\": \"A green door\"," + NEW_LINE + " \"price\": 12.50," + NEW_LINE + " \"tags\": [\"home\", \"green\"]" + NEW_LINE + "}"), headersToIgnore) ); } @Test public void shouldClearExpectationsWithParameterBody() { // given mockServerClient .when( request() .withBody(params(param("bodyParameterNameOne", "bodyParameterValueOne"))) ) .respond( response() .withBody("some_body1") ); mockServerClient .when( request() .withBody(params(param("bodyParameterNameTwo", "bodyParameterValueTwo"))) ) .respond( response() .withBody("some_body2") ); // then assertEquals( response() .withStatusCode(OK_200.code()) .withReasonPhrase(OK_200.reasonPhrase()) .withBody("some_body1"), makeRequest( request() .withBody(params(param("bodyParameterName.*", "bodyParameterValue.*"))), headersToIgnore) ); // when mockServerClient .clear( request() .withBody(params(param("bodyParameterNameOne", "bodyParameterValueOne"))) ); // then assertThat( mockServerClient.retrieveActiveExpectations(null), arrayContaining( new Expectation(request() .withBody(params(param("bodyParameterNameTwo", "bodyParameterValueTwo")))) .thenRespond( response() .withBody("some_body2") ) ) ); // - in http assertEquals( response() .withStatusCode(OK_200.code()) .withReasonPhrase(OK_200.reasonPhrase()) .withBody("some_body2"), makeRequest( request() .withBody(params(param("bodyParameterName.*", "bodyParameterValue.*"))), headersToIgnore) ); // - in https assertEquals( response() .withStatusCode(OK_200.code()) .withReasonPhrase(OK_200.reasonPhrase()) .withBody("some_body2"), makeRequest( request() .withSecure(true) .withBody(params(param("bodyParameterName.*", "bodyParameterValue.*"))), headersToIgnore) ); } @Test public void shouldEnsureThatInterruptedRequestsAreVerifiable() throws Exception { mockServerClient .when( request(calculatePath("delayed")) ) .respond( response("delayed data") .withDelay(new Delay(TimeUnit.SECONDS, 3)) ); Future<HttpResponse> delayedFuture = Executors.newSingleThreadExecutor().submit(new Callable<HttpResponse>() { @Override public HttpResponse call() throws Exception { return httpClient.sendRequest( request(addContextToPath(calculatePath("delayed"))) .withHeader(HOST.toString(), "localhost:" + getServerPort()) ).get(10, TimeUnit.SECONDS); } }); Uninterruptibles.sleepUninterruptibly(1, TimeUnit.SECONDS); // Let request reach server delayedFuture.cancel(true); // Then interrupt requesting thread mockServerClient.verify(request(calculatePath("delayed"))); // We should be able to verify request that reached server even though its later interrupted } @Test public void shouldEnsureThatRequestDelaysDoNotAffectOtherRequests() throws Exception { mockServerClient .when( request("/slow") ) .respond( response("super slow") .withDelay(new Delay(TimeUnit.SECONDS, 5)) ); mockServerClient .when( request("/fast") ) .respond( response("quite fast") ); ExecutorService executorService = Executors.newFixedThreadPool(2); Future<Long> slowFuture = executorService.submit(new Callable<Long>() { @Override public Long call() throws Exception { long start = System.currentTimeMillis(); makeRequest(request("/slow"), Collections.<String>emptySet()); return System.currentTimeMillis() - start; } }); // Let fast request come to the server slightly after slow request Uninterruptibles.sleepUninterruptibly(1, TimeUnit.SECONDS); Future<Long> fastFuture = executorService.submit(new Callable<Long>() { @Override public Long call() throws Exception { long start = System.currentTimeMillis(); makeRequest(request("/fast"), Collections.<String>emptySet()); return System.currentTimeMillis() - start; } }); Long slowRequestElapsedMillis = slowFuture.get(); Long fastRequestElapsedMillis = fastFuture.get(); assertThat("Slow request takes less than expected", slowRequestElapsedMillis, is(greaterThan(5 * 1000L))); assertThat("Fast request takes longer than expected", fastRequestElapsedMillis, is(lessThan(5 * 1000L))); } }
gabrielf/mockserver
mockserver-integration-testing/src/main/java/org/mockserver/integration/server/AbstractExtendedMockingIntegrationTest.java
937
package org.mockserver.integration.server; import com.google.common.util.concurrent.Uninterruptibles; import io.netty.util.CharsetUtil; import org.apache.commons.io.IOUtils; import org.junit.BeforeClass; import org.junit.Test; import org.mockserver.log.TimeService; import org.mockserver.log.model.LogEntry; import org.mockserver.logging.MockServerLogger; import org.mockserver.matchers.MatchType; import org.mockserver.matchers.TimeToLive; import org.mockserver.mock.Expectation; import org.mockserver.model.*; import org.mockserver.serialization.ExpectationSerializer; import org.mockserver.serialization.HttpRequestSerializer; import org.mockserver.serialization.LogEntrySerializer; import org.mockserver.serialization.java.ExpectationToJavaSerializer; import org.mockserver.verify.VerificationTimes; import org.slf4j.event.Level; import java.io.IOException; import java.nio.charset.StandardCharsets; import java.util.Arrays; import java.util.Collections; import java.util.List; import java.util.concurrent.*; import static io.netty.handler.codec.http.HttpHeaderNames.*; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.*; import static org.hamcrest.core.Is.is; import static org.hamcrest.core.StringStartsWith.startsWith; import static org.hamcrest.number.OrderingComparison.greaterThan; import static org.junit.Assert.assertEquals; import static org.junit.Assert.fail; import static org.mockserver.character.Character.NEW_LINE; import static org.mockserver.log.model.LogEntry.LogMessageType.RECEIVED_REQUEST; import static org.mockserver.matchers.Times.exactly; import static org.mockserver.model.BinaryBody.binary; import static org.mockserver.model.Cookie.cookie; import static org.mockserver.model.Header.header; import static org.mockserver.model.HttpForward.forward; import static org.mockserver.model.HttpRequest.request; import static org.mockserver.model.HttpResponse.notFoundResponse; import static org.mockserver.model.HttpResponse.response; import static org.mockserver.model.HttpStatusCode.*; import static org.mockserver.model.JsonBody.json; import static org.mockserver.model.JsonPathBody.jsonPath; import static org.mockserver.model.JsonSchemaBody.jsonSchema; import static org.mockserver.model.NottableString.not; import static org.mockserver.model.NottableString.string; import static org.mockserver.model.Parameter.param; import static org.mockserver.model.ParameterBody.params; import static org.mockserver.model.RegexBody.regex; import static org.mockserver.model.StringBody.exact; import static org.mockserver.model.StringBody.subString; import static org.mockserver.model.XPathBody.xpath; import static org.mockserver.model.XmlBody.xml; import static org.mockserver.model.XmlSchemaBody.xmlSchema; import static org.mockserver.model.XmlSchemaBody.xmlSchemaFromResource; /** * @author jamesdbloom */ public abstract class AbstractExtendedMockingIntegrationTest extends AbstractBasicMockingIntegrationTest { @BeforeClass public static void fixTime() { TimeService.fixedTime = true; } @Test public void shouldReturnResponseForRequestInSsl() { // when mockServerClient.when(request().withSecure(true)).respond(response().withBody("some_body")); // then // - in http assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()) .withReasonPhrase(HttpStatusCode.NOT_FOUND_404.reasonPhrase()), makeRequest( request() .withPath(calculatePath("")), headersToIgnore) ); // - in https assertEquals( response() .withStatusCode(OK_200.code()) .withReasonPhrase(OK_200.reasonPhrase()) .withBody("some_body"), makeRequest( request() .withSecure(true) .withPath(calculatePath("")), headersToIgnore) ); } @Test public void shouldReturnResponseForRequestNotInSsl() { // when mockServerClient.when(request().withSecure(false)).respond(response().withBody("some_body")); // then // - in http assertEquals( response() .withStatusCode(OK_200.code()) .withReasonPhrase(OK_200.reasonPhrase()) .withBody("some_body"), makeRequest( request() .withPath(calculatePath("")), headersToIgnore) ); // - in https assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()) .withReasonPhrase(HttpStatusCode.NOT_FOUND_404.reasonPhrase()), makeRequest( request() .withSecure(true) .withPath(calculatePath("")), headersToIgnore) ); } @Test public void shouldReturnResponseByMatchingPath() { // when mockServerClient .when( request() .withPath(calculatePath("some_path1")) ) .respond( response() .withBody("some_body1") ); mockServerClient .when( request() .withPath(calculatePath("some_path2")) ) .respond( response() .withBody("some_body2") ); // then // - in http assertEquals( response() .withStatusCode(OK_200.code()) .withReasonPhrase(OK_200.reasonPhrase()) .withBody("some_body2"), makeRequest( request() .withPath(calculatePath("some_path2")), headersToIgnore) ); assertEquals( response() .withStatusCode(OK_200.code()) .withReasonPhrase(OK_200.reasonPhrase()) .withBody("some_body1"), makeRequest( request() .withPath(calculatePath("some_path1")), headersToIgnore) ); // - in https assertEquals( response() .withStatusCode(OK_200.code()) .withReasonPhrase(OK_200.reasonPhrase()) .withBody("some_body2"), makeRequest( request() .withSecure(true) .withPath(calculatePath("some_path2")), headersToIgnore) ); assertEquals( response() .withStatusCode(OK_200.code()) .withReasonPhrase(OK_200.reasonPhrase()) .withBody("some_body1"), makeRequest( request() .withSecure(true) .withPath(calculatePath("some_path1")), headersToIgnore) ); } @Test public void shouldReturnResponseByMatchingPathExactTimes() { // when mockServerClient .when( request() .withPath(calculatePath("some_path")), exactly(2) ) .respond( response() .withBody("some_body") ); // then // - in http assertEquals( response() .withStatusCode(OK_200.code()) .withReasonPhrase(OK_200.reasonPhrase()) .withBody("some_body"), makeRequest( request() .withPath(calculatePath("some_path")), headersToIgnore) ); // - in https assertEquals( response() .withStatusCode(OK_200.code()) .withReasonPhrase(OK_200.reasonPhrase()) .withBody("some_body"), makeRequest( request() .withSecure(true) .withPath(calculatePath("some_path")), headersToIgnore) ); // - in http assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()) .withReasonPhrase(HttpStatusCode.NOT_FOUND_404.reasonPhrase()), makeRequest( request() .withPath(calculatePath("some_path")), headersToIgnore) ); // - in https assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()) .withReasonPhrase(HttpStatusCode.NOT_FOUND_404.reasonPhrase()), makeRequest( request() .withSecure(true) .withPath(calculatePath("some_path")), headersToIgnore) ); } @Test public void shouldReturnResponseWhenTimeToLiveHasNotExpired() { // when mockServerClient .when( request().withPath(calculatePath("some_path")), exactly(2), TimeToLive.exactly(TimeUnit.HOURS, 1L) ) .respond( response().withBody("some_body") ); // then // - in http assertEquals( response() .withStatusCode(OK_200.code()) .withReasonPhrase(OK_200.reasonPhrase()) .withBody("some_body"), makeRequest( request() .withPath(calculatePath("some_path")), headersToIgnore) ); // - in https assertEquals( response() .withStatusCode(OK_200.code()) .withReasonPhrase(OK_200.reasonPhrase()) .withBody("some_body"), makeRequest( request() .withSecure(true) .withPath(calculatePath("some_path")), headersToIgnore) ); // - in http assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()) .withReasonPhrase(HttpStatusCode.NOT_FOUND_404.reasonPhrase()), makeRequest( request() .withPath(calculatePath("some_path")), headersToIgnore) ); // - in https assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()) .withReasonPhrase(HttpStatusCode.NOT_FOUND_404.reasonPhrase()), makeRequest( request() .withSecure(true) .withPath(calculatePath("some_path")), headersToIgnore) ); } @Test public void shouldReturnMatchRequestWithBodyInUTF16() { // when String body = "我说中国话"; mockServerClient .when( request() .withBody(body, StandardCharsets.UTF_16) ) .respond( response() .withBody(body, StandardCharsets.UTF_8) ); // then // - in http assertEquals( response() .withStatusCode(OK_200.code()) .withReasonPhrase(OK_200.reasonPhrase()) .withHeader(CONTENT_TYPE.toString(), MediaType.PLAIN_TEXT_UTF_8.toString()) .withBody(body, MediaType.PLAIN_TEXT_UTF_8), makeRequest( request() .withPath(calculatePath("")) .withBody(body, StandardCharsets.UTF_16), headersToIgnore) ); // - in https assertEquals( response() .withStatusCode(OK_200.code()) .withReasonPhrase(OK_200.reasonPhrase()) .withHeader(CONTENT_TYPE.toString(), MediaType.PLAIN_TEXT_UTF_8.toString()) .withBody(body, MediaType.PLAIN_TEXT_UTF_8), makeRequest( request() .withSecure(true) .withPath(calculatePath("")) .withBody(body, StandardCharsets.UTF_16), headersToIgnore) ); } @Test public void shouldReturnMatchRequestWithBodyInUTF8WithContentTypeHeader() { // when String body = "我说中国话"; mockServerClient .when( request() .withHeader(CONTENT_TYPE.toString(), MediaType.PLAIN_TEXT_UTF_8.toString()) .withBody(body) ) .respond( response() .withBody(body, StandardCharsets.UTF_8) ); // then // - in http assertEquals( response() .withStatusCode(OK_200.code()) .withReasonPhrase(OK_200.reasonPhrase()) .withHeader(CONTENT_TYPE.toString(), MediaType.PLAIN_TEXT_UTF_8.toString()) .withBody(body, MediaType.PLAIN_TEXT_UTF_8), makeRequest( request() .withHeader(CONTENT_TYPE.toString(), MediaType.PLAIN_TEXT_UTF_8.toString()) .withPath(calculatePath("")) .withBody(body, StandardCharsets.UTF_8), headersToIgnore) ); // - in https assertEquals( response() .withStatusCode(OK_200.code()) .withReasonPhrase(OK_200.reasonPhrase()) .withHeader(CONTENT_TYPE.toString(), MediaType.PLAIN_TEXT_UTF_8.toString()) .withBody(body, MediaType.PLAIN_TEXT_UTF_8), makeRequest( request() .withHeader(CONTENT_TYPE.toString(), MediaType.PLAIN_TEXT_UTF_8.toString()) .withSecure(true) .withPath(calculatePath("")) .withBody(body, StandardCharsets.UTF_8), headersToIgnore) ); } @Test public void shouldReturnResponseWithBodyInUTF16() { // when String body = "我说中国话"; mockServerClient .when( request() .withHeader(CONTENT_TYPE.toString(), MediaType.create("text", "plain").withCharset(StandardCharsets.UTF_16).toString()) .withBody(body) ) .respond( response() .withHeader(CONTENT_TYPE.toString(), MediaType.create("text", "plain").withCharset(StandardCharsets.UTF_16).toString()) .withBody(body, StandardCharsets.UTF_16) ); // then // - in http assertEquals( response() .withStatusCode(OK_200.code()) .withReasonPhrase(OK_200.reasonPhrase()) .withHeader(CONTENT_TYPE.toString(), MediaType.create("text", "plain").withCharset(StandardCharsets.UTF_16).toString()) .withBody(body, StandardCharsets.UTF_16), makeRequest( request() .withHeader(CONTENT_TYPE.toString(), MediaType.create("text", "plain").withCharset(StandardCharsets.UTF_16).toString()) .withPath(calculatePath("")) .withBody(body), headersToIgnore) ); // - in https assertEquals( response() .withStatusCode(OK_200.code()) .withReasonPhrase(OK_200.reasonPhrase()) .withHeader(CONTENT_TYPE.toString(), MediaType.create("text", "plain").withCharset(StandardCharsets.UTF_16).toString()) .withBody(body, StandardCharsets.UTF_16), makeRequest( request() .withHeader(CONTENT_TYPE.toString(), MediaType.create("text", "plain").withCharset(StandardCharsets.UTF_16).toString()) .withSecure(true) .withPath(calculatePath("")) .withBody(body), headersToIgnore) ); } @Test public void shouldReturnResponseWithBodyInUTF8WithContentTypeHeader() { // when String body = "我说中国话"; mockServerClient .when( request() ) .respond( response() .withHeader(CONTENT_TYPE.toString(), MediaType.PLAIN_TEXT_UTF_8.toString()) .withBody(body) ); // then // - in http assertEquals( response() .withStatusCode(OK_200.code()) .withReasonPhrase(OK_200.reasonPhrase()) .withHeader(CONTENT_TYPE.toString(), MediaType.PLAIN_TEXT_UTF_8.toString()) .withBody(body, MediaType.PLAIN_TEXT_UTF_8), makeRequest( request() .withPath(calculatePath("")), headersToIgnore) ); // - in https assertEquals( response() .withStatusCode(OK_200.code()) .withReasonPhrase(OK_200.reasonPhrase()) .withHeader(CONTENT_TYPE.toString(), MediaType.PLAIN_TEXT_UTF_8.toString()) .withBody(body, MediaType.PLAIN_TEXT_UTF_8), makeRequest( request() .withSecure(true) .withPath(calculatePath("")), headersToIgnore) ); } @Test public void shouldReturnResponseWithBodyInUTF8WithNoContentTypeHeader() { // when String body = "我说中国话"; mockServerClient .when( request() ) .respond( response() .withBody(body, CharsetUtil.UTF_8) ); // then // - in http assertEquals( response() .withStatusCode(OK_200.code()) .withReasonPhrase(OK_200.reasonPhrase()) .withHeader(CONTENT_TYPE.toString(), MediaType.PLAIN_TEXT_UTF_8.toString()) .withBody(body, CharsetUtil.UTF_8), makeRequest( request() .withPath(calculatePath("")), headersToIgnore) ); // - in https assertEquals( response() .withStatusCode(OK_200.code()) .withReasonPhrase(OK_200.reasonPhrase()) .withHeader(CONTENT_TYPE.toString(), MediaType.PLAIN_TEXT_UTF_8.toString()) .withBody(body, CharsetUtil.UTF_8), makeRequest( request() .withSecure(true) .withPath(calculatePath("")), headersToIgnore) ); } @Test public void shouldReturnResponseByMatchingSubStringBody() { // when mockServerClient .when( request() .withBody( subString("random") ), exactly(2) ) .respond( response() .withBody("some_sub_string_body_response") ); // then // - in http assertEquals( response() .withStatusCode(OK_200.code()) .withReasonPhrase(OK_200.reasonPhrase()) .withBody("some_sub_string_body_response"), makeRequest( request() .withMethod("POST") .withPath(calculatePath("some_path")) .withBody("some_random_body"), headersToIgnore) ); // - in https assertEquals( response() .withStatusCode(OK_200.code()) .withReasonPhrase(OK_200.reasonPhrase()) .withBody("some_sub_string_body_response"), makeRequest( request() .withSecure(true) .withMethod("POST") .withPath(calculatePath("some_path")) .withBody("some_random_body"), headersToIgnore) ); } @Test public void shouldReturnResponseByMatchingNotRegexBody() { // when mockServerClient .when( request() .withMethod("POST") .withBody(Body.not(regex("10\\.\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}"))) ) .respond( response() .withBody("some_not_regex_body_response") ); // then // - in http // should not match (because body matches regex) assertEquals( response() .withStatusCode(NOT_FOUND_404.code()) .withReasonPhrase(NOT_FOUND_404.reasonPhrase()), makeRequest( request() .withMethod("POST") .withBody("10.2.3.123"), headersToIgnore) ); // should match (because body doesn't matches regex) assertEquals( response() .withStatusCode(OK_200.code()) .withReasonPhrase(OK_200.reasonPhrase()) .withBody("some_not_regex_body_response"), makeRequest( request() .withMethod("POST") .withBody("10.2.3.1234"), headersToIgnore) ); // - in https // should not match (because body matches regex) assertEquals( response() .withStatusCode(NOT_FOUND_404.code()) .withReasonPhrase(NOT_FOUND_404.reasonPhrase()), makeRequest( request() .withSecure(true) .withMethod("POST") .withBody("10.2.3.123"), headersToIgnore) ); // should match (because body doesn't matches regex) assertEquals( response() .withStatusCode(OK_200.code()) .withReasonPhrase(OK_200.reasonPhrase()) .withBody("some_not_regex_body_response"), makeRequest( request() .withSecure(true) .withMethod("POST") .withBody("10.2.3.1234"), headersToIgnore) ); } @Test public void shouldReturnResponseByMatchingNotSubStringBody() { // when mockServerClient .when( request() .withMethod("POST") .withBody(Body.not(subString("some_body"))) ) .respond( response() .withBody("some_not_regex_body_response") ); // then // - in http // should not match (because body matches regex) assertEquals( response() .withStatusCode(NOT_FOUND_404.code()) .withReasonPhrase(NOT_FOUND_404.reasonPhrase()), makeRequest( request() .withMethod("POST") .withBody("some_body_full_string"), headersToIgnore) ); // should match (because body doesn't matches regex) assertEquals( response() .withStatusCode(OK_200.code()) .withReasonPhrase(OK_200.reasonPhrase()) .withBody("some_not_regex_body_response"), makeRequest( request() .withMethod("POST") .withBody("some_other_body_full_string"), headersToIgnore) ); // - in https // should not match (because body matches regex) assertEquals( response() .withStatusCode(NOT_FOUND_404.code()) .withReasonPhrase(NOT_FOUND_404.reasonPhrase()), makeRequest( request() .withSecure(true) .withMethod("POST") .withBody("some_body_full_string"), headersToIgnore) ); // should match (because body doesn't matches regex) assertEquals( response() .withStatusCode(OK_200.code()) .withReasonPhrase(OK_200.reasonPhrase()) .withBody("some_not_regex_body_response"), makeRequest( request() .withSecure(true) .withMethod("POST") .withBody("some_other_body_full_string"), headersToIgnore) ); } @Test public void shouldReturnResponseByMatchingNotExactBody() { // when mockServerClient .when( request() .withMethod("POST") .withBody(Body.not(exact("some_body"))) ) .respond( response() .withBody("some_not_regex_body_response") ); // then // - in http // should not match (because body matches regex) assertEquals( response() .withStatusCode(NOT_FOUND_404.code()) .withReasonPhrase(NOT_FOUND_404.reasonPhrase()), makeRequest( request() .withMethod("POST") .withBody("some_body"), headersToIgnore) ); // should match (because body doesn't matches regex) assertEquals( response() .withStatusCode(OK_200.code()) .withReasonPhrase(OK_200.reasonPhrase()) .withBody("some_not_regex_body_response"), makeRequest( request() .withMethod("POST") .withBody("some_other_body"), headersToIgnore) ); // - in https // should not match (because body matches regex) assertEquals( response() .withStatusCode(NOT_FOUND_404.code()) .withReasonPhrase(NOT_FOUND_404.reasonPhrase()), makeRequest( request() .withSecure(true) .withMethod("POST") .withBody("some_body"), headersToIgnore) ); // should match (because body doesn't matches regex) assertEquals( response() .withStatusCode(OK_200.code()) .withReasonPhrase(OK_200.reasonPhrase()) .withBody("some_not_regex_body_response"), makeRequest( request() .withSecure(true) .withMethod("POST") .withBody("some_other_body"), headersToIgnore) ); } @Test public void shouldReturnResponseByMatchingBodyWithXPath() { // when mockServerClient.when(request().withBody(xpath("/bookstore/book[price>30]/price")), exactly(2)).respond(response().withBody("some_body")); // then // - in http assertEquals( response() .withStatusCode(OK_200.code()) .withReasonPhrase(OK_200.reasonPhrase()) .withBody("some_body"), makeRequest( request() .withPath(calculatePath("some_path")) .withMethod("POST") .withBody(new StringBody("" + "<?xml version=\"1.0\" encoding=\"ISO-8859-1\"?>" + NEW_LINE + "<bookstore>" + NEW_LINE + " <book category=\"COOKING\">" + NEW_LINE + " <title lang=\"en\">Everyday Italian</title>" + NEW_LINE + " <author>Giada De Laurentiis</author>" + NEW_LINE + " <year>2005</year>" + NEW_LINE + " <price>30.00</price>" + NEW_LINE + " </book>" + NEW_LINE + " <book category=\"CHILDREN\">" + NEW_LINE + " <title lang=\"en\">Harry Potter</title>" + NEW_LINE + " <author>J K. Rowling</author>" + NEW_LINE + " <year>2005</year>" + NEW_LINE + " <price>29.99</price>" + NEW_LINE + " </book>" + NEW_LINE + " <book category=\"WEB\">" + NEW_LINE + " <title lang=\"en\">Learning XML</title>" + NEW_LINE + " <author>Erik T. Ray</author>" + NEW_LINE + " <year>2003</year>" + NEW_LINE + " <price>31.95</price>" + NEW_LINE + " </book>" + NEW_LINE + "</bookstore>")), headersToIgnore) ); // - in https assertEquals( response() .withStatusCode(OK_200.code()) .withReasonPhrase(OK_200.reasonPhrase()) .withBody("some_body"), makeRequest( request() .withSecure(true) .withPath(calculatePath("some_path")) .withMethod("POST") .withBody(new StringBody("" + "<?xml version=\"1.0\" encoding=\"ISO-8859-1\"?>" + NEW_LINE + "<bookstore>" + NEW_LINE + " <book category=\"COOKING\">" + NEW_LINE + " <title lang=\"en\">Everyday Italian</title>" + NEW_LINE + " <author>Giada De Laurentiis</author>" + NEW_LINE + " <year>2005</year>" + NEW_LINE + " <price>30.00</price>" + NEW_LINE + " </book>" + NEW_LINE + " <book category=\"CHILDREN\">" + NEW_LINE + " <title lang=\"en\">Harry Potter</title>" + NEW_LINE + " <author>J K. Rowling</author>" + NEW_LINE + " <year>2005</year>" + NEW_LINE + " <price>29.99</price>" + NEW_LINE + " </book>" + NEW_LINE + " <book category=\"WEB\">" + NEW_LINE + " <title lang=\"en\">Learning XML</title>" + NEW_LINE + " <author>Erik T. Ray</author>" + NEW_LINE + " <year>2003</year>" + NEW_LINE + " <price>31.95</price>" + NEW_LINE + " </book>" + NEW_LINE + "</bookstore>")), headersToIgnore) ); } @Test public void shouldReturnResponseByMatchingBodyWithXmlSchema() { // when mockServerClient.when(request() .withBody( xmlSchema("<?xml version=\"1.0\" encoding=\"UTF-8\"?>" + NEW_LINE + "<xs:schema xmlns:xs=\"http://www.w3.org/2001/XMLSchema\" elementFormDefault=\"qualified\" attributeFormDefault=\"unqualified\">" + NEW_LINE + " <!-- XML Schema Generated from XML Document on Wed Jun 28 2017 21:52:45 GMT+0100 (BST) -->" + NEW_LINE + " <!-- with XmlGrid.net Free Online Service http://xmlgrid.net -->" + NEW_LINE + " <xs:element name=\"notes\">" + NEW_LINE + " <xs:complexType>" + NEW_LINE + " <xs:sequence>" + NEW_LINE + " <xs:element name=\"note\" maxOccurs=\"unbounded\">" + NEW_LINE + " <xs:complexType>" + NEW_LINE + " <xs:sequence>" + NEW_LINE + " <xs:element name=\"to\" minOccurs=\"1\" maxOccurs=\"1\" type=\"xs:string\"></xs:element>" + NEW_LINE + " <xs:element name=\"from\" minOccurs=\"1\" maxOccurs=\"1\" type=\"xs:string\"></xs:element>" + NEW_LINE + " <xs:element name=\"heading\" minOccurs=\"1\" maxOccurs=\"1\" type=\"xs:string\"></xs:element>" + NEW_LINE + " <xs:element name=\"body\" minOccurs=\"1\" maxOccurs=\"1\" type=\"xs:string\"></xs:element>" + NEW_LINE + " </xs:sequence>" + NEW_LINE + " </xs:complexType>" + NEW_LINE + " </xs:element>" + NEW_LINE + " </xs:sequence>" + NEW_LINE + " </xs:complexType>" + NEW_LINE + " </xs:element>" + NEW_LINE + "</xs:schema>")), exactly(2) ) .respond( response() .withBody("some_body") ); // then // - in http assertEquals( response() .withStatusCode(NOT_FOUND_404.code()) .withReasonPhrase(NOT_FOUND_404.reasonPhrase()), makeRequest( request() .withMethod("POST") .withBody("<?xml version=\"1.0\" encoding=\"utf-8\"?>" + NEW_LINE + "<notes>" + NEW_LINE + " <note>" + NEW_LINE + " <to>Bob</to>" + NEW_LINE + " <heading>Reminder</heading>" + NEW_LINE + " <body>Buy Bread</body>" + NEW_LINE + " </note>" + NEW_LINE + " <note>" + NEW_LINE + " <to>Jack</to>" + NEW_LINE + " <from>Jill</from>" + NEW_LINE + " <heading>Reminder</heading>" + NEW_LINE + " <body>Wash Shirts</body>" + NEW_LINE + " </note>" + NEW_LINE + "</notes>"), headersToIgnore) ); assertEquals( response() .withStatusCode(OK_200.code()) .withReasonPhrase(OK_200.reasonPhrase()) .withBody("some_body"), makeRequest( request() .withPath(calculatePath("some_path")) .withMethod("POST") .withBody("<?xml version=\"1.0\" encoding=\"utf-8\"?>" + NEW_LINE + "<notes>" + NEW_LINE + " <note>" + NEW_LINE + " <to>Bob</to>" + NEW_LINE + " <from>Bill</from>" + NEW_LINE + " <heading>Reminder</heading>" + NEW_LINE + " <body>Buy Bread</body>" + NEW_LINE + " </note>" + NEW_LINE + " <note>" + NEW_LINE + " <to>Jack</to>" + NEW_LINE + " <from>Jill</from>" + NEW_LINE + " <heading>Reminder</heading>" + NEW_LINE + " <body>Wash Shirts</body>" + NEW_LINE + " </note>" + NEW_LINE + "</notes>"), headersToIgnore) ); // - in https assertEquals( response() .withStatusCode(OK_200.code()) .withReasonPhrase(OK_200.reasonPhrase()) .withBody("some_body"), makeRequest( request() .withSecure(true) .withPath(calculatePath("some_path")) .withMethod("POST") .withBody("<?xml version=\"1.0\" encoding=\"utf-8\"?>" + NEW_LINE + "<notes>" + NEW_LINE + " <note>" + NEW_LINE + " <to>Bob</to>" + NEW_LINE + " <from>Bill</from>" + NEW_LINE + " <heading>Reminder</heading>" + NEW_LINE + " <body>Buy Bread</body>" + NEW_LINE + " </note>" + NEW_LINE + " <note>" + NEW_LINE + " <to>Jack</to>" + NEW_LINE + " <from>Jill</from>" + NEW_LINE + " <heading>Reminder</heading>" + NEW_LINE + " <body>Wash Shirts</body>" + NEW_LINE + " </note>" + NEW_LINE + "</notes>"), headersToIgnore) ); } @Test public void shouldReturnResponseByMatchingBodyWithXmlSchemaByClasspath() { // when mockServerClient.when(request() .withBody( xmlSchemaFromResource("org/mockserver/model/testXmlSchema.xsd")), exactly(2) ) .respond( response() .withBody("some_body") ); // then // - in http assertEquals( response() .withStatusCode(NOT_FOUND_404.code()) .withReasonPhrase(NOT_FOUND_404.reasonPhrase()), makeRequest( request() .withMethod("POST") .withBody("<?xml version=\"1.0\" encoding=\"utf-8\"?>" + NEW_LINE + "<notes>" + NEW_LINE + " <note>" + NEW_LINE + " <to>Bob</to>" + NEW_LINE + " <heading>Reminder</heading>" + NEW_LINE + " <body>Buy Bread</body>" + NEW_LINE + " </note>" + NEW_LINE + " <note>" + NEW_LINE + " <to>Jack</to>" + NEW_LINE + " <from>Jill</from>" + NEW_LINE + " <heading>Reminder</heading>" + NEW_LINE + " <body>Wash Shirts</body>" + NEW_LINE + " </note>" + NEW_LINE + "</notes>"), headersToIgnore) ); assertEquals( response() .withStatusCode(OK_200.code()) .withReasonPhrase(OK_200.reasonPhrase()) .withBody("some_body"), makeRequest( request() .withPath(calculatePath("some_path")) .withMethod("POST") .withBody("<?xml version=\"1.0\" encoding=\"utf-8\"?>" + NEW_LINE + "<notes>" + NEW_LINE + " <note>" + NEW_LINE + " <to>Bob</to>" + NEW_LINE + " <from>Bill</from>" + NEW_LINE + " <heading>Reminder</heading>" + NEW_LINE + " <body>Buy Bread</body>" + NEW_LINE + " </note>" + NEW_LINE + " <note>" + NEW_LINE + " <to>Jack</to>" + NEW_LINE + " <from>Jill</from>" + NEW_LINE + " <heading>Reminder</heading>" + NEW_LINE + " <body>Wash Shirts</body>" + NEW_LINE + " </note>" + NEW_LINE + "</notes>"), headersToIgnore) ); // - in https assertEquals( response() .withStatusCode(OK_200.code()) .withReasonPhrase(OK_200.reasonPhrase()) .withBody("some_body"), makeRequest( request() .withSecure(true) .withPath(calculatePath("some_path")) .withMethod("POST") .withBody("<?xml version=\"1.0\" encoding=\"utf-8\"?>" + NEW_LINE + "<notes>" + NEW_LINE + " <note>" + NEW_LINE + " <to>Bob</to>" + NEW_LINE + " <from>Bill</from>" + NEW_LINE + " <heading>Reminder</heading>" + NEW_LINE + " <body>Buy Bread</body>" + NEW_LINE + " </note>" + NEW_LINE + " <note>" + NEW_LINE + " <to>Jack</to>" + NEW_LINE + " <from>Jill</from>" + NEW_LINE + " <heading>Reminder</heading>" + NEW_LINE + " <body>Wash Shirts</body>" + NEW_LINE + " </note>" + NEW_LINE + "</notes>"), headersToIgnore) ); } @Test public void shouldReturnResponseByMatchingBodyWithXml() { // when mockServerClient.when(request().withBody(xml("" + "<bookstore>" + NEW_LINE + " <book nationality=\"ITALIAN\" category=\"COOKING\"><title lang=\"en\">Everyday Italian</title><author>Giada De Laurentiis</author><year>2005</year><price>30.00</price></book>" + NEW_LINE + "</bookstore>")), exactly(2)).respond(response().withBody("some_body")); // then // - in http assertEquals( response() .withStatusCode(OK_200.code()) .withReasonPhrase(OK_200.reasonPhrase()) .withBody("some_body"), makeRequest( request() .withPath(calculatePath("some_path")) .withMethod("POST") .withBody(new StringBody("" + "<?xml version=\"1.0\" encoding=\"ISO-8859-1\"?>" + NEW_LINE + "<bookstore>" + NEW_LINE + " <book category=\"COOKING\" nationality=\"ITALIAN\">" + NEW_LINE + " <title lang=\"en\">Everyday Italian</title>" + NEW_LINE + " <author>Giada De Laurentiis</author>" + NEW_LINE + " <year>2005</year>" + NEW_LINE + " <price>30.00</price>" + NEW_LINE + " </book>" + NEW_LINE + "</bookstore>")), headersToIgnore) ); // - in https assertEquals( response() .withStatusCode(OK_200.code()) .withReasonPhrase(OK_200.reasonPhrase()) .withBody("some_body"), makeRequest( request() .withSecure(true) .withPath(calculatePath("some_path")) .withMethod("POST") .withBody(new StringBody("" + "<?xml version=\"1.0\" encoding=\"ISO-8859-1\"?>" + NEW_LINE + "<bookstore>" + NEW_LINE + " <book category=\"COOKING\" nationality=\"ITALIAN\">" + NEW_LINE + " <title lang=\"en\">Everyday Italian</title>" + NEW_LINE + " <author>Giada De Laurentiis</author>" + NEW_LINE + " <year>2005</year>" + NEW_LINE + " <price>30.00</price>" + NEW_LINE + " </book>" + NEW_LINE + "</bookstore>")), headersToIgnore) ); } @Test public void shouldReturnResponseByMatchingBodyWithXmlWithSpecialCharacters() { // when mockServerClient .when( request() .withBody( xml( "" + "<bookstore>" + NEW_LINE + " <book nationality=\"ITALIAN\" category=\"COOKING\"><title>Everyday Italian</title><author>我说中国话</author></book>" + NEW_LINE + "</bookstore>", StandardCharsets.UTF_8 ) ), exactly(2) ) .respond( response() .withBody("some_body") ); // then // - in http assertEquals( response() .withStatusCode(OK_200.code()) .withReasonPhrase(OK_200.reasonPhrase()) .withBody("some_body"), makeRequest( request() .withPath(calculatePath("some_path")) .withMethod("POST") .withHeader("Content-Type", "application/xml; charset=utf-8") .withBody(new StringBody("" + "<?xml version=\"1.0\" encoding=\"UTF-8\"?>" + NEW_LINE + "<bookstore>" + NEW_LINE + " <book category=\"COOKING\" nationality=\"ITALIAN\">" + NEW_LINE + " <title>Everyday Italian</title>" + NEW_LINE + " <author>我说中国话</author>" + NEW_LINE + " </book>" + NEW_LINE + "</bookstore>")), headersToIgnore) ); // - in https assertEquals( response() .withStatusCode(OK_200.code()) .withReasonPhrase(OK_200.reasonPhrase()) .withBody("some_body"), makeRequest( request() .withSecure(true) .withPath(calculatePath("some_path")) .withMethod("POST") .withHeader("Content-Type", "application/xml; charset=utf-8") .withBody(new StringBody("" + "<?xml version=\"1.0\" encoding=\"UTF-8\"?>" + NEW_LINE + "<bookstore>" + NEW_LINE + " <book category=\"COOKING\" nationality=\"ITALIAN\">" + NEW_LINE + " <title>Everyday Italian</title>" + NEW_LINE + " <author>我说中国话</author>" + NEW_LINE + " </book>" + NEW_LINE + "</bookstore>")), headersToIgnore) ); } @Test public void shouldReturnResponseByMatchingBodyWithXmlWithSpecialCharactersClientCharsetDifferent() { // when mockServerClient .when( request() .withBody( xml( "" + "<bookstore>" + NEW_LINE + " <book nationality=\"ITALIAN\" category=\"COOKING\"><title>Everyday Italian</title><author>ÄÑçîüÏ</author></book>" + NEW_LINE + "</bookstore>", StandardCharsets.UTF_8 ) ), exactly(2) ) .respond( response() .withBody("some_body") ); // then // - in http assertEquals( response() .withStatusCode(OK_200.code()) .withReasonPhrase(OK_200.reasonPhrase()) .withBody("some_body"), makeRequest( request() .withPath(calculatePath("some_path")) .withMethod("POST") .withHeader("Content-Type", "application/xml; charset=" + StandardCharsets.ISO_8859_1.name()) .withBody(binary(("" + "<?xml version=\"1.0\" encoding=\"ISO-8859-1\"?>" + NEW_LINE + "<bookstore>" + NEW_LINE + " <book category=\"COOKING\" nationality=\"ITALIAN\">" + NEW_LINE + " <title>Everyday Italian</title>" + NEW_LINE + " <author>ÄÑçîüÏ</author>" + NEW_LINE + " </book>" + NEW_LINE + "</bookstore>").getBytes(StandardCharsets.ISO_8859_1))), headersToIgnore) ); // - in https assertEquals( response() .withStatusCode(OK_200.code()) .withReasonPhrase(OK_200.reasonPhrase()) .withBody("some_body"), makeRequest( request() .withSecure(true) .withPath(calculatePath("some_path")) .withMethod("POST") .withHeader("Content-Type", "application/xml; charset=" + StandardCharsets.ISO_8859_1.name()) .withBody(binary(("" + "<?xml version=\"1.0\" encoding=\"ISO-8859-1\"?>" + NEW_LINE + "<bookstore>" + NEW_LINE + " <book category=\"COOKING\" nationality=\"ITALIAN\">" + NEW_LINE + " <title>Everyday Italian</title>" + NEW_LINE + " <author>ÄÑçîüÏ</author>" + NEW_LINE + " </book>" + NEW_LINE + "</bookstore>").getBytes(StandardCharsets.ISO_8859_1))), headersToIgnore) ); } @Test public void shouldReturnResponseByMatchingBodyWithJson() { // when mockServerClient .when( request() .withBody(json("{" + NEW_LINE + " \"id\": 1," + NEW_LINE + " \"name\": \"A green door\"," + NEW_LINE + " \"price\": 12.50," + NEW_LINE + " \"tags\": [\"home\", \"green\"]" + NEW_LINE + "}")), exactly(2) ) .respond( response() .withStatusCode(ACCEPTED_202.code()) .withReasonPhrase(ACCEPTED_202.reasonPhrase()) .withBody("some_body") ); // then // - in http assertEquals( response() .withStatusCode(ACCEPTED_202.code()) .withReasonPhrase(ACCEPTED_202.reasonPhrase()) .withBody("some_body"), makeRequest( request() .withPath(calculatePath("some_path")) .withMethod("POST") .withBody("{" + NEW_LINE + " \"id\": 1," + NEW_LINE + " \"extra ignored field\": \"some value\"," + NEW_LINE + " \"name\": \"A green door\"," + NEW_LINE + " \"price\": 12.50," + NEW_LINE + " \"tags\": [\"home\", \"green\"]" + NEW_LINE + "}"), headersToIgnore) ); // - in https assertEquals( response() .withStatusCode(ACCEPTED_202.code()) .withReasonPhrase(ACCEPTED_202.reasonPhrase()) .withBody("some_body"), makeRequest( request() .withSecure(true) .withPath(calculatePath("some_path")) .withMethod("POST") .withBody("{" + NEW_LINE + " \"id\": 1," + NEW_LINE + " \"extra ignored array\": [\"one\", \"two\"]," + NEW_LINE + " \"name\": \"A green door\"," + NEW_LINE + " \"price\": 12.50," + NEW_LINE + " \"tags\": [\"home\", \"green\"]" + NEW_LINE + "}"), headersToIgnore) ); } @Test public void shouldReturnResponseByMatchingBodyWithJsonAsRawBody() { // when assertEquals( response() .withStatusCode(CREATED_201.code()) .withReasonPhrase(CREATED_201.reasonPhrase()), makeRequest( request() .withPath(calculatePath("mockserver/expectation")) .withMethod("PUT") .withBody("{" + NEW_LINE + " \"httpRequest\" : {" + NEW_LINE + " \"body\" : {" + NEW_LINE + " \"id\": 1," + NEW_LINE + " \"name\": \"A green door\"," + NEW_LINE + " \"price\": 12.50," + NEW_LINE + " \"tags\": [\"home\", \"green\"]" + NEW_LINE + " }" + NEW_LINE + " }," + NEW_LINE + " \"httpResponse\" : {" + NEW_LINE + " \"body\" : {" + NEW_LINE + " \"id\": 1," + NEW_LINE + " \"name\": \"A green door\"," + NEW_LINE + " \"price\": 12.50," + NEW_LINE + " \"tags\": [\"home\", \"green\"]" + NEW_LINE + " }" + NEW_LINE + " }" + NEW_LINE + "}"), headersToIgnore) ); // then assertEquals( response() .withStatusCode(OK_200.code()) .withReasonPhrase(OK_200.reasonPhrase()) .withHeader(CONTENT_TYPE.toString(), MediaType.create("application", "json").toString()) .withBody(json("{\"id\":1,\"name\":\"A green door\",\"price\":12.5,\"tags\":[\"home\",\"green\"]}", (MediaType) null)), makeRequest( request() .withPath(calculatePath("some_path")) .withMethod("POST") .withBody("{" + NEW_LINE + " \"id\" : 1," + NEW_LINE + " \"name\" : \"A green door\"," + NEW_LINE + " \"price\" : 12.5," + NEW_LINE + " \"tags\" : [ \"home\", \"green\" ]" + NEW_LINE + "}"), headersToIgnore) ); } @Test public void shouldReturnResponseByMatchingBodyWithJsonWithCharsetUTF8() { // when mockServerClient .when( request() .withBody(json("{" + NEW_LINE + " \"ταυτότητα\": 1," + NEW_LINE + " \"όνομα\": \"μια πράσινη πόρτα\"," + NEW_LINE + " \"τιμή\": 12.50," + NEW_LINE + " \"ετικέτες\": [\"σπίτι\", \"πράσινος\"]" + NEW_LINE + "}", StandardCharsets.UTF_16, MatchType.ONLY_MATCHING_FIELDS)), exactly(2) ) .respond( response() .withStatusCode(ACCEPTED_202.code()) .withReasonPhrase(ACCEPTED_202.reasonPhrase()) .withBody("some_body") ); // then // - in http assertEquals( response() .withStatusCode(ACCEPTED_202.code()) .withReasonPhrase(ACCEPTED_202.reasonPhrase()) .withBody("some_body"), makeRequest( request() .withPath(calculatePath("some_path")) .withMethod("POST") .withBody(json("{" + NEW_LINE + " \"ταυτότητα\": 1," + NEW_LINE + " \"επιπλέον αγνοούνται τομέα\": \"κάποια αξία\"," + NEW_LINE + " \"όνομα\": \"μια πράσινη πόρτα\"," + NEW_LINE + " \"τιμή\": 12.50," + NEW_LINE + " \"ετικέτες\": [\"σπίτι\", \"πράσινος\"]" + NEW_LINE + "}", StandardCharsets.UTF_16, MatchType.ONLY_MATCHING_FIELDS)), headersToIgnore) ); // - in https assertEquals( response() .withStatusCode(ACCEPTED_202.code()) .withReasonPhrase(ACCEPTED_202.reasonPhrase()) .withBody("some_body"), makeRequest( request() .withSecure(true) .withPath(calculatePath("some_path")) .withMethod("POST") .withBody(json("{" + NEW_LINE + " \"ταυτότητα\": 1," + NEW_LINE + " \"επιπλέον αγνοούνται σειρά\": [\"ένας\", \"δυο\"]," + NEW_LINE + " \"όνομα\": \"μια πράσινη πόρτα\"," + NEW_LINE + " \"τιμή\": 12.50," + NEW_LINE + " \"ετικέτες\": [\"σπίτι\", \"πράσινος\"]" + NEW_LINE + "}", StandardCharsets.UTF_16, MatchType.ONLY_MATCHING_FIELDS)), headersToIgnore) ); } @Test public void shouldReturnResponseByMatchingBodyWithJsonWithContentTypeHeader() { // when mockServerClient .when( request() .withBody(json("{" + NEW_LINE + " \"ταυτότητα\": 1," + NEW_LINE + " \"όνομα\": \"μια πράσινη πόρτα\"," + NEW_LINE + " \"τιμή\": 12.50," + NEW_LINE + " \"ετικέτες\": [\"σπίτι\", \"πράσινος\"]" + NEW_LINE + "}", StandardCharsets.UTF_16, MatchType.ONLY_MATCHING_FIELDS)), exactly(2) ) .respond( response() .withStatusCode(ACCEPTED_202.code()) .withReasonPhrase(ACCEPTED_202.reasonPhrase()) .withBody("some_body") ); // then // - in http assertEquals( response() .withStatusCode(ACCEPTED_202.code()) .withReasonPhrase(ACCEPTED_202.reasonPhrase()) .withBody("some_body"), makeRequest( request() .withHeader(CONTENT_TYPE.toString(), MediaType.create("text", "plain").withCharset(StandardCharsets.UTF_16).toString()) .withPath(calculatePath("some_path")) .withMethod("POST") .withBody(json("{" + NEW_LINE + " \"ταυτότητα\": 1," + NEW_LINE + " \"επιπλέον αγνοούνται τομέα\": \"κάποια αξία\"," + NEW_LINE + " \"όνομα\": \"μια πράσινη πόρτα\"," + NEW_LINE + " \"τιμή\": 12.50," + NEW_LINE + " \"ετικέτες\": [\"σπίτι\", \"πράσινος\"]" + NEW_LINE + "}")), headersToIgnore) ); // - in https assertEquals( response() .withStatusCode(ACCEPTED_202.code()) .withReasonPhrase(ACCEPTED_202.reasonPhrase()) .withBody("some_body"), makeRequest( request() .withSecure(true) .withHeader(CONTENT_TYPE.toString(), MediaType.create("text", "plain").withCharset(StandardCharsets.UTF_16).toString()) .withPath(calculatePath("some_path")) .withMethod("POST") .withBody(json("{" + NEW_LINE + " \"ταυτότητα\": 1," + NEW_LINE + " \"επιπλέον αγνοούνται σειρά\": [\"ένας\", \"δυο\"]," + NEW_LINE + " \"όνομα\": \"μια πράσινη πόρτα\"," + NEW_LINE + " \"τιμή\": 12.50," + NEW_LINE + " \"ετικέτες\": [\"σπίτι\", \"πράσινος\"]" + NEW_LINE + "}")), headersToIgnore) ); } @Test public void shouldReturnResponseByMatchingBodyWithJsonWithMatchType() { // when mockServerClient .when( request() .withBody(json("{" + NEW_LINE + " \"id\": 1," + NEW_LINE + " \"name\": \"A green door\"," + NEW_LINE + " \"price\": 12.50," + NEW_LINE + " \"tags\": [\"home\", \"green\"]" + NEW_LINE + "}", MatchType.ONLY_MATCHING_FIELDS)), exactly(2) ) .respond( response() .withBody("some_body") ); // then // - in http assertEquals( response("some_body"), makeRequest( request() .withPath(calculatePath("some_path")) .withMethod("POST") .withBody("{" + NEW_LINE + " \"id\": 1," + NEW_LINE + " \"extra field\": \"some value\"," + NEW_LINE + " \"name\": \"A green door\"," + NEW_LINE + " \"price\": 12.50," + NEW_LINE + " \"tags\": [\"home\", \"green\"]" + NEW_LINE + "}"), headersToIgnore) ); // - in https assertEquals( response("some_body"), makeRequest( request() .withSecure(true) .withPath(calculatePath("some_path")) .withMethod("POST") .withBody("{" + NEW_LINE + " \"id\": 1," + NEW_LINE + " \"extra field\": \"some value\"," + NEW_LINE + " \"name\": \"A green door\"," + NEW_LINE + " \"price\": 12.50," + NEW_LINE + " \"tags\": [\"home\", \"green\"]" + NEW_LINE + "}"), headersToIgnore) ); } @Test public void shouldReturnResponseByMatchingBodyWithJsonSchema() { // when mockServerClient.when(request().withBody(jsonSchema("{" + NEW_LINE + " \"$schema\": \"http://json-schema.org/draft-04/schema#\"," + NEW_LINE + " \"title\": \"Product\"," + NEW_LINE + " \"description\": \"A product from Acme's catalog\"," + NEW_LINE + " \"type\": \"object\"," + NEW_LINE + " \"properties\": {" + NEW_LINE + " \"id\": {" + NEW_LINE + " \"description\": \"The unique identifier for a product\"," + NEW_LINE + " \"type\": \"integer\"" + NEW_LINE + " }," + NEW_LINE + " \"name\": {" + NEW_LINE + " \"description\": \"Name of the product\"," + NEW_LINE + " \"type\": \"string\"" + NEW_LINE + " }," + NEW_LINE + " \"price\": {" + NEW_LINE + " \"type\": \"number\"," + NEW_LINE + " \"minimum\": 0," + NEW_LINE + " \"exclusiveMinimum\": true" + NEW_LINE + " }," + NEW_LINE + " \"tags\": {" + NEW_LINE + " \"type\": \"array\"," + NEW_LINE + " \"items\": {" + NEW_LINE + " \"type\": \"string\"" + NEW_LINE + " }," + NEW_LINE + " \"minItems\": 1," + NEW_LINE + " \"uniqueItems\": true" + NEW_LINE + " }" + NEW_LINE + " }," + NEW_LINE + " \"required\": [\"id\", \"name\", \"price\"]" + NEW_LINE + "}")), exactly(2)).respond(response().withBody("some_body")); // then // - in http assertEquals( response() .withStatusCode(OK_200.code()) .withReasonPhrase(OK_200.reasonPhrase()) .withBody("some_body"), makeRequest( request() .withPath(calculatePath("some_path")) .withMethod("POST") .withBody("{" + NEW_LINE + " \"id\": 1," + NEW_LINE + " \"name\": \"A green door\"," + NEW_LINE + " \"price\": 12.50," + NEW_LINE + " \"tags\": [\"home\", \"green\"]" + NEW_LINE + "}"), headersToIgnore) ); // - in https assertEquals( response() .withStatusCode(OK_200.code()) .withReasonPhrase(OK_200.reasonPhrase()) .withBody("some_body"), makeRequest( request() .withSecure(true) .withPath(calculatePath("some_path")) .withMethod("POST") .withBody("{" + NEW_LINE + " \"id\": 1," + NEW_LINE + " \"name\": \"A green door\"," + NEW_LINE + " \"price\": 12.50," + NEW_LINE + " \"tags\": [\"home\", \"green\"]" + NEW_LINE + "}"), headersToIgnore) ); } @Test public void shouldReturnResponseByMatchingBodyWithJsonPath() { // when mockServerClient.when(request().withBody(jsonPath("$..book[?(@.price <= $['expensive'])]")), exactly(2)).respond(response().withBody("some_body")); // then // - in http assertEquals( response() .withStatusCode(OK_200.code()) .withReasonPhrase(OK_200.reasonPhrase()) .withBody("some_body"), makeRequest( request() .withPath(calculatePath("some_path")) .withMethod("POST") .withBody(new StringBody("" + "{" + NEW_LINE + " \"store\": {" + NEW_LINE + " \"book\": [" + NEW_LINE + " {" + NEW_LINE + " \"category\": \"reference\"," + NEW_LINE + " \"author\": \"Nigel Rees\"," + NEW_LINE + " \"title\": \"Sayings of the Century\"," + NEW_LINE + " \"price\": 8.95" + NEW_LINE + " }," + NEW_LINE + " {" + NEW_LINE + " \"category\": \"fiction\"," + NEW_LINE + " \"author\": \"Herman Melville\"," + NEW_LINE + " \"title\": \"Moby Dick\"," + NEW_LINE + " \"isbn\": \"0-553-21311-3\"," + NEW_LINE + " \"price\": 8.99" + NEW_LINE + " }" + NEW_LINE + " ]," + NEW_LINE + " \"bicycle\": {" + NEW_LINE + " \"color\": \"red\"," + NEW_LINE + " \"price\": 19.95" + NEW_LINE + " }" + NEW_LINE + " }," + NEW_LINE + " \"expensive\": 10" + NEW_LINE + "}")), headersToIgnore) ); // - in https assertEquals( response() .withStatusCode(OK_200.code()) .withReasonPhrase(OK_200.reasonPhrase()) .withBody("some_body"), makeRequest( request() .withSecure(true) .withPath(calculatePath("some_path")) .withMethod("POST") .withBody(new StringBody("" + "{" + NEW_LINE + " \"store\": {" + NEW_LINE + " \"book\": [" + NEW_LINE + " {" + NEW_LINE + " \"category\": \"reference\"," + NEW_LINE + " \"author\": \"Nigel Rees\"," + NEW_LINE + " \"title\": \"Sayings of the Century\"," + NEW_LINE + " \"price\": 8.95" + NEW_LINE + " }," + NEW_LINE + " {" + NEW_LINE + " \"category\": \"fiction\"," + NEW_LINE + " \"author\": \"Herman Melville\"," + NEW_LINE + " \"title\": \"Moby Dick\"," + NEW_LINE + " \"isbn\": \"0-553-21311-3\"," + NEW_LINE + " \"price\": 8.99" + NEW_LINE + " }" + NEW_LINE + " ]," + NEW_LINE + " \"bicycle\": {" + NEW_LINE + " \"color\": \"red\"," + NEW_LINE + " \"price\": 19.95" + NEW_LINE + " }" + NEW_LINE + " }," + NEW_LINE + " \"expensive\": 10" + NEW_LINE + "}")), headersToIgnore) ); } @Test public void shouldReturnPDFResponseByMatchingPath() throws IOException { // when byte[] pdfBytes = IOUtils.toByteArray(getClass().getClassLoader().getResourceAsStream("test.pdf")); mockServerClient .when( request() .withPath(calculatePath("ws/rest/user/[0-9]+/document/[0-9]+\\.pdf")) ) .respond( response() .withStatusCode(OK_200.code()) .withReasonPhrase(OK_200.reasonPhrase()) .withHeaders( header(CONTENT_TYPE.toString(), MediaType.PDF.toString()), header(CONTENT_DISPOSITION.toString(), "form-data; name=\"test.pdf\"; filename=\"test.pdf\""), header(CACHE_CONTROL.toString(), "must-revalidate, post-check=0, pre-check=0") ) .withBody(binary(pdfBytes)) ); // then // - in http assertEquals( response() .withStatusCode(OK_200.code()) .withReasonPhrase(OK_200.reasonPhrase()) .withHeaders( header(CONTENT_DISPOSITION.toString(), "form-data; name=\"test.pdf\"; filename=\"test.pdf\""), header(CACHE_CONTROL.toString(), "must-revalidate, post-check=0, pre-check=0"), header(CONTENT_TYPE.toString(), MediaType.PDF.toString()) ) .withBody(binary(pdfBytes)), makeRequest( request() .withPath(calculatePath("ws/rest/user/1/document/2.pdf")) .withMethod("GET"), headersToIgnore) ); // - in https assertEquals( response() .withStatusCode(OK_200.code()) .withReasonPhrase(OK_200.reasonPhrase()) .withHeaders( header(CONTENT_DISPOSITION.toString(), "form-data; name=\"test.pdf\"; filename=\"test.pdf\""), header(CACHE_CONTROL.toString(), "must-revalidate, post-check=0, pre-check=0"), header(CONTENT_TYPE.toString(), MediaType.PDF.toString()) ) .withBody(binary(pdfBytes)), makeRequest( request() .withSecure(true) .withPath(calculatePath("ws/rest/user/1/document/2.pdf")) .withMethod("GET"), headersToIgnore) ); } @Test public void shouldReturnPNGResponseByMatchingPath() throws IOException { // when byte[] pngBytes = IOUtils.toByteArray(getClass().getClassLoader().getResourceAsStream("test.png")); mockServerClient .when( request() .withPath(calculatePath("ws/rest/user/[0-9]+/icon/[0-9]+\\.png")) ) .respond( response() .withStatusCode(OK_200.code()) .withReasonPhrase(OK_200.reasonPhrase()) .withHeaders( header(CONTENT_TYPE.toString(), MediaType.PNG.toString()), header(CONTENT_DISPOSITION.toString(), "form-data; name=\"test.png\"; filename=\"test.png\"") ) .withBody(binary(pngBytes)) ); // then // - in http assertEquals( response() .withStatusCode(OK_200.code()) .withReasonPhrase(OK_200.reasonPhrase()) .withHeaders( header(CONTENT_DISPOSITION.toString(), "form-data; name=\"test.png\"; filename=\"test.png\""), header(CONTENT_TYPE.toString(), MediaType.PNG.toString()) ) .withBody(binary(pngBytes)), makeRequest( request() .withPath(calculatePath("ws/rest/user/1/icon/1.png")) .withMethod("GET"), headersToIgnore) ); // - in https assertEquals( response() .withStatusCode(OK_200.code()) .withReasonPhrase(OK_200.reasonPhrase()) .withHeaders( header(CONTENT_DISPOSITION.toString(), "form-data; name=\"test.png\"; filename=\"test.png\""), header(CONTENT_TYPE.toString(), MediaType.PNG.toString()) ) .withBody(binary(pngBytes)), makeRequest( request() .withSecure(true) .withPath(calculatePath("ws/rest/user/1/icon/1.png")) .withMethod("GET"), headersToIgnore) ); } @Test public void shouldReturnPDFResponseByMatchingBinaryPDFBody() throws IOException { // when byte[] pdfBytes = IOUtils.toByteArray(getClass().getClassLoader().getResourceAsStream("test.pdf")); mockServerClient .when( request() .withBody(binary(pdfBytes, MediaType.PDF)) ) .respond( response() .withStatusCode(OK_200.code()) .withReasonPhrase(OK_200.reasonPhrase()) .withHeaders( header(CONTENT_TYPE.toString(), MediaType.PDF.toString()), header(CONTENT_DISPOSITION.toString(), "form-data; name=\"test.pdf\"; filename=\"test.pdf\""), header(CACHE_CONTROL.toString(), "must-revalidate, post-check=0, pre-check=0") ) .withBody(binary(pdfBytes)) ); // then // - in http assertEquals( response() .withStatusCode(OK_200.code()) .withReasonPhrase(OK_200.reasonPhrase()) .withHeaders( header(CONTENT_DISPOSITION.toString(), "form-data; name=\"test.pdf\"; filename=\"test.pdf\""), header(CACHE_CONTROL.toString(), "must-revalidate, post-check=0, pre-check=0"), header(CONTENT_TYPE.toString(), MediaType.PDF.toString()) ) .withBody(binary(pdfBytes)), makeRequest( request() .withPath(calculatePath("ws/rest/user/1/document/2.pdf")) .withBody(binary(pdfBytes, MediaType.PDF)) .withMethod("POST"), headersToIgnore) ); // - in https assertEquals( response() .withStatusCode(OK_200.code()) .withReasonPhrase(OK_200.reasonPhrase()) .withHeaders( header(CONTENT_DISPOSITION.toString(), "form-data; name=\"test.pdf\"; filename=\"test.pdf\""), header(CACHE_CONTROL.toString(), "must-revalidate, post-check=0, pre-check=0"), header(CONTENT_TYPE.toString(), MediaType.PDF.toString()) ) .withBody(binary(pdfBytes)), makeRequest( request() .withSecure(true) .withPath(calculatePath("ws/rest/user/1/document/2.pdf")) .withBody(binary(pdfBytes, MediaType.PDF)) .withMethod("POST"), headersToIgnore) ); } @Test public void shouldReturnPNGResponseByMatchingBinaryPNGBody() throws IOException { // when byte[] pngBytes = IOUtils.toByteArray(getClass().getClassLoader().getResourceAsStream("test.png")); mockServerClient .when( request() .withBody(binary(pngBytes, MediaType.ANY_IMAGE_TYPE)) ) .respond( response() .withStatusCode(OK_200.code()) .withReasonPhrase(OK_200.reasonPhrase()) .withHeaders( header(CONTENT_TYPE.toString(), MediaType.PNG.toString()), header(CONTENT_DISPOSITION.toString(), "form-data; name=\"test.png\"; filename=\"test.png\"") ) .withBody(binary(pngBytes)) ); // then // - in http assertEquals( response() .withStatusCode(OK_200.code()) .withReasonPhrase(OK_200.reasonPhrase()) .withHeaders( header(CONTENT_DISPOSITION.toString(), "form-data; name=\"test.png\"; filename=\"test.png\""), header(CONTENT_TYPE.toString(), MediaType.PNG.toString()) ) .withBody(binary(pngBytes)), makeRequest( request() .withPath(calculatePath("ws/rest/user/1/icon/1.png")) .withBody(binary(pngBytes, MediaType.ANY_IMAGE_TYPE)) .withMethod("POST"), headersToIgnore) ); // - in https assertEquals( response() .withStatusCode(OK_200.code()) .withReasonPhrase(OK_200.reasonPhrase()) .withHeaders( header(CONTENT_DISPOSITION.toString(), "form-data; name=\"test.png\"; filename=\"test.png\""), header(CONTENT_TYPE.toString(), MediaType.PNG.toString()) ) .withBody(binary(pngBytes)), makeRequest( request() .withSecure(true) .withPath(calculatePath("ws/rest/user/1/icon/1.png")) .withBody(binary(pngBytes, MediaType.ANY_IMAGE_TYPE)) .withMethod("POST"), headersToIgnore) ); } @Test public void shouldReturnResponseByNotMatchingPathWithNotOperator() { // when mockServerClient .when( request() .withPath(not(calculatePath("some_path"))) ) .respond( response() .withStatusCode(ACCEPTED_202.code()) .withReasonPhrase(ACCEPTED_202.reasonPhrase()) .withBody("some_body_response") ); // then // - in http assertEquals( response() .withStatusCode(ACCEPTED_202.code()) .withReasonPhrase(ACCEPTED_202.reasonPhrase()) .withBody("some_body_response"), makeRequest( request() .withPath(calculatePath("some_other_path")), headersToIgnore) ); // - in https assertEquals( response() .withStatusCode(ACCEPTED_202.code()) .withReasonPhrase(ACCEPTED_202.reasonPhrase()) .withBody("some_body_response"), makeRequest( request() .withPath(calculatePath("some_other_path")), headersToIgnore) ); } @Test public void shouldReturnResponseByNotMatchingMethodWithNotOperator() { // when mockServerClient .when( request() .withMethod(not("GET")) ) .respond( response() .withStatusCode(ACCEPTED_202.code()) .withReasonPhrase(ACCEPTED_202.reasonPhrase()) .withBody("some_body_response") ); // then // - in http assertEquals( response() .withStatusCode(ACCEPTED_202.code()) .withReasonPhrase(ACCEPTED_202.reasonPhrase()) .withBody("some_body_response"), makeRequest( request() .withMethod("POST"), headersToIgnore) ); // - in https assertEquals( response() .withStatusCode(ACCEPTED_202.code()) .withReasonPhrase(ACCEPTED_202.reasonPhrase()) .withBody("some_body_response"), makeRequest( request() .withMethod("POST"), headersToIgnore) ); } @Test public void shouldReturnResponseByMatchingPathAndMethodAndBody() { // when mockServerClient .when( request() .withMethod("POST") .withPath(calculatePath("some_pathRequest")) .withBody("some_bodyRequest") ) .respond( response() .withStatusCode(ACCEPTED_202.code()) .withReasonPhrase(ACCEPTED_202.reasonPhrase()) .withBody("some_body_response") .withHeaders(header("headerNameResponse", "headerValueResponse")) ); // then // - in http assertEquals( response() .withStatusCode(ACCEPTED_202.code()) .withReasonPhrase(ACCEPTED_202.reasonPhrase()) .withBody("some_body_response") .withHeaders( header("headerNameResponse", "headerValueResponse") ), makeRequest( request() .withMethod("POST") .withPath(calculatePath("some_pathRequest")) .withQueryStringParameters( param("queryStringParameterOneName", "queryStringParameterOneValue"), param("queryStringParameterTwoName", "queryStringParameterTwoValue") ) .withBody("some_bodyRequest") .withHeaders(header("headerNameRequest", "headerValueRequest")) .withCookies(cookie("cookieNameRequest", "cookieValueRequest")), headersToIgnore) ); // - in https assertEquals( response() .withStatusCode(ACCEPTED_202.code()) .withReasonPhrase(ACCEPTED_202.reasonPhrase()) .withBody("some_body_response") .withHeaders( header("headerNameResponse", "headerValueResponse") ), makeRequest( request() .withMethod("POST") .withSecure(true) .withPath(calculatePath("some_pathRequest")) .withQueryStringParameters( param("queryStringParameterOneName", "queryStringParameterOneValue"), param("queryStringParameterTwoName", "queryStringParameterTwoValue") ) .withBody("some_bodyRequest") .withHeaders(header("headerNameRequest", "headerValueRequest")) .withCookies(cookie("cookieNameRequest", "cookieValueRequest")), headersToIgnore) ); } @Test public void shouldReturnResponseByMatchingPathAndMethodAndQueryStringParameters() { // when mockServerClient .when( request() .withMethod("GET") .withPath(calculatePath("some_pathRequest")) .withQueryStringParameters( param("queryStringParameterOneName", "queryStringParameterOneValue"), param("queryStringParameterTwoName", "queryStringParameterTwoValue") ) ) .respond( response() .withStatusCode(ACCEPTED_202.code()) .withReasonPhrase(ACCEPTED_202.reasonPhrase()) .withBody("some_body_response") .withCookies(cookie("cookieNameResponse", "cookieValueResponse")) ); // then // - in http assertEquals( response() .withStatusCode(ACCEPTED_202.code()) .withReasonPhrase(ACCEPTED_202.reasonPhrase()) .withBody("some_body_response") .withCookies(cookie("cookieNameResponse", "cookieValueResponse")) .withHeaders( header(SET_COOKIE.toString(), "cookieNameResponse=cookieValueResponse") ), makeRequest( request() .withMethod("GET") .withPath(calculatePath("some_pathRequest")) .withQueryStringParameters( param("queryStringParameterOneName", "queryStringParameterOneValue"), param("queryStringParameterTwoName", "queryStringParameterTwoValue") ) .withHeaders(header("headerNameRequest", "headerValueRequest")) .withCookies(cookie("cookieNameRequest", "cookieValueRequest")), headersToIgnore) ); // - in https assertEquals( response() .withStatusCode(ACCEPTED_202.code()) .withReasonPhrase(ACCEPTED_202.reasonPhrase()) .withBody("some_body_response") .withCookies(cookie("cookieNameResponse", "cookieValueResponse")) .withHeaders( header(SET_COOKIE.toString(), "cookieNameResponse=cookieValueResponse") ), makeRequest( request() .withMethod("GET") .withSecure(true) .withPath(calculatePath("some_pathRequest")) .withQueryStringParameters( param("queryStringParameterOneName", "queryStringParameterOneValue"), param("queryStringParameterTwoName", "queryStringParameterTwoValue") ) .withHeaders(header("headerNameRequest", "headerValueRequest")) .withCookies(cookie("cookieNameRequest", "cookieValueRequest")), headersToIgnore) ); } @Test public void shouldReturnResponseByMatchingPathAndMethodAndHeaders() { // when mockServerClient .when( request() .withMethod("GET") .withPath(calculatePath("some_pathRequest")) .withHeaders( header("requestHeaderNameOne", "requestHeaderValueOne_One", "requestHeaderValueOne_Two"), header("requestHeaderNameTwo", "requestHeaderValueTwo") ) ) .respond( response() .withStatusCode(ACCEPTED_202.code()) .withReasonPhrase(ACCEPTED_202.reasonPhrase()) .withBody("some_body_response") .withCookies(cookie("cookieNameResponse", "cookieValueResponse")) ); // then // - in http assertEquals( response() .withStatusCode(ACCEPTED_202.code()) .withReasonPhrase(ACCEPTED_202.reasonPhrase()) .withBody("some_body_response") .withCookies(cookie("cookieNameResponse", "cookieValueResponse")) .withHeaders( header(SET_COOKIE.toString(), "cookieNameResponse=cookieValueResponse") ), makeRequest( request() .withMethod("GET") .withPath(calculatePath("some_pathRequest")) .withHeaders( header("requestHeaderNameOne", "requestHeaderValueOne_One", "requestHeaderValueOne_Two"), header("requestHeaderNameTwo", "requestHeaderValueTwo") ) .withCookies(cookie("cookieNameRequest", "cookieValueRequest")), headersToIgnore) ); // - in https assertEquals( response() .withStatusCode(ACCEPTED_202.code()) .withReasonPhrase(ACCEPTED_202.reasonPhrase()) .withBody("some_body_response") .withCookies(cookie("cookieNameResponse", "cookieValueResponse")) .withHeaders( header(SET_COOKIE.toString(), "cookieNameResponse=cookieValueResponse") ), makeRequest( request() .withMethod("GET") .withSecure(true) .withPath(calculatePath("some_pathRequest")) .withHeaders( header("requestHeaderNameOne", "requestHeaderValueOne_One", "requestHeaderValueOne_Two"), header("requestHeaderNameTwo", "requestHeaderValueTwo") ) .withCookies(cookie("cookieNameRequest", "cookieValueRequest")), headersToIgnore) ); } @Test public void shouldReturnResponseByMatchingPathAndMethodAndCookies() { // when mockServerClient .when( request() .withMethod("GET") .withPath(calculatePath("some_pathRequest")) .withCookies( cookie("requestCookieNameOne", "requestCookieValueOne"), cookie("requestCookieNameTwo", "requestCookieValueTwo") ) ) .respond( response() .withStatusCode(ACCEPTED_202.code()) .withReasonPhrase(ACCEPTED_202.reasonPhrase()) .withBody("some_body_response") .withCookies( cookie("responseCookieNameOne", "responseCookieValueOne"), cookie("responseCookieNameTwo", "responseCookieValueTwo") ) ); // then // - in http - cookie objects assertEquals( response() .withStatusCode(ACCEPTED_202.code()) .withReasonPhrase(ACCEPTED_202.reasonPhrase()) .withBody("some_body_response") .withCookies( cookie("responseCookieNameOne", "responseCookieValueOne"), cookie("responseCookieNameTwo", "responseCookieValueTwo") ) .withHeaders( header(SET_COOKIE.toString(), "responseCookieNameOne=responseCookieValueOne", "responseCookieNameTwo=responseCookieValueTwo") ), makeRequest( request() .withMethod("GET") .withPath(calculatePath("some_pathRequest")) .withHeaders( header("headerNameRequest", "headerValueRequest"), header(CONTENT_TYPE.toString(), MediaType.create("text", "plain").toString()) ) .withCookies( cookie("requestCookieNameOne", "requestCookieValueOne"), cookie("requestCookieNameTwo", "requestCookieValueTwo") ), headersToIgnore) ); // - in http - cookie header assertEquals( response() .withStatusCode(ACCEPTED_202.code()) .withReasonPhrase(ACCEPTED_202.reasonPhrase()) .withBody("some_body_response") .withCookies( cookie("responseCookieNameOne", "responseCookieValueOne"), cookie("responseCookieNameTwo", "responseCookieValueTwo") ) .withHeaders( header(SET_COOKIE.toString(), "responseCookieNameOne=responseCookieValueOne", "responseCookieNameTwo=responseCookieValueTwo") ), makeRequest( request() .withMethod("GET") .withPath(calculatePath("some_pathRequest")) .withHeaders( header("headerNameRequest", "headerValueRequest"), header("Cookie", "requestCookieNameOne=requestCookieValueOne; requestCookieNameTwo=requestCookieValueTwo") ), headersToIgnore) ); // - in https - cookie objects assertEquals( response() .withStatusCode(ACCEPTED_202.code()) .withReasonPhrase(ACCEPTED_202.reasonPhrase()) .withBody("some_body_response") .withCookies( cookie("responseCookieNameOne", "responseCookieValueOne"), cookie("responseCookieNameTwo", "responseCookieValueTwo") ) .withHeaders( header(SET_COOKIE.toString(), "responseCookieNameOne=responseCookieValueOne", "responseCookieNameTwo=responseCookieValueTwo") ), makeRequest( request() .withMethod("GET") .withSecure(true) .withPath(calculatePath("some_pathRequest")) .withHeaders( header("headerNameRequest", "headerValueRequest") ) .withCookies( cookie("requestCookieNameOne", "requestCookieValueOne"), cookie("requestCookieNameTwo", "requestCookieValueTwo") ), headersToIgnore) ); // - in https - cookie header assertEquals( response() .withStatusCode(ACCEPTED_202.code()) .withReasonPhrase(ACCEPTED_202.reasonPhrase()) .withBody("some_body_response") .withCookies( cookie("responseCookieNameOne", "responseCookieValueOne"), cookie("responseCookieNameTwo", "responseCookieValueTwo") ) .withHeaders( header(SET_COOKIE.toString(), "responseCookieNameOne=responseCookieValueOne", "responseCookieNameTwo=responseCookieValueTwo") ), makeRequest( request() .withMethod("GET") .withSecure(true) .withPath(calculatePath("some_pathRequest")) .withHeaders( header("headerNameRequest", "headerValueRequest"), header("Cookie", "requestCookieNameOne=requestCookieValueOne; requestCookieNameTwo=requestCookieValueTwo") ), headersToIgnore) ); } @Test public void shouldReturnResponseByMatchingPathAndMethodAndQueryStringParametersAndBodyParameters() { // when mockServerClient .when( request() .withMethod("POST") .withPath(calculatePath("some_pathRequest")) .withQueryStringParameters( param("queryStringParameterOneName", "queryStringParameterOneValueOne", "queryStringParameterOneValueTwo"), param("queryStringParameterTwoName", "queryStringParameterTwoValue") ) .withBody(params(param("bodyParameterName", "bodyParameterValue"))) ) .respond( response() .withStatusCode(ACCEPTED_202.code()) .withReasonPhrase(ACCEPTED_202.reasonPhrase()) .withBody("some_body") ); // then // - in http - url query string assertEquals( response() .withStatusCode(ACCEPTED_202.code()) .withReasonPhrase(ACCEPTED_202.reasonPhrase()) .withBody("some_body"), makeRequest( request() .withMethod("POST") .withPath(calculatePath("some_pathRequest")) .withQueryStringParameters( param("queryStringParameterOneName", "queryStringParameterOneValueOne", "queryStringParameterOneValueTwo"), param("queryStringParameterTwoName", "queryStringParameterTwoValue") ) .withBody(params(param("bodyParameterName", "bodyParameterValue"))), headersToIgnore) ); // - in https - query string parameter objects assertEquals( response() .withStatusCode(ACCEPTED_202.code()) .withReasonPhrase(ACCEPTED_202.reasonPhrase()) .withBody("some_body"), makeRequest( request() .withSecure(true) .withMethod("POST") .withPath(calculatePath("some_pathRequest")) .withQueryStringParameters( param("queryStringParameterOneName", "queryStringParameterOneValueOne", "queryStringParameterOneValueTwo"), param("queryStringParameterTwoName", "queryStringParameterTwoValue") ) .withBody(params(param("bodyParameterName", "bodyParameterValue"))), headersToIgnore) ); } @Test public void shouldReturnResponseByMatchingPathAndMethodAndQueryStringParametersAndBody() { // when mockServerClient .when( request() .withMethod("POST") .withPath(calculatePath("some_pathRequest")) .withQueryStringParameters( param("queryStringParameterOneName", "queryStringParameterOneValueOne", "queryStringParameterOneValueTwo"), param("queryStringParameterTwoName", "queryStringParameterTwoValue") ) .withBody("some_bodyRequest") ) .respond( response() .withStatusCode(ACCEPTED_202.code()) .withReasonPhrase(ACCEPTED_202.reasonPhrase()) .withBody("some_body_response") .withHeaders(header("headerNameResponse", "headerValueResponse")) .withCookies(cookie("cookieNameResponse", "cookieValueResponse")) ); // then // - in http - url query string assertEquals( response() .withStatusCode(ACCEPTED_202.code()) .withReasonPhrase(ACCEPTED_202.reasonPhrase()) .withBody("some_body_response") .withCookies(cookie("cookieNameResponse", "cookieValueResponse")) .withHeaders( header("headerNameResponse", "headerValueResponse"), header(SET_COOKIE.toString(), "cookieNameResponse=cookieValueResponse") ), makeRequest( request() .withMethod("POST") .withPath(calculatePath("some_pathRequest")) .withQueryStringParameters( param("queryStringParameterOneName", "queryStringParameterOneValueOne", "queryStringParameterOneValueTwo"), param("queryStringParameterTwoName", "queryStringParameterTwoValue") ) .withBody("some_bodyRequest") .withHeaders(header("headerNameRequest", "headerValueRequest")) .withCookies(cookie("cookieNameRequest", "cookieValueRequest")), headersToIgnore) ); // - in http - query string parameter objects assertEquals( response() .withStatusCode(ACCEPTED_202.code()) .withReasonPhrase(ACCEPTED_202.reasonPhrase()) .withBody("some_body_response") .withCookies(cookie("cookieNameResponse", "cookieValueResponse")) .withHeaders( header("headerNameResponse", "headerValueResponse"), header(SET_COOKIE.toString(), "cookieNameResponse=cookieValueResponse") ), makeRequest( request() .withMethod("POST") .withPath(calculatePath("some_pathRequest")) .withQueryStringParameters( param("queryStringParameterOneName", "queryStringParameterOneValueOne", "queryStringParameterOneValueTwo"), param("queryStringParameterTwoName", "queryStringParameterTwoValue") ) .withBody("some_bodyRequest") .withHeaders(header("headerNameRequest", "headerValueRequest")) .withCookies(cookie("cookieNameRequest", "cookieValueRequest")), headersToIgnore) ); // - in https - url string and query string parameter objects assertEquals( response() .withStatusCode(ACCEPTED_202.code()) .withReasonPhrase(ACCEPTED_202.reasonPhrase()) .withBody("some_body_response") .withCookies(cookie("cookieNameResponse", "cookieValueResponse")) .withHeaders( header("headerNameResponse", "headerValueResponse"), header(SET_COOKIE.toString(), "cookieNameResponse=cookieValueResponse") ), makeRequest( request() .withMethod("POST") .withPath(calculatePath("some_pathRequest")) .withQueryStringParameters( param("queryStringParameterOneName", "queryStringParameterOneValueOne", "queryStringParameterOneValueTwo"), param("queryStringParameterTwoName", "queryStringParameterTwoValue") ) .withBody("some_bodyRequest") .withHeaders(header("headerNameRequest", "headerValueRequest")) .withCookies(cookie("cookieNameRequest", "cookieValueRequest")), headersToIgnore) ); } @Test public void shouldReturnResponseByMatchingPathAndMethodAndBodyParameters() { // when mockServerClient .when( request() .withMethod("POST") .withPath(calculatePath("some_pathRequest")) .withBody(params( param("bodyParameterOneName", "Parameter One Value One", "Parameter One Value Two"), param("bodyParameterTwoName", "Parameter Two") )) ) .respond( response() .withStatusCode(ACCEPTED_202.code()) .withReasonPhrase(ACCEPTED_202.reasonPhrase()) .withBody("some_body_response") .withHeaders(header("headerNameResponse", "headerValueResponse")) .withCookies(cookie("cookieNameResponse", "cookieValueResponse")) ); // then // - in http - body string assertEquals( response() .withStatusCode(ACCEPTED_202.code()) .withReasonPhrase(ACCEPTED_202.reasonPhrase()) .withBody("some_body_response") .withCookies(cookie("cookieNameResponse", "cookieValueResponse")) .withHeaders( header("headerNameResponse", "headerValueResponse"), header(SET_COOKIE.toString(), "cookieNameResponse=cookieValueResponse") ), makeRequest( request() .withMethod("POST") .withPath(calculatePath("some_pathRequest")) .withBody(new StringBody("bodyParameterOneName=Parameter+One+Value+One" + "&bodyParameterOneName=Parameter+One+Value+Two" + "&bodyParameterTwoName=Parameter+Two")) .withHeaders(header("headerNameRequest", "headerValueRequest")) .withCookies(cookie("cookieNameRequest", "cookieValueRequest")), headersToIgnore) ); // - in http - body parameter objects assertEquals( response() .withStatusCode(ACCEPTED_202.code()) .withReasonPhrase(ACCEPTED_202.reasonPhrase()) .withBody("some_body_response") .withCookies(cookie("cookieNameResponse", "cookieValueResponse")) .withHeaders( header("headerNameResponse", "headerValueResponse"), header(SET_COOKIE.toString(), "cookieNameResponse=cookieValueResponse") ), makeRequest( request() .withMethod("POST") .withPath(calculatePath("some_pathRequest")) .withBody(params( param("bodyParameterOneName", "Parameter One Value One", "Parameter One Value Two"), param("bodyParameterTwoName", "Parameter Two") )) .withHeaders(header("headerNameRequest", "headerValueRequest")) .withCookies(cookie("cookieNameRequest", "cookieValueRequest")), headersToIgnore) ); // - in https - url string and query string parameter objects assertEquals( response() .withStatusCode(ACCEPTED_202.code()) .withReasonPhrase(ACCEPTED_202.reasonPhrase()) .withBody("some_body_response") .withCookies(cookie("cookieNameResponse", "cookieValueResponse")) .withHeaders( header("headerNameResponse", "headerValueResponse"), header(SET_COOKIE.toString(), "cookieNameResponse=cookieValueResponse") ), makeRequest( request() .withMethod("POST") .withPath(calculatePath("some_pathRequest")) .withBody(params( param("bodyParameterOneName", "Parameter One Value One", "Parameter One Value Two"), param("bodyParameterTwoName", "Parameter Two") )) .withHeaders(header("headerNameRequest", "headerValueRequest")) .withCookies(cookie("cookieNameRequest", "cookieValueRequest")), headersToIgnore) ); } @Test public void shouldReturnResponseByMatchingPathAndMethodAndParametersAndHeadersAndCookies() { // when mockServerClient .when( request() .withMethod("PUT") .withPath(calculatePath("some_pathRequest")) .withBody(new StringBody("bodyParameterOneName=Parameter+One+Value+One" + "&bodyParameterOneName=Parameter+One+Value+Two" + "&bodyParameterTwoName=Parameter+Two")) .withHeaders(header("headerNameRequest", "headerValueRequest")) .withCookies(cookie("cookieNameRequest", "cookieValueRequest")) ) .respond( response() .withStatusCode(ACCEPTED_202.code()) .withReasonPhrase(ACCEPTED_202.reasonPhrase()) .withBody("some_body_response") .withHeaders(header("headerNameResponse", "headerValueResponse")) .withCookies(cookie("cookieNameResponse", "cookieValueResponse")) ); // then // - in http - body string assertEquals( response() .withStatusCode(ACCEPTED_202.code()) .withReasonPhrase(ACCEPTED_202.reasonPhrase()) .withBody("some_body_response") .withCookies(cookie("cookieNameResponse", "cookieValueResponse")) .withHeaders( header("headerNameResponse", "headerValueResponse"), header(SET_COOKIE.toString(), "cookieNameResponse=cookieValueResponse") ), makeRequest( request() .withMethod("PUT") .withPath(calculatePath("some_pathRequest")) .withBody(new StringBody("bodyParameterOneName=Parameter+One+Value+One" + "&bodyParameterOneName=Parameter+One+Value+Two" + "&bodyParameterTwoName=Parameter+Two")) .withHeaders( header("headerNameRequest", "headerValueRequest"), header("Cookie", "cookieNameRequest=cookieValueRequest") ), headersToIgnore) ); // - in http - body parameter objects assertEquals( response() .withStatusCode(ACCEPTED_202.code()) .withReasonPhrase(ACCEPTED_202.reasonPhrase()) .withBody("some_body_response") .withCookies(cookie("cookieNameResponse", "cookieValueResponse")) .withHeaders( header("headerNameResponse", "headerValueResponse"), header(SET_COOKIE.toString(), "cookieNameResponse=cookieValueResponse") ), makeRequest( request() .withMethod("PUT") .withPath(calculatePath("some_pathRequest")) .withBody(params( param("bodyParameterOneName", "Parameter One Value One", "Parameter One Value Two"), param("bodyParameterTwoName", "Parameter Two") )) .withHeaders(header("headerNameRequest", "headerValueRequest")) .withCookies(cookie("cookieNameRequest", "cookieValueRequest")), headersToIgnore) ); } @Test public void shouldReturnResponseByNotMatchingBodyParameterWithNotOperatorForNameAndValue() { // when mockServerClient .when( request() .withMethod("POST") .withPath(calculatePath("some_pathRequest")) .withBody(params( param(not("bodyParameterOneName"), not("Parameter One Value One"), not("Parameter One Value Two")), param("bodyParameterTwoName", "Parameter Two") )) ) .respond( response() .withStatusCode(ACCEPTED_202.code()) .withReasonPhrase(ACCEPTED_202.reasonPhrase()) .withBody("some_body_response") ); // then // wrong query string parameter name assertEquals( response() .withStatusCode(ACCEPTED_202.code()) .withReasonPhrase(ACCEPTED_202.reasonPhrase()) .withBody("some_body_response"), makeRequest( request() .withMethod("POST") .withPath(calculatePath("some_pathRequest")) .withBody(params( param("OTHERBodyParameterOneName", "Parameter One Value One", "Parameter One Value Two"), param("bodyParameterTwoName", "Parameter Two") )) .withHeaders(header("headerNameRequest", "headerValueRequest")) .withCookies(cookie("cookieNameRequest", "cookieValueRequest")), headersToIgnore) ); // wrong query string parameter name assertEquals( response() .withStatusCode(ACCEPTED_202.code()) .withReasonPhrase(ACCEPTED_202.reasonPhrase()) .withBody("some_body_response"), makeRequest( request() .withMethod("POST") .withPath(calculatePath("some_pathRequest")) .withBody(new StringBody("OTHERBodyParameterOneName=Parameter+One+Value+One" + "&OTHERBodyParameterOneName=Parameter+One+Value+Two" + "&bodyParameterTwoName=Parameter+Two")) .withHeaders(header("headerNameRequest", "headerValueRequest")) .withCookies(cookie("cookieNameRequest", "cookieValueRequest")), headersToIgnore) ); // wrong query string parameter value assertEquals( response() .withStatusCode(ACCEPTED_202.code()) .withReasonPhrase(ACCEPTED_202.reasonPhrase()) .withBody("some_body_response"), makeRequest( request() .withMethod("POST") .withPath(calculatePath("some_pathRequest")) .withBody(params( param("bodyParameterOneName", "OTHER Parameter One Value One", "OTHER Parameter One Value Two"), param("bodyParameterTwoName", "Parameter Two") )) .withHeaders(header("headerNameRequest", "headerValueRequest")) .withCookies(cookie("cookieNameRequest", "cookieValueRequest")), headersToIgnore) ); // wrong query string parameter value assertEquals( response() .withStatusCode(ACCEPTED_202.code()) .withReasonPhrase(ACCEPTED_202.reasonPhrase()) .withBody("some_body_response"), makeRequest( request() .withMethod("POST") .withPath(calculatePath("some_pathRequest")) .withBody(new StringBody("bodyParameterOneName=OTHER Parameter+One+Value+One" + "&bodyParameterOneName=OTHER Parameter+One+Value+Two" + "&bodyParameterTwoName=Parameter+Two")) .withHeaders(header("headerNameRequest", "headerValueRequest")) .withCookies(cookie("cookieNameRequest", "cookieValueRequest")), headersToIgnore) ); } @Test public void shouldReturnResponseByNotMatchingBodyParameterWithNotOperatorForName() { // when mockServerClient .when( request() .withMethod("POST") .withPath(calculatePath("some_pathRequest")) .withBody(params( param(not("bodyParameterOneName"), string("Parameter One Value One"), string("Parameter One Value Two")), param("bodyParameterTwoName", "Parameter Two") )) ) .respond( response() .withStatusCode(ACCEPTED_202.code()) .withReasonPhrase(ACCEPTED_202.reasonPhrase()) .withBody("some_body_response") ); // then // wrong query string parameter name assertEquals( response() .withStatusCode(ACCEPTED_202.code()) .withReasonPhrase(ACCEPTED_202.reasonPhrase()) .withBody("some_body_response"), makeRequest( request() .withMethod("POST") .withPath(calculatePath("some_pathRequest")) .withBody(params( param("OTHERBodyParameterOneName", "Parameter One Value One", "Parameter One Value Two"), param("bodyParameterTwoName", "Parameter Two") )) .withHeaders(header("headerNameRequest", "headerValueRequest")) .withCookies(cookie("cookieNameRequest", "cookieValueRequest")), headersToIgnore) ); // wrong query string parameter name assertEquals( response() .withStatusCode(ACCEPTED_202.code()) .withReasonPhrase(ACCEPTED_202.reasonPhrase()) .withBody("some_body_response"), makeRequest( request() .withMethod("POST") .withPath(calculatePath("some_pathRequest")) .withBody(new StringBody("OTHERBodyParameterOneName=Parameter+One+Value+One" + "&OTHERBodyParameterOneName=Parameter+One+Value+Two" + "&bodyParameterTwoName=Parameter+Two")) .withHeaders(header("headerNameRequest", "headerValueRequest")) .withCookies(cookie("cookieNameRequest", "cookieValueRequest")), headersToIgnore) ); } @Test public void shouldReturnResponseByNotMatchingBodyParameterWithNotOperatorForValue() { // when mockServerClient .when( request() .withMethod("POST") .withPath(calculatePath("some_pathRequest")) .withBody(params( param(string("bodyParameterOneName"), not("Parameter One Value One"), not("Parameter One Value Two")), param("bodyParameterTwoName", "Parameter Two") )) ) .respond( response() .withStatusCode(ACCEPTED_202.code()) .withReasonPhrase(ACCEPTED_202.reasonPhrase()) .withBody("some_body_response") ); // then // wrong query string parameter value assertEquals( response() .withStatusCode(ACCEPTED_202.code()) .withReasonPhrase(ACCEPTED_202.reasonPhrase()) .withBody("some_body_response"), makeRequest( request() .withMethod("POST") .withPath(calculatePath("some_pathRequest")) .withBody(params( param("bodyParameterOneName", "OTHER Parameter One Value One", "OTHER Parameter One Value Two"), param("bodyParameterTwoName", "Parameter Two") )) .withHeaders(header("headerNameRequest", "headerValueRequest")) .withCookies(cookie("cookieNameRequest", "cookieValueRequest")), headersToIgnore) ); // wrong query string parameter value assertEquals( response() .withStatusCode(ACCEPTED_202.code()) .withReasonPhrase(ACCEPTED_202.reasonPhrase()) .withBody("some_body_response"), makeRequest( request() .withMethod("POST") .withPath(calculatePath("some_pathRequest")) .withBody(new StringBody("bodyParameterOneName=OTHER Parameter+One+Value+One" + "&bodyParameterOneName=OTHER Parameter+One+Value+Two" + "&bodyParameterTwoName=Parameter+Two")) .withHeaders(header("headerNameRequest", "headerValueRequest")) .withCookies(cookie("cookieNameRequest", "cookieValueRequest")), headersToIgnore) ); } @Test public void shouldReturnResponseByNotMatchingQueryStringParameterWithNotOperatorForNameAndValue() { // when mockServerClient .when( request() .withMethod("POST") .withPath(calculatePath("some_pathRequest")) .withQueryStringParameters( param(not("queryStringParameterOneName"), not("Parameter One Value One"), not("Parameter One Value Two")), param("queryStringParameterTwoName", "Parameter Two") ) ) .respond( response() .withStatusCode(ACCEPTED_202.code()) .withReasonPhrase(ACCEPTED_202.reasonPhrase()) .withBody("some_body_response") ); // then // wrong query string parameter name assertEquals( response() .withStatusCode(ACCEPTED_202.code()) .withReasonPhrase(ACCEPTED_202.reasonPhrase()) .withBody("some_body_response"), makeRequest( request() .withMethod("POST") .withPath(calculatePath("some_pathRequest")) .withQueryStringParameters( param("OTHERQueryStringParameterOneName", "Parameter One Value One", "Parameter One Value Two"), param("queryStringParameterTwoName", "Parameter Two") ), headersToIgnore) ); // wrong query string parameter value assertEquals( response() .withStatusCode(ACCEPTED_202.code()) .withReasonPhrase(ACCEPTED_202.reasonPhrase()) .withBody("some_body_response"), makeRequest( request() .withMethod("POST") .withPath(calculatePath("some_pathRequest")) .withQueryStringParameters( param("queryStringParameterOneName", "OTHER Parameter One Value One", "OTHER Parameter One Value Two"), param("queryStringParameterTwoName", "Parameter Two") ), headersToIgnore) ); } @Test public void shouldReturnResponseByNotMatchingQueryStringParameterWithNotOperatorForName() { // when mockServerClient .when( request() .withMethod("POST") .withPath(calculatePath("some_pathRequest")) .withQueryStringParameters( param(not("queryStringParameterOneName"), string("Parameter One Value One"), string("Parameter One Value Two")), param("queryStringParameterTwoName", "Parameter Two") ) ) .respond( response() .withStatusCode(ACCEPTED_202.code()) .withReasonPhrase(ACCEPTED_202.reasonPhrase()) .withBody("some_body_response") ); // then // wrong query string parameter name assertEquals( response() .withStatusCode(ACCEPTED_202.code()) .withReasonPhrase(ACCEPTED_202.reasonPhrase()) .withBody("some_body_response"), makeRequest( request() .withMethod("POST") .withPath(calculatePath("some_pathRequest")) .withQueryStringParameters( param("OTHERQueryStringParameterOneName", "Parameter One Value One", "Parameter One Value Two"), param("queryStringParameterTwoName", "Parameter Two") ), headersToIgnore) ); } @Test public void shouldReturnResponseByNotMatchingQueryStringParameterWithNotOperatorForValue() { // when mockServerClient .when( request() .withMethod("POST") .withPath(calculatePath("some_pathRequest")) .withQueryStringParameters( param(string("queryStringParameterOneName"), not("Parameter One Value One"), not("Parameter One Value Two")), param("queryStringParameterTwoName", "Parameter Two") ) ) .respond( response() .withStatusCode(ACCEPTED_202.code()) .withReasonPhrase(ACCEPTED_202.reasonPhrase()) .withBody("some_body_response") ); // then // wrong query string parameter value assertEquals( response() .withStatusCode(ACCEPTED_202.code()) .withReasonPhrase(ACCEPTED_202.reasonPhrase()) .withBody("some_body_response"), makeRequest( request() .withMethod("POST") .withPath(calculatePath("some_pathRequest")) .withQueryStringParameters( param("queryStringParameterOneName", "OTHER Parameter One Value One", "OTHER Parameter One Value Two"), param("queryStringParameterTwoName", "Parameter Two") ), headersToIgnore) ); } @Test public void shouldReturnResponseByNotMatchingCookieWithNotOperatorForNameAndValue() { // when mockServerClient .when( request() .withMethod("GET") .withPath(calculatePath("some_pathRequest")) .withCookies( cookie(not("requestCookieNameOne"), not("requestCookieValueOne")), cookie("requestCookieNameTwo", "requestCookieValueTwo") ) ) .respond( response() .withStatusCode(ACCEPTED_202.code()) .withReasonPhrase(ACCEPTED_202.reasonPhrase()) .withBody("some_body_response") ); // then // wrong query string cookie name assertEquals( response() .withStatusCode(ACCEPTED_202.code()) .withReasonPhrase(ACCEPTED_202.reasonPhrase()) .withBody("some_body_response"), makeRequest( request() .withMethod("GET") .withPath(calculatePath("some_pathRequest")) .withCookies( cookie("OTHERrequestCookieNameOne", "requestCookieValueOne"), cookie("requestCookieNameTwo", "requestCookieValueTwo") ), headersToIgnore) ); // wrong query string cookie value assertEquals( response() .withStatusCode(ACCEPTED_202.code()) .withReasonPhrase(ACCEPTED_202.reasonPhrase()) .withBody("some_body_response"), makeRequest( request() .withMethod("GET") .withPath(calculatePath("some_pathRequest")) .withCookies( cookie("requestCookieNameOne", "OTHERrequestCookieValueOne"), cookie("requestCookieNameTwo", "requestCookieValueTwo") ), headersToIgnore) ); } @Test public void shouldReturnResponseByNotMatchingCookieWithNotOperatorForName() { // when mockServerClient .when( request() .withMethod("GET") .withPath(calculatePath("some_pathRequest")) .withCookies( cookie(not("requestCookieNameOne"), string("requestCookieValueOne")), cookie("requestCookieNameTwo", "requestCookieValueTwo") ) ) .respond( response() .withStatusCode(ACCEPTED_202.code()) .withReasonPhrase(ACCEPTED_202.reasonPhrase()) .withBody("some_body_response") ); // then // wrong query string cookie name assertEquals( response() .withStatusCode(ACCEPTED_202.code()) .withReasonPhrase(ACCEPTED_202.reasonPhrase()) .withBody("some_body_response"), makeRequest( request() .withMethod("GET") .withPath(calculatePath("some_pathRequest")) .withCookies( cookie("OTHERrequestCookieNameOne", "requestCookieValueOne"), cookie("requestCookieNameTwo", "requestCookieValueTwo") ), headersToIgnore) ); } @Test public void shouldReturnResponseByNotMatchingCookieWithNotOperatorForValue() { // when mockServerClient .when( request() .withMethod("GET") .withPath(calculatePath("some_pathRequest")) .withCookies( cookie(string("requestCookieNameOne"), not("requestCookieValueOne")), cookie("requestCookieNameTwo", "requestCookieValueTwo") ) ) .respond( response() .withStatusCode(ACCEPTED_202.code()) .withReasonPhrase(ACCEPTED_202.reasonPhrase()) .withBody("some_body_response") ); // then // wrong query string cookie value assertEquals( response() .withStatusCode(ACCEPTED_202.code()) .withReasonPhrase(ACCEPTED_202.reasonPhrase()) .withBody("some_body_response"), makeRequest( request() .withMethod("GET") .withPath(calculatePath("some_pathRequest")) .withCookies( cookie("requestCookieNameOne", "OTHERrequestCookieValueOne"), cookie("requestCookieNameTwo", "requestCookieValueTwo") ), headersToIgnore) ); } @Test public void shouldReturnResponseByNotMatchingHeaderWithNotOperatorForNameAndValue() { // when mockServerClient .when( request() .withMethod("GET") .withPath(calculatePath("some_pathRequest")) .withHeaders( header(not("requestHeaderNameOne"), not("requestHeaderValueOne")), header("requestHeaderNameTwo", "requestHeaderValueTwo") ) ) .respond( response() .withStatusCode(ACCEPTED_202.code()) .withReasonPhrase(ACCEPTED_202.reasonPhrase()) .withBody("some_body_response") ); // then // wrong query string header name assertEquals( response() .withStatusCode(ACCEPTED_202.code()) .withReasonPhrase(ACCEPTED_202.reasonPhrase()) .withBody("some_body_response"), makeRequest( request() .withMethod("GET") .withPath(calculatePath("some_pathRequest")) .withHeaders( header("OTHERrequestHeaderNameOne", "requestHeaderValueOne"), header("requestHeaderNameTwo", "requestHeaderValueTwo") ), headersToIgnore) ); // wrong query string header value assertEquals( response() .withStatusCode(ACCEPTED_202.code()) .withReasonPhrase(ACCEPTED_202.reasonPhrase()) .withBody("some_body_response"), makeRequest( request() .withMethod("GET") .withPath(calculatePath("some_pathRequest")) .withHeaders( header("requestHeaderNameOne", "OTHERrequestHeaderValueOne"), header("requestHeaderNameTwo", "requestHeaderValueTwo") ), headersToIgnore) ); } @Test public void shouldReturnResponseByNotMatchingHeaderWithNotOperatorForName() { // when mockServerClient .when( request() .withMethod("GET") .withPath(calculatePath("some_pathRequest")) .withHeaders( header(not("requestHeaderNameOne"), string("requestHeaderValueOne")), header("requestHeaderNameTwo", "requestHeaderValueTwo") ) ) .respond( response() .withStatusCode(ACCEPTED_202.code()) .withReasonPhrase(ACCEPTED_202.reasonPhrase()) .withBody("some_body_response") ); // then // wrong query string header name assertEquals( response() .withStatusCode(ACCEPTED_202.code()) .withReasonPhrase(ACCEPTED_202.reasonPhrase()) .withBody("some_body_response"), makeRequest( request() .withMethod("GET") .withPath(calculatePath("some_pathRequest")) .withHeaders( header("OTHERrequestHeaderNameOne", "requestHeaderValueOne"), header("requestHeaderNameTwo", "requestHeaderValueTwo") ), headersToIgnore) ); } @Test public void shouldReturnResponseByNotMatchingHeaderWithNotOperatorForValue() { // when mockServerClient .when( request() .withMethod("GET") .withPath(calculatePath("some_pathRequest")) .withHeaders( header(string("requestHeaderNameOne"), not("requestHeaderValueOne")), header("requestHeaderNameTwo", "requestHeaderValueTwo") ) ) .respond( response() .withStatusCode(ACCEPTED_202.code()) .withReasonPhrase(ACCEPTED_202.reasonPhrase()) .withBody("some_body_response") ); // then // wrong query string header value assertEquals( response() .withStatusCode(ACCEPTED_202.code()) .withReasonPhrase(ACCEPTED_202.reasonPhrase()) .withBody("some_body_response"), makeRequest( request() .withMethod("GET") .withPath(calculatePath("some_pathRequest")) .withHeaders( header("requestHeaderNameOne", "OTHERrequestHeaderValueOne"), header("requestHeaderNameTwo", "requestHeaderValueTwo") ), headersToIgnore) ); } @Test public void shouldNotReturnResponseForWhenTimeToLiveExpired() { // when mockServerClient .when( request().withPath(calculatePath("some_path")), exactly(2), TimeToLive.exactly(TimeUnit.SECONDS, 3L) ) .respond( response().withBody("some_body").withDelay(TimeUnit.SECONDS, 3L) ); // then assertEquals( response() .withStatusCode(OK_200.code()) .withReasonPhrase(OK_200.reasonPhrase()) .withBody("some_body"), makeRequest( request() .withPath(calculatePath("some_path")), headersToIgnore) ); // - in http assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()) .withReasonPhrase(HttpStatusCode.NOT_FOUND_404.reasonPhrase()), makeRequest( request() .withPath(calculatePath("some_path")), headersToIgnore) ); // - in https assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()) .withReasonPhrase(HttpStatusCode.NOT_FOUND_404.reasonPhrase()), makeRequest( request() .withSecure(true) .withPath(calculatePath("some_path")), headersToIgnore) ); } @Test public void shouldNotReturnResponseForMatchingBodyWithNotOperator() { // when mockServerClient .when( request() .withBody(Not.not(json("{" + NEW_LINE + " \"id\": 1," + NEW_LINE + " \"name\": \"A green door\"," + NEW_LINE + " \"price\": 12.50," + NEW_LINE + " \"tags\": [\"home\", \"green\"]" + NEW_LINE + "}"))), exactly(2) ) .respond( response() .withStatusCode(ACCEPTED_202.code()) .withReasonPhrase(ACCEPTED_202.reasonPhrase()) .withBody("some_body") ); // then // - in http assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()) .withReasonPhrase(HttpStatusCode.NOT_FOUND_404.reasonPhrase()), makeRequest( request() .withPath(calculatePath("some_path")) .withMethod("POST") .withBody("{" + NEW_LINE + " \"id\": 1," + NEW_LINE + " \"extra_ignored_field\": \"some value\"," + NEW_LINE + " \"name\": \"A green door\"," + NEW_LINE + " \"price\": 12.50," + NEW_LINE + " \"tags\": [\"home\", \"green\"]" + NEW_LINE + "}"), headersToIgnore) ); // - in https assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()) .withReasonPhrase(HttpStatusCode.NOT_FOUND_404.reasonPhrase()), makeRequest( request() .withSecure(true) .withPath(calculatePath("some_path")) .withMethod("POST") .withBody("{" + NEW_LINE + " \"id\": 1," + NEW_LINE + " \"extra_ignored_array\": [\"one\", \"two\"]," + NEW_LINE + " \"name\": \"A green door\"," + NEW_LINE + " \"price\": 12.50," + NEW_LINE + " \"tags\": [\"home\", \"green\"]" + NEW_LINE + "}"), headersToIgnore) ); } @Test public void shouldNotReturnResponseForNonMatchingXPathBody() { // when mockServerClient.when(request().withBody(new XPathBody("/bookstore/book[price>35]/price")), exactly(2)).respond(response().withBody("some_body")); // then // - in http assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()) .withReasonPhrase(HttpStatusCode.NOT_FOUND_404.reasonPhrase()), makeRequest( request() .withSecure(true) .withPath(calculatePath("some_path")) .withMethod("POST") .withBody(new StringBody("" + "<?xml version=\"1.0\" encoding=\"ISO-8859-1\"?>" + NEW_LINE + "<bookstore>" + NEW_LINE + " <book category=\"COOKING\">" + NEW_LINE + " <title lang=\"en\">Everyday Italian</title>" + NEW_LINE + " <author>Giada De Laurentiis</author>" + NEW_LINE + " <year>2005</year>" + NEW_LINE + " <price>30.00</price>" + NEW_LINE + " </book>" + NEW_LINE + " <book category=\"CHILDREN\">" + NEW_LINE + " <title lang=\"en\">Harry Potter</title>" + NEW_LINE + " <author>J K. Rowling</author>" + NEW_LINE + " <year>2005</year>" + NEW_LINE + " <price>29.99</price>" + NEW_LINE + " </book>" + NEW_LINE + " <book category=\"WEB\">" + NEW_LINE + " <title lang=\"en\">Learning XML</title>" + NEW_LINE + " <author>Erik T. Ray</author>" + NEW_LINE + " <year>2003</year>" + NEW_LINE + " <price>31.95</price>" + NEW_LINE + " </book>" + NEW_LINE + "</bookstore>")), headersToIgnore) ); // - in https assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()) .withReasonPhrase(HttpStatusCode.NOT_FOUND_404.reasonPhrase()), makeRequest( request() .withSecure(true) .withPath(calculatePath("some_path")) .withMethod("POST") .withBody(new StringBody("" + "<?xml version=\"1.0\" encoding=\"ISO-8859-1\"?>" + NEW_LINE + "<bookstore>" + NEW_LINE + " <book category=\"COOKING\">" + NEW_LINE + " <title lang=\"en\">Everyday Italian</title>" + NEW_LINE + " <author>Giada De Laurentiis</author>" + NEW_LINE + " <year>2005</year>" + NEW_LINE + " <price>30.00</price>" + NEW_LINE + " </book>" + NEW_LINE + " <book category=\"CHILDREN\">" + NEW_LINE + " <title lang=\"en\">Harry Potter</title>" + NEW_LINE + " <author>J K. Rowling</author>" + NEW_LINE + " <year>2005</year>" + NEW_LINE + " <price>29.99</price>" + NEW_LINE + " </book>" + NEW_LINE + " <book category=\"WEB\">" + NEW_LINE + " <title lang=\"en\">Learning XML</title>" + NEW_LINE + " <author>Erik T. Ray</author>" + NEW_LINE + " <year>2003</year>" + NEW_LINE + " <price>31.95</price>" + NEW_LINE + " </book>" + NEW_LINE + "</bookstore>")), headersToIgnore) ); } @Test public void shouldNotReturnResponseForNonMatchingXmlBody() { // when mockServerClient.when(request().withBody(xml("" + "<?xml version=\"1.0\" encoding=\"ISO-8859-1\"?>" + NEW_LINE + "<bookstore>" + NEW_LINE + " <book category=\"COOKING\" nationality=\"ITALIAN\">" + NEW_LINE + " <title lang=\"en\">Everyday Italian</title>" + NEW_LINE + " <author>Giada De Laurentiis</author>" + NEW_LINE + " <year>2005</year>" + NEW_LINE + " <price>30.00</price>" + NEW_LINE + " </book>" + NEW_LINE + "</bookstore>")), exactly(2)).respond(response().withBody("some_body")); // then // - in http assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()) .withReasonPhrase(HttpStatusCode.NOT_FOUND_404.reasonPhrase()), makeRequest( request() .withSecure(true) .withPath(calculatePath("some_path")) .withMethod("POST") .withBody(new StringBody("" + "<?xml version=\"1.0\" encoding=\"ISO-8859-1\"?>" + NEW_LINE + "<bookstore>" + NEW_LINE + " <book category=\"COOKING\">" + NEW_LINE + " <title lang=\"en\">Everyday Italian</title>" + NEW_LINE + " <author>Giada De Laurentiis</author>" + NEW_LINE + " <year>2005</year>" + NEW_LINE + " <price>30.00</price>" + NEW_LINE + " </book>" + NEW_LINE + "</bookstore>")), headersToIgnore) ); // - in https assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()) .withReasonPhrase(HttpStatusCode.NOT_FOUND_404.reasonPhrase()), makeRequest( request() .withSecure(true) .withPath(calculatePath("some_path")) .withMethod("POST") .withBody(new StringBody("" + "<?xml version=\"1.0\" encoding=\"ISO-8859-1\"?>" + NEW_LINE + "<bookstore>" + NEW_LINE + " <book category=\"COOKING\">" + NEW_LINE + " <title lang=\"en\">Everyday Italian</title>" + NEW_LINE + " <author>Giada De Laurentiis</author>" + NEW_LINE + " <year>2005</year>" + NEW_LINE + " <price>30.00</price>" + NEW_LINE + " </book>" + NEW_LINE + "</bookstore>")), headersToIgnore) ); } @Test public void shouldNotReturnResponseForNonMatchingJsonBody() { // when mockServerClient.when(request().withBody(json("{" + NEW_LINE + " \"id\": 1," + NEW_LINE + " \"name\": \"A green door\"," + NEW_LINE + " \"price\": 12.50," + NEW_LINE + " \"tags\": [\"home\", \"green\"]" + NEW_LINE + "}")), exactly(2)).respond(response().withBody("some_body")); // then // - in http assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()) .withReasonPhrase(HttpStatusCode.NOT_FOUND_404.reasonPhrase()), makeRequest( request() .withPath(calculatePath("some_path")) .withMethod("POST") .withBody("{" + NEW_LINE + " \"id\": 1," + NEW_LINE + " \"name\": \"---- XXXX WRONG VALUE XXXX ----\"," + NEW_LINE + " \"price\": 12.50," + NEW_LINE + " \"tags\": [\"home\", \"green\"]" + NEW_LINE + "}"), headersToIgnore) ); // - in https assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()) .withReasonPhrase(HttpStatusCode.NOT_FOUND_404.reasonPhrase()), makeRequest( request() .withSecure(true) .withPath(calculatePath("some_path")) .withMethod("POST") .withBody("{" + NEW_LINE + " \"id\": 1," + NEW_LINE + " \"name\": \"---- XXXX WRONG VALUE XXXX ----\"," + NEW_LINE + " \"price\": 12.50," + NEW_LINE + " \"tags\": [\"home\", \"green\"]" + NEW_LINE + "}"), headersToIgnore) ); } @Test public void shouldNotReturnResponseForNonMatchingJsonBodyWithMatchType() { // when mockServerClient .when( request() .withBody(json("{" + NEW_LINE + " \"id\": 1," + NEW_LINE + " \"name\": \"A green door\"," + NEW_LINE + " \"price\": 12.50," + NEW_LINE + " \"tags\": [\"home\", \"green\"]" + NEW_LINE + "}", MatchType.STRICT)), exactly(2)) .respond( response() .withBody("some_body") ); // then // - in http assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()) .withReasonPhrase(HttpStatusCode.NOT_FOUND_404.reasonPhrase()), makeRequest( request() .withPath(calculatePath("some_path")) .withMethod("POST") .withBody("{" + NEW_LINE + " \"id\": 1," + NEW_LINE + " \"extra field\": \"some value\"," + NEW_LINE + " \"name\": \"A green door\"," + NEW_LINE + " \"price\": 12.50," + NEW_LINE + " \"tags\": [\"home\", \"green\"]" + NEW_LINE + "}"), headersToIgnore) ); // - in https assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()) .withReasonPhrase(HttpStatusCode.NOT_FOUND_404.reasonPhrase()), makeRequest( request() .withSecure(true) .withPath(calculatePath("some_path")) .withMethod("POST") .withBody("{" + NEW_LINE + " \"id\": 1," + NEW_LINE + " \"extra field\": \"some value\"," + NEW_LINE + " \"name\": \"A green door\"," + NEW_LINE + " \"price\": 12.50," + NEW_LINE + " \"tags\": [\"home\", \"green\"]" + NEW_LINE + "}"), headersToIgnore) ); } @Test public void shouldNotReturnResponseForNonMatchingJsonSchema() { // when mockServerClient.when(request().withBody(jsonSchema("{" + NEW_LINE + " \"$schema\": \"http://json-schema.org/draft-04/schema#\"," + NEW_LINE + " \"title\": \"Product\"," + NEW_LINE + " \"description\": \"A product from Acme's catalog\"," + NEW_LINE + " \"type\": \"object\"," + NEW_LINE + " \"properties\": {" + NEW_LINE + " \"id\": {" + NEW_LINE + " \"description\": \"The unique identifier for a product\"," + NEW_LINE + " \"type\": \"integer\"" + NEW_LINE + " }," + NEW_LINE + " \"name\": {" + NEW_LINE + " \"description\": \"Name of the product\"," + NEW_LINE + " \"type\": \"string\"" + NEW_LINE + " }," + NEW_LINE + " \"price\": {" + NEW_LINE + " \"type\": \"number\"," + NEW_LINE + " \"minimum\": 0," + NEW_LINE + " \"exclusiveMinimum\": true" + NEW_LINE + " }," + NEW_LINE + " \"tags\": {" + NEW_LINE + " \"type\": \"array\"," + NEW_LINE + " \"items\": {" + NEW_LINE + " \"type\": \"string\"" + NEW_LINE + " }," + NEW_LINE + " \"minItems\": 1," + NEW_LINE + " \"uniqueItems\": true" + NEW_LINE + " }" + NEW_LINE + " }," + NEW_LINE + " \"required\": [\"id\", \"name\", \"price\"]" + NEW_LINE + "}")), exactly(2)).respond(response().withBody("some_body")); // then // - in http assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()) .withReasonPhrase(HttpStatusCode.NOT_FOUND_404.reasonPhrase()), makeRequest( request() .withPath(calculatePath("some_path")) .withMethod("POST") .withBody("{" + NEW_LINE + " \"id\": 1," + NEW_LINE + " \"wrong field name\": \"A green door\"," + NEW_LINE + " \"price\": 12.50," + NEW_LINE + " \"tags\": [\"home\", \"green\"]" + NEW_LINE + "}"), headersToIgnore) ); // - in https assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()) .withReasonPhrase(HttpStatusCode.NOT_FOUND_404.reasonPhrase()), makeRequest( request() .withSecure(true) .withPath(calculatePath("some_path")) .withMethod("POST") .withBody("{" + NEW_LINE + " \"id\": 1," + NEW_LINE + " \"name\": \"A green door\"," + NEW_LINE + " \"wrong field name\": 12.50," + NEW_LINE + " \"tags\": [\"home\", \"green\"]" + NEW_LINE + "}"), headersToIgnore) ); } @Test public void shouldNotReturnResponseForNonMatchingJsonPathBody() { // when mockServerClient.when(request().withBody(new JsonPathBody("$..book[?(@.price > $['expensive'])]")), exactly(2)).respond(response().withBody("some_body")); // then // - in http assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()) .withReasonPhrase(HttpStatusCode.NOT_FOUND_404.reasonPhrase()), makeRequest( request() .withSecure(true) .withPath(calculatePath("some_path")) .withMethod("POST") .withBody(new StringBody("" + "{" + NEW_LINE + " \"store\": {" + NEW_LINE + " \"book\": [" + NEW_LINE + " {" + NEW_LINE + " \"category\": \"reference\"," + NEW_LINE + " \"author\": \"Nigel Rees\"," + NEW_LINE + " \"title\": \"Sayings of the Century\"," + NEW_LINE + " \"price\": 8.95" + NEW_LINE + " }," + NEW_LINE + " {" + NEW_LINE + " \"category\": \"fiction\"," + NEW_LINE + " \"author\": \"Herman Melville\"," + NEW_LINE + " \"title\": \"Moby Dick\"," + NEW_LINE + " \"isbn\": \"0-553-21311-3\"," + NEW_LINE + " \"price\": 8.99" + NEW_LINE + " }" + NEW_LINE + " ]," + NEW_LINE + " \"bicycle\": {" + NEW_LINE + " \"color\": \"red\"," + NEW_LINE + " \"price\": 19.95" + NEW_LINE + " }" + NEW_LINE + " }," + NEW_LINE + " \"expensive\": 10" + NEW_LINE + "}")), headersToIgnore) ); // - in https assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()) .withReasonPhrase(HttpStatusCode.NOT_FOUND_404.reasonPhrase()), makeRequest( request() .withSecure(true) .withPath(calculatePath("some_path")) .withMethod("POST") .withBody(new StringBody("" + "{" + NEW_LINE + " \"store\": {" + NEW_LINE + " \"book\": [" + NEW_LINE + " {" + NEW_LINE + " \"category\": \"reference\"," + NEW_LINE + " \"author\": \"Nigel Rees\"," + NEW_LINE + " \"title\": \"Sayings of the Century\"," + NEW_LINE + " \"price\": 8.95" + NEW_LINE + " }," + NEW_LINE + " {" + NEW_LINE + " \"category\": \"fiction\"," + NEW_LINE + " \"author\": \"Herman Melville\"," + NEW_LINE + " \"title\": \"Moby Dick\"," + NEW_LINE + " \"isbn\": \"0-553-21311-3\"," + NEW_LINE + " \"price\": 8.99" + NEW_LINE + " }" + NEW_LINE + " ]," + NEW_LINE + " \"bicycle\": {" + NEW_LINE + " \"color\": \"red\"," + NEW_LINE + " \"price\": 19.95" + NEW_LINE + " }" + NEW_LINE + " }," + NEW_LINE + " \"expensive\": 10" + NEW_LINE + "}")), headersToIgnore) ); } @Test public void shouldNotReturnResponseForMatchingPathWithNotOperator() { // when mockServerClient .when( request() .withPath(not(calculatePath("some_path"))) ) .respond( response() .withStatusCode(ACCEPTED_202.code()) .withReasonPhrase(ACCEPTED_202.reasonPhrase()) .withBody("some_body_response") ); // then // - in http assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()) .withReasonPhrase(HttpStatusCode.NOT_FOUND_404.reasonPhrase()), makeRequest( request() .withPath(calculatePath("some_path")), headersToIgnore) ); // - in https assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()) .withReasonPhrase(HttpStatusCode.NOT_FOUND_404.reasonPhrase()), makeRequest( request() .withPath(calculatePath("some_path")), headersToIgnore) ); } @Test public void shouldNotReturnResponseForMatchingMethodWithNotOperator() { // when mockServerClient .when( request() .withMethod(not("GET")) ) .respond( response() .withStatusCode(ACCEPTED_202.code()) .withReasonPhrase(ACCEPTED_202.reasonPhrase()) .withBody("some_body_response") ); // then // - in http assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()) .withReasonPhrase(HttpStatusCode.NOT_FOUND_404.reasonPhrase()), makeRequest( request() .withMethod("GET"), headersToIgnore) ); // - in https assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()) .withReasonPhrase(HttpStatusCode.NOT_FOUND_404.reasonPhrase()), makeRequest( request() .withMethod("GET"), headersToIgnore) ); } @Test public void shouldNotReturnResponseForNonMatchingBodyParameterName() { // when mockServerClient .when( request() .withMethod("POST") .withPath(calculatePath("some_pathRequest")) .withBody(params( param("bodyParameterOneName", "Parameter One Value One", "Parameter One Value Two"), param("bodyParameterTwoName", "Parameter Two") )) ) .respond( response() .withStatusCode(ACCEPTED_202.code()) .withReasonPhrase(ACCEPTED_202.reasonPhrase()) .withBody("some_body_response") .withHeaders(header("headerNameResponse", "headerValueResponse")) .withCookies(cookie("cookieNameResponse", "cookieValueResponse")) ); // then // wrong query string parameter name assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()) .withReasonPhrase(HttpStatusCode.NOT_FOUND_404.reasonPhrase()), makeRequest( request() .withMethod("POST") .withPath(calculatePath("some_pathRequest")) .withBody(params( param("OTHERBodyParameterOneName", "Parameter One Value One", "Parameter One Value Two"), param("bodyParameterTwoName", "Parameter Two") )) .withHeaders(header("headerNameRequest", "headerValueRequest")) .withCookies(cookie("cookieNameRequest", "cookieValueRequest")), headersToIgnore) ); // wrong query string parameter name assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()) .withReasonPhrase(HttpStatusCode.NOT_FOUND_404.reasonPhrase()), makeRequest( request() .withMethod("POST") .withPath(calculatePath("some_pathRequest")) .withBody(new StringBody("OTHERBodyParameterOneName=Parameter+One+Value+One" + "&bodyParameterOneName=Parameter+One+Value+Two" + "&bodyParameterTwoName=Parameter+Two")) .withHeaders(header("headerNameRequest", "headerValueRequest")) .withCookies(cookie("cookieNameRequest", "cookieValueRequest")), headersToIgnore) ); } @Test public void shouldNotReturnResponseForMatchingBodyParameterWithNotOperator() { // when mockServerClient .when( request() .withMethod("POST") .withPath(calculatePath("some_pathRequest")) .withBody(params( param(not("bodyParameterOneName"), not("Parameter One Value One"), not("Parameter One Value Two")), param("bodyParameterTwoName", "Parameter Two") )) ) .respond( response() .withStatusCode(ACCEPTED_202.code()) .withReasonPhrase(ACCEPTED_202.reasonPhrase()) .withBody("some_body_response") ); // then // wrong query string parameter name assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()) .withReasonPhrase(HttpStatusCode.NOT_FOUND_404.reasonPhrase()), makeRequest( request() .withMethod("POST") .withPath(calculatePath("some_pathRequest")) .withBody(params( param("bodyParameterOneName", "Parameter One Value One", "Parameter One Value Two"), param("bodyParameterTwoName", "Parameter Two") )) .withHeaders(header("headerNameRequest", "headerValueRequest")) .withCookies(cookie("cookieNameRequest", "cookieValueRequest")), headersToIgnore) ); // wrong query string parameter name assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()) .withReasonPhrase(HttpStatusCode.NOT_FOUND_404.reasonPhrase()), makeRequest( request() .withMethod("POST") .withPath(calculatePath("some_pathRequest")) .withBody(new StringBody("bodyParameterOneName=Other Parameter+One+Value+One" + "&bodyParameterOneName=Parameter+One+Value+Two" + "&bodyParameterTwoName=Parameter+Two")) .withHeaders(header("headerNameRequest", "headerValueRequest")) .withCookies(cookie("cookieNameRequest", "cookieValueRequest")), headersToIgnore) ); } @Test public void shouldNotReturnResponseForNonMatchingBodyParameterValue() { // when mockServerClient .when( request() .withMethod("POST") .withPath(calculatePath("some_pathRequest")) .withBody(params( param("bodyParameterOneName", "Parameter One Value One", "Parameter One Value Two"), param("bodyParameterTwoName", "Parameter Two") )) ) .respond( response() .withStatusCode(ACCEPTED_202.code()) .withReasonPhrase(ACCEPTED_202.reasonPhrase()) .withBody("some_body_response") .withHeaders(header("headerNameResponse", "headerValueResponse")) .withCookies(cookie("cookieNameResponse", "cookieValueResponse")) ); // then // wrong body parameter value assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()) .withReasonPhrase(HttpStatusCode.NOT_FOUND_404.reasonPhrase()), makeRequest( request() .withMethod("POST") .withPath(calculatePath("some_pathRequest")) .withBody(params( param("bodyParameterOneName", "Other Parameter One Value One", "Parameter One Value Two"), param("bodyParameterTwoName", "Parameter Two") )) .withHeaders(header("headerNameRequest", "headerValueRequest")) .withCookies(cookie("cookieNameRequest", "cookieValueRequest")), headersToIgnore) ); // wrong body parameter value assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()) .withReasonPhrase(HttpStatusCode.NOT_FOUND_404.reasonPhrase()), makeRequest( request() .withMethod("POST") .withPath(calculatePath("some_pathRequest")) .withBody(new StringBody("bodyParameterOneName=Other Parameter+One+Value+One" + "&bodyParameterOneName=Parameter+One+Value+Two" + "&bodyParameterTwoName=Parameter+Two")) .withHeaders(header("headerNameRequest", "headerValueRequest")) .withCookies(cookie("cookieNameRequest", "cookieValueRequest")), headersToIgnore) ); } @Test public void shouldNotReturnResponseForNonMatchingQueryStringParameterName() { // when mockServerClient .when( request() .withMethod("POST") .withPath(calculatePath("some_pathRequest")) .withQueryStringParameters( param("queryStringParameterOneName", "queryStringParameterOneValueOne", "queryStringParameterOneValueTwo"), param("queryStringParameterTwoName", "queryStringParameterTwoValue") ) .withBody("some_bodyRequest") ) .respond( response() .withStatusCode(ACCEPTED_202.code()) .withReasonPhrase(ACCEPTED_202.reasonPhrase()) .withBody("some_body_response") .withHeaders(header("headerNameResponse", "headerValueResponse")) .withCookies(cookie("cookieNameResponse", "cookieValueResponse")) ); // then // wrong query string parameter name assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()) .withReasonPhrase(HttpStatusCode.NOT_FOUND_404.reasonPhrase()), makeRequest( request() .withMethod("POST") .withPath(calculatePath("some_pathRequest")) .withQueryStringParameters( param("OTHERQueryStringParameterOneName", "queryStringParameterOneValueOne", "queryStringParameterOneValueTwo"), param("queryStringParameterTwoName", "queryStringParameterTwoValue") ) .withBody("some_bodyRequest") .withHeaders( header("headerNameRequest", "headerValueRequest") ) .withCookies(cookie("cookieNameRequest", "cookieValueRequest")), headersToIgnore) ); } @Test public void shouldNotReturnResponseForNonMatchingQueryStringParameterValue() { // when mockServerClient .when( request() .withMethod("POST") .withPath(calculatePath("some_pathRequest")) .withQueryStringParameters( param("queryStringParameterOneName", "queryStringParameterOneValueOne", "queryStringParameterOneValueTwo"), param("queryStringParameterTwoName", "queryStringParameterTwoValue") ) .withBody("some_bodyRequest") ) .respond( response() .withStatusCode(ACCEPTED_202.code()) .withReasonPhrase(ACCEPTED_202.reasonPhrase()) .withBody("some_body_response") .withHeaders(header("headerNameResponse", "headerValueResponse")) .withCookies(cookie("cookieNameResponse", "cookieValueResponse")) ); // then // wrong query string parameter value assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()) .withReasonPhrase(HttpStatusCode.NOT_FOUND_404.reasonPhrase()), makeRequest( request() .withMethod("POST") .withPath(calculatePath("some_pathRequest")) .withQueryStringParameters( param("queryStringParameterOneName", "OTHERqueryStringParameterOneValueOne", "queryStringParameterOneValueTwo"), param("queryStringParameterTwoName", "queryStringParameterTwoValue") ) .withBody("some_bodyRequest") .withHeaders(header("headerNameRequest", "headerValueRequest")) .withCookies(cookie("cookieNameRequest", "cookieValueRequest")), headersToIgnore) ); } @Test public void shouldNotReturnResponseForMatchingQueryStringParameterWithNotOperator() { // when mockServerClient .when( request() .withMethod("POST") .withPath(calculatePath("some_pathRequest")) .withQueryStringParameters( param(not("queryStringParameterOneName"), not("Parameter One Value One"), not("Parameter One Value Two")), param("queryStringParameterTwoName", "Parameter Two") ) ) .respond( response() .withStatusCode(ACCEPTED_202.code()) .withReasonPhrase(ACCEPTED_202.reasonPhrase()) .withBody("some_body_response") ); // then // wrong query string parameter name assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()) .withReasonPhrase(HttpStatusCode.NOT_FOUND_404.reasonPhrase()), makeRequest( request() .withMethod("POST") .withPath(calculatePath("some_pathRequest")) .withQueryStringParameters( param("queryStringParameterOneName", "Parameter One Value One", "Parameter One Value Two"), param("queryStringParameterTwoName", "Parameter Two") ), headersToIgnore) ); // wrong query string parameter name assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()) .withReasonPhrase(HttpStatusCode.NOT_FOUND_404.reasonPhrase()), makeRequest( request() .withMethod("POST") .withPath(calculatePath("some_pathRequest")) .withQueryStringParameters( param("queryStringParameterOneName", "Parameter One Value One", "Parameter One Value Two"), param("queryStringParameterTwoName", "Parameter Two") ), headersToIgnore) ); } @Test public void shouldNotReturnResponseForNonMatchingCookieName() { // when mockServerClient .when( request() .withMethod("GET") .withPath(calculatePath("some_path")) .withQueryStringParameters( param("queryStringParameterOneName", "queryStringParameterOneValue"), param("queryStringParameterTwoName", "queryStringParameterTwoValue") ) .withBody(exact("some_body")) .withHeaders(header("headerName", "headerValue")) .withCookies(cookie("cookieName", "cookieValue")) ) .respond( response() .withStatusCode(ACCEPTED_202.code()) .withReasonPhrase(ACCEPTED_202.reasonPhrase()) .withBody("some_body") .withHeaders(header("headerName", "headerValue")) .withCookies(cookie("cookieName", "cookieValue")) ); // then // - in http assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()) .withReasonPhrase(HttpStatusCode.NOT_FOUND_404.reasonPhrase()), makeRequest( request() .withMethod("GET") .withPath(calculatePath("some_path")) .withQueryStringParameters( param("queryStringParameterOneName", "queryStringParameterOneValue"), param("queryStringParameterTwoName", "queryStringParameterTwoValue") ) .withBody(exact("some_body")) .withHeaders(header("headerName", "headerValue")) .withCookies(cookie("cookieOtherName", "cookieValue")), headersToIgnore) ); // - in https assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()) .withReasonPhrase(HttpStatusCode.NOT_FOUND_404.reasonPhrase()), makeRequest( request() .withMethod("GET") .withSecure(true) .withPath(calculatePath("some_path")) .withQueryStringParameters( param("queryStringParameterOneName", "queryStringParameterOneValue"), param("queryStringParameterTwoName", "queryStringParameterTwoValue") ) .withBody(exact("some_body")) .withHeaders(header("headerName", "headerValue")) .withCookies(cookie("cookieOtherName", "cookieValue")), headersToIgnore) ); } @Test public void shouldNotReturnResponseForNonMatchingCookieValue() { // when mockServerClient .when( request() .withMethod("GET") .withPath(calculatePath("some_path")) .withQueryStringParameters( param("queryStringParameterOneName", "queryStringParameterOneValue"), param("queryStringParameterTwoName", "queryStringParameterTwoValue") ) .withBody(exact("some_body")) .withHeaders(header("headerName", "headerValue")) .withCookies(cookie("cookieName", "cookieValue")) ) .respond( response() .withStatusCode(ACCEPTED_202.code()) .withReasonPhrase(ACCEPTED_202.reasonPhrase()) .withBody("some_body") .withHeaders(header("headerName", "headerValue")) .withCookies(cookie("cookieName", "cookieValue")) ); // then // - in http assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()) .withReasonPhrase(HttpStatusCode.NOT_FOUND_404.reasonPhrase()), makeRequest( request() .withMethod("GET") .withPath(calculatePath("some_path")) .withQueryStringParameters( param("queryStringParameterOneName", "queryStringParameterOneValue"), param("queryStringParameterTwoName", "queryStringParameterTwoValue") ) .withBody(exact("some_body")) .withHeaders(header("headerName", "headerValue")) .withCookies(cookie("cookieName", "cookieOtherValue")), headersToIgnore) ); // - in https assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()) .withReasonPhrase(HttpStatusCode.NOT_FOUND_404.reasonPhrase()), makeRequest( request() .withMethod("GET") .withSecure(true) .withPath(calculatePath("some_path")) .withQueryStringParameters( param("queryStringParameterOneName", "queryStringParameterOneValue"), param("queryStringParameterTwoName", "queryStringParameterTwoValue") ) .withBody(exact("some_body")) .withHeaders(header("headerName", "headerValue")) .withCookies(cookie("cookieName", "cookieOtherValue")), headersToIgnore) ); } @Test public void shouldNotReturnResponseForMatchingCookieWithNotOperator() { // when mockServerClient .when( request() .withMethod("GET") .withPath(calculatePath("some_pathRequest")) .withCookies( cookie(not("requestCookieNameOne"), not("requestCookieValueOne")), cookie("requestCookieNameTwo", "requestCookieValueTwo") ) ) .respond( response() .withStatusCode(ACCEPTED_202.code()) .withReasonPhrase(ACCEPTED_202.reasonPhrase()) .withBody("some_body_response") ); // then // wrong query string parameter name assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()) .withReasonPhrase(HttpStatusCode.NOT_FOUND_404.reasonPhrase()), makeRequest( request() .withMethod("GET") .withPath(calculatePath("some_pathRequest")) .withCookies( cookie("requestCookieNameOne", "requestCookieValueOne"), cookie("requestCookieNameTwo", "requestCookieValueTwo") ), headersToIgnore) ); // wrong query string parameter name assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()) .withReasonPhrase(HttpStatusCode.NOT_FOUND_404.reasonPhrase()), makeRequest( request() .withMethod("GET") .withPath(calculatePath("some_pathRequest")) .withCookies( cookie("requestCookieNameOne", "requestCookieValueOne"), cookie("requestCookieNameTwo", "requestCookieValueTwo") ), headersToIgnore) ); } @Test public void shouldNotReturnResponseForNonMatchingHeaderName() { // when mockServerClient .when( request() .withMethod("GET") .withPath(calculatePath("some_path")) .withQueryStringParameters( param("queryStringParameterOneName", "queryStringParameterOneValue"), param("queryStringParameterTwoName", "queryStringParameterTwoValue") ) .withBody(exact("some_body")) .withHeaders(header("headerName", "headerValue")) .withCookies(cookie("cookieName", "cookieValue")) ) .respond( response() .withStatusCode(ACCEPTED_202.code()) .withReasonPhrase(ACCEPTED_202.reasonPhrase()) .withBody("some_body") .withHeaders(header("headerName", "headerValue")) .withCookies(cookie("cookieName", "cookieValue")) ); // then // - in http assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()) .withReasonPhrase(HttpStatusCode.NOT_FOUND_404.reasonPhrase()), makeRequest( request() .withMethod("GET") .withPath(calculatePath("some_path")) .withQueryStringParameters( param("queryStringParameterOneName", "queryStringParameterOneValue"), param("queryStringParameterTwoName", "queryStringParameterTwoValue") ) .withBody(exact("some_body")) .withHeaders(header("headerOtherName", "headerValue")) .withCookies(cookie("cookieName", "cookieValue")), headersToIgnore) ); // - in https assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()) .withReasonPhrase(HttpStatusCode.NOT_FOUND_404.reasonPhrase()), makeRequest( request() .withMethod("GET") .withSecure(true) .withPath(calculatePath("some_path")) .withQueryStringParameters( param("queryStringParameterOneName", "queryStringParameterOneValue"), param("queryStringParameterTwoName", "queryStringParameterTwoValue") ) .withBody(exact("some_body")) .withHeaders(header("headerOtherName", "headerValue")) .withCookies(cookie("cookieName", "cookieValue")), headersToIgnore) ); } @Test public void shouldNotReturnResponseForNonMatchingHeaderValue() { // when mockServerClient .when( request() .withMethod("GET") .withPath(calculatePath("some_path")) .withQueryStringParameters( param("queryStringParameterOneName", "queryStringParameterOneValue"), param("queryStringParameterTwoName", "queryStringParameterTwoValue") ) .withBody(exact("some_body")) .withHeaders(header("headerName", "headerValue")) .withCookies(cookie("cookieName", "cookieValue")) ) .respond( response() .withStatusCode(ACCEPTED_202.code()) .withReasonPhrase(ACCEPTED_202.reasonPhrase()) .withBody("some_body") .withHeaders(header("headerName", "headerValue")) .withCookies(cookie("cookieName", "cookieValue")) ); // then // - in http assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()) .withReasonPhrase(HttpStatusCode.NOT_FOUND_404.reasonPhrase()), makeRequest( request() .withMethod("GET") .withPath(calculatePath("some_path")) .withQueryStringParameters( param("queryStringParameterOneName", "queryStringParameterOneValue"), param("queryStringParameterTwoName", "queryStringParameterTwoValue") ) .withBody(exact("some_body")) .withHeaders(header("headerName", "headerOtherValue")) .withCookies(cookie("cookieName", "cookieValue")), headersToIgnore) ); // - in https assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()) .withReasonPhrase(HttpStatusCode.NOT_FOUND_404.reasonPhrase()), makeRequest( request() .withMethod("GET") .withSecure(true) .withPath(calculatePath("some_path")) .withQueryStringParameters( param("queryStringParameterOneName", "queryStringParameterOneValue"), param("queryStringParameterTwoName", "queryStringParameterTwoValue") ) .withBody(exact("some_body")) .withHeaders(header("headerName", "headerOtherValue")) .withCookies(cookie("cookieName", "cookieValue")), headersToIgnore) ); } @Test public void shouldNotReturnResponseForMatchingHeaderWithNotOperator() { // when mockServerClient .when( request() .withMethod("GET") .withPath(calculatePath("some_pathRequest")) .withHeaders( header(not("requestHeaderNameOne"), not("requestHeaderValueOne")), header("requestHeaderNameTwo", "requestHeaderValueTwo") ) ) .respond( response() .withStatusCode(ACCEPTED_202.code()) .withReasonPhrase(ACCEPTED_202.reasonPhrase()) .withBody("some_body_response") ); // then // wrong query string parameter name assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()) .withReasonPhrase(HttpStatusCode.NOT_FOUND_404.reasonPhrase()), makeRequest( request() .withMethod("GET") .withPath(calculatePath("some_pathRequest")) .withHeaders( header("requestHeaderNameOne", "requestHeaderValueOne"), header("requestHeaderNameTwo", "requestHeaderValueTwo") ), headersToIgnore) ); // wrong query string parameter name assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()) .withReasonPhrase(HttpStatusCode.NOT_FOUND_404.reasonPhrase()), makeRequest( request() .withMethod("GET") .withPath(calculatePath("some_pathRequest")) .withHeaders( header("requestHeaderNameOne", "requestHeaderValueOne"), header("requestHeaderNameTwo", "requestHeaderValueTwo") ), headersToIgnore) ); } @Test public void shouldVerifyReceivedRequestInSsl() { // when mockServerClient .when( request() .withPath(calculatePath("some.*path")), exactly(2) ) .respond( response() .withBody("some_body") ); // then // - in http assertEquals( response() .withStatusCode(OK_200.code()) .withReasonPhrase(OK_200.reasonPhrase()) .withBody("some_body"), makeRequest( request() .withPath(calculatePath("some_path")), headersToIgnore) ); mockServerClient.verify(request() .withPath(calculatePath("some_path")) .withSecure(false)); mockServerClient.verify(request() .withPath(calculatePath("some_path")) .withSecure(false), VerificationTimes.exactly(1)); // - in https assertEquals( response() .withStatusCode(OK_200.code()) .withReasonPhrase(OK_200.reasonPhrase()) .withBody("some_body"), makeRequest( request() .withPath(calculatePath("some_secure_path")) .withSecure(true), headersToIgnore) ); mockServerClient.verify(request() .withPath(calculatePath("some_secure_path")) .withSecure(true)); mockServerClient.verify(request() .withPath(calculatePath("some_secure_path")) .withSecure(true), VerificationTimes.exactly(1)); } @Test public void shouldVerifyReceivedRequestsWithRegexBody() { // when mockServerClient .when( request() .withMethod("POST") .withPath(calculatePath("some_path")) .withBody("{type: 'some_random_type', value: 'some_random_value'}"), exactly(2) ) .respond( response() .withBody("some_response") ); // then // - in http assertEquals( response() .withStatusCode(OK_200.code()) .withReasonPhrase(OK_200.reasonPhrase()) .withBody("some_response"), makeRequest( request() .withMethod("POST") .withPath(calculatePath("some_path")) .withBody("{type: 'some_random_type', value: 'some_random_value'}"), headersToIgnore) ); mockServerClient.verify( request() .withBody(regex("\\{type\\: \\'some_random_type\\'\\, value\\: \\'some_random_value\\'\\}")) ); mockServerClient.verify( request() .withBody(regex("\\{type\\: \\'some_random_type\\'\\, value\\: \\'some_random_value\\'\\}")), VerificationTimes.exactly(1) ); // - in https assertEquals( response() .withStatusCode(OK_200.code()) .withReasonPhrase(OK_200.reasonPhrase()) .withBody("some_response"), makeRequest( request() .withSecure(true) .withMethod("POST") .withPath(calculatePath("some_path")) .withBody("{type: 'some_random_type', value: 'some_random_value'}"), headersToIgnore) ); mockServerClient.verify( request() .withSecure(true) .withBody(regex("\\{type\\: \\'some_random_type\\'\\, value\\: \\'some_random_value\\'\\}")) ); mockServerClient.verify( request() .withSecure(true) .withBody(regex("\\{type\\: \\'some_random_type\\'\\, value\\: \\'some_random_value\\'\\}")), VerificationTimes.atLeast(1) ); } @Test public void shouldVerifyReceivedRequestsWithNoBody() { // when mockServerClient.when(request().withPath(calculatePath("some_path")), exactly(2)).respond(response()); // then // - in http assertEquals( response() .withStatusCode(OK_200.code()) .withReasonPhrase(OK_200.reasonPhrase()), makeRequest( request() .withPath(calculatePath("some_path")), headersToIgnore) ); mockServerClient.verify(request() .withPath(calculatePath("some_path"))); mockServerClient.verify(request() .withPath(calculatePath("some_path")), VerificationTimes.exactly(1)); } @Test public void shouldVerifyReceivedRequestsWithNoMatchingExpectation() { // when makeRequest( request() .withPath(calculatePath("some_path")), headersToIgnore); mockServerClient.verify(request() .withPath(calculatePath("some_path"))); mockServerClient.verify(request() .withPath(calculatePath("some_path")), VerificationTimes.exactly(1)); mockServerClient.verify(request() .withPath(calculatePath("some_path")), VerificationTimes.once()); } @Test public void shouldVerifyTooManyRequestsReceived() { // when mockServerClient.when(request().withPath(calculatePath("some_path")), exactly(2)).respond(response().withBody("some_body")); // then assertEquals( response() .withStatusCode(OK_200.code()) .withReasonPhrase(OK_200.reasonPhrase()) .withBody("some_body"), makeRequest( request() .withPath(calculatePath("some_path")), headersToIgnore) ); try { mockServerClient.verify(request() .withPath(calculatePath("some_path")), VerificationTimes.exactly(0)); fail(); } catch (AssertionError ae) { assertThat(ae.getMessage(), startsWith("Request not found exactly 0 times, expected:<{" + NEW_LINE + " \"path\" : \"" + calculatePath("some_path") + "\"" + NEW_LINE + "}> but was:<{" + NEW_LINE + " \"method\" : \"GET\"," + NEW_LINE + " \"path\" : \"" + calculatePath("some_path") + "\"," + NEW_LINE)); } } @Test public void shouldVerifyNoMatchingRequestsReceived() { // when mockServerClient.when(request().withPath(calculatePath("some_path")), exactly(2)).respond(response().withBody("some_body")); // then assertEquals( response() .withStatusCode(OK_200.code()) .withReasonPhrase(OK_200.reasonPhrase()) .withBody("some_body"), makeRequest( request() .withPath(calculatePath("some_path")), headersToIgnore) ); try { mockServerClient.verify(request() .withPath(calculatePath("some_other_path")), VerificationTimes.exactly(2)); fail(); } catch (AssertionError ae) { assertThat(ae.getMessage(), startsWith("Request not found exactly 2 times, expected:<{" + NEW_LINE + " \"path\" : \"" + calculatePath("some_other_path") + "\"" + NEW_LINE + "}> but was:<{" + NEW_LINE + " \"method\" : \"GET\"," + NEW_LINE + " \"path\" : \"" + calculatePath("some_path") + "\"," + NEW_LINE)); } } @Test public void shouldNotVerifyNoRequestsReceived() { // when mockServerClient.when(request().withPath(calculatePath("some_path")), exactly(2)).respond(response().withBody("some_body")); // then assertEquals( response() .withStatusCode(OK_200.code()) .withReasonPhrase(OK_200.reasonPhrase()) .withBody("some_body"), makeRequest( request() .withPath(calculatePath("some_path")), headersToIgnore) ); try { mockServerClient.verifyZeroInteractions(); fail(); } catch (AssertionError ae) { assertThat(ae.getMessage(), startsWith("Request not found exactly 0 times, expected:<{ }> but was:<{" + NEW_LINE + " \"method\" : \"GET\"," + NEW_LINE + " \"path\" : \"" + calculatePath("some_path") + "\"," + NEW_LINE)); } } @Test public void shouldVerifyNoMatchingRequestsReceivedInSsl() { // when mockServerClient.when(request().withPath(calculatePath("some.*path")), exactly(2)).respond(response().withBody("some_body")); // then // - in http assertEquals( response() .withStatusCode(OK_200.code()) .withReasonPhrase(OK_200.reasonPhrase()) .withBody("some_body"), makeRequest( request() .withPath(calculatePath("some_path")), headersToIgnore) ); try { mockServerClient.verify( request() .withPath(calculatePath("some_path")) .withSecure(true), VerificationTimes.atLeast(1) ); fail(); } catch (AssertionError ae) { assertThat(ae.getMessage(), startsWith("Request not found at least once, expected:<{" + NEW_LINE + " \"path\" : \"" + calculatePath("some_path") + "\"," + NEW_LINE + " \"secure\" : true" + NEW_LINE + "}> but was:<{" + NEW_LINE + " \"method\" : \"GET\"," + NEW_LINE + " \"path\" : \"" + calculatePath("some_path") + "\"," + NEW_LINE)); } // - in https assertEquals( response() .withStatusCode(OK_200.code()) .withReasonPhrase(OK_200.reasonPhrase()) .withBody("some_body"), makeRequest( request() .withPath(calculatePath("some_secure_path")) .withSecure(true), headersToIgnore) ); try { mockServerClient.verify( request() .withPath(calculatePath("some_secure_path")) .withSecure(false), VerificationTimes.atLeast(1) ); fail(); } catch (AssertionError ae) { assertThat(ae.getMessage(), startsWith("Request not found at least once, expected:<{" + NEW_LINE + " \"path\" : \"" + calculatePath("some_secure_path") + "\"," + NEW_LINE + " \"secure\" : false" + NEW_LINE + "}> but was:<[ {" + NEW_LINE + " \"method\" : \"GET\"," + NEW_LINE + " \"path\" : \"" + calculatePath("some_path") + "\"," + NEW_LINE)); } } @Test public void shouldVerifySequenceOfRequestsReceivedIncludingThoseNotMatchingAnException() { // when mockServerClient.when(request().withPath(calculatePath("some_path.*")), exactly(4)).respond(response().withBody("some_body")); // then assertEquals( response("some_body"), makeRequest( request().withPath(calculatePath("some_path_one")), headersToIgnore) ); assertEquals( notFoundResponse(), makeRequest( request().withPath(calculatePath("not_found")), headersToIgnore) ); assertEquals( response("some_body"), makeRequest( request().withPath(calculatePath("some_path_three")), headersToIgnore) ); mockServerClient.verify(request(calculatePath("some_path_one")), request(calculatePath("some_path_three"))); mockServerClient.verify(request(calculatePath("some_path_one")), request(calculatePath("not_found"))); mockServerClient.verify(request(calculatePath("some_path_one")), request(calculatePath("not_found")), request(calculatePath("some_path_three"))); mockServerClient.verify(request(calculatePath("some_path_one")), request(calculatePath("not_found")), request(calculatePath("some_path_three"))); } @Test public void shouldVerifySequenceOfRequestsNotReceived() { // when mockServerClient.when(request().withPath(calculatePath("some_path.*")), exactly(6)).respond(response().withBody("some_body")); // then assertEquals( response("some_body"), makeRequest( request().withPath(calculatePath("some_path_one")), headersToIgnore) ); assertEquals( response("some_body"), makeRequest( request().withPath(calculatePath("some_path_two")), headersToIgnore) ); assertEquals( response("some_body"), makeRequest( request().withPath(calculatePath("some_path_three")), headersToIgnore) ); try { mockServerClient.verify(request(calculatePath("some_path_two")), request(calculatePath("some_path_one"))); fail(); } catch (AssertionError ae) { assertThat(ae.getMessage(), startsWith("Request sequence not found, expected:<[ {" + NEW_LINE + " \"path\" : \"" + calculatePath("some_path_two") + "\"" + NEW_LINE + "}, {" + NEW_LINE + " \"path\" : \"" + calculatePath("some_path_one") + "\"" + NEW_LINE + "} ]> but was:<[ {" + NEW_LINE + " \"method\" : \"GET\"," + NEW_LINE + " \"path\" : \"" + calculatePath("some_path_one") + "\"," + NEW_LINE)); } try { mockServerClient.verify(request(calculatePath("some_path_three")), request(calculatePath("some_path_two"))); fail(); } catch (AssertionError ae) { assertThat(ae.getMessage(), startsWith("Request sequence not found, expected:<[ {" + NEW_LINE + " \"path\" : \"" + calculatePath("some_path_three") + "\"" + NEW_LINE + "}, {" + NEW_LINE + " \"path\" : \"" + calculatePath("some_path_two") + "\"" + NEW_LINE + "} ]> but was:<[ {" + NEW_LINE + " \"method\" : \"GET\"," + NEW_LINE + " \"path\" : \"" + calculatePath("some_path_one") + "\"," + NEW_LINE)); } try { mockServerClient.verify(request(calculatePath("some_path_four"))); fail(); } catch (AssertionError ae) { assertThat(ae.getMessage(), startsWith("Request sequence not found, expected:<[ {" + NEW_LINE + " \"path\" : \"" + calculatePath("some_path_four") + "\"" + NEW_LINE + "} ]> but was:<[ {" + NEW_LINE + " \"method\" : \"GET\"," + NEW_LINE + " \"path\" : \"" + calculatePath("some_path_one") + "\"," + NEW_LINE)); } } @Test public void shouldRetrieveRecordedRequestsAsJson() { // when mockServerClient.when(request().withPath(calculatePath("some_path.*")), exactly(4)).respond(response().withBody("some_body")); assertEquals( response("some_body"), makeRequest( request().withPath(calculatePath("some_path_one")), headersToIgnore) ); assertEquals( notFoundResponse(), makeRequest( request().withPath(calculatePath("not_found")), headersToIgnore) ); assertEquals( response("some_body"), makeRequest( request().withPath(calculatePath("some_path_three")), headersToIgnore) ); // then verifyRequestsMatches( new HttpRequestSerializer(new MockServerLogger()).deserializeArray(mockServerClient.retrieveRecordedRequests(request().withPath(calculatePath("some_path.*")), Format.JSON)), request(calculatePath("some_path_one")), request(calculatePath("some_path_three")) ); verifyRequestsMatches( new HttpRequestSerializer(new MockServerLogger()).deserializeArray(mockServerClient.retrieveRecordedRequests(request(), Format.JSON)), request(calculatePath("some_path_one")), request(calculatePath("not_found")), request(calculatePath("some_path_three")) ); verifyRequestsMatches( new HttpRequestSerializer(new MockServerLogger()).deserializeArray(mockServerClient.retrieveRecordedRequests(null, Format.JSON)), request(calculatePath("some_path_one")), request(calculatePath("not_found")), request(calculatePath("some_path_three")) ); } @Test public void shouldRetrieveRecordedRequestsAsLogEntries() { // given mockServerClient.when(request().withPath(calculatePath("some_path.*")), exactly(4)).respond(response().withBody("some_body")); assertEquals( response("some_body"), makeRequest( request().withPath(calculatePath("some_path_one")), headersToIgnore) ); assertEquals( notFoundResponse(), makeRequest( request().withPath(calculatePath("not_found")), headersToIgnore) ); assertEquals( response("some_body"), makeRequest( request().withPath(calculatePath("some_path_three")), headersToIgnore) ); // when String logEntriesActual = mockServerClient.retrieveRecordedRequests(request().withPath(calculatePath("some_path.*")), Format.LOG_ENTRIES); HttpRequest requestOne = request("/some_path_one") .withMethod("GET") .withHeader("host", "localhost:" + this.getServerPort()) .withHeader("accept-encoding", "gzip,deflate") .withHeader("content-length", "0") .withHeader("connection", "keep-alive") .withKeepAlive(true) .withSecure(false); HttpRequest requestTwo = request("/some_path_three") .withMethod("GET") .withHeader("host", "localhost:" + this.getServerPort()) .withHeader("accept-encoding", "gzip,deflate") .withHeader("content-length", "0") .withHeader("connection", "keep-alive") .withKeepAlive(true) .withSecure(false); List<LogEntry> logEntriesExpected = Arrays.asList( new LogEntry() .setType(RECEIVED_REQUEST) .setLogLevel(Level.INFO) .setHttpRequest(requestOne) .setMessageFormat("received request:{}") .setArguments(requestOne), new LogEntry() .setType(RECEIVED_REQUEST) .setLogLevel(Level.INFO) .setHttpRequest(requestTwo) .setMessageFormat("received request:{}") .setArguments(requestTwo) ); // then assertThat(logEntriesActual, is(new LogEntrySerializer(new MockServerLogger()).serialize(logEntriesExpected))); } @Test public void shouldRetrieveActiveExpectationsAsJson() { // when mockServerClient.when(request().withPath(calculatePath("some_path.*")), exactly(4)) .respond(response().withBody("some_body")); mockServerClient.when(request().withPath(calculatePath("some_path.*"))) .respond(response().withBody("some_body")); mockServerClient.when(request().withPath(calculatePath("some_other_path"))) .respond(response().withBody("some_other_body")); mockServerClient.when(request().withPath(calculatePath("some_forward_path"))) .forward(forward()); // then assertThat( mockServerClient.retrieveActiveExpectations(request().withPath(calculatePath("some_path.*")), Format.JSON), is(new ExpectationSerializer(new MockServerLogger()).serialize(Arrays.asList( new Expectation(request().withPath(calculatePath("some_path.*")), exactly(4), TimeToLive.unlimited()) .thenRespond(response().withBody("some_body")), new Expectation(request().withPath(calculatePath("some_path.*"))) .thenRespond(response().withBody("some_body")) ))) ); assertThat( mockServerClient.retrieveActiveExpectations(null, Format.JSON), is(new ExpectationSerializer(new MockServerLogger()).serialize(Arrays.asList( new Expectation(request().withPath(calculatePath("some_path.*")), exactly(4), TimeToLive.unlimited()) .thenRespond(response().withBody("some_body")), new Expectation(request().withPath(calculatePath("some_path.*"))) .thenRespond(response().withBody("some_body")), new Expectation(request().withPath(calculatePath("some_other_path"))) .thenRespond(response().withBody("some_other_body")), new Expectation(request().withPath(calculatePath("some_forward_path"))) .thenForward(forward()) ))) ); assertThat( mockServerClient.retrieveActiveExpectations(request(), Format.JSON), is(new ExpectationSerializer(new MockServerLogger()).serialize(Arrays.asList( new Expectation(request().withPath(calculatePath("some_path.*")), exactly(4), TimeToLive.unlimited()) .thenRespond(response().withBody("some_body")), new Expectation(request().withPath(calculatePath("some_path.*"))) .thenRespond(response().withBody("some_body")), new Expectation(request().withPath(calculatePath("some_other_path"))) .thenRespond(response().withBody("some_other_body")), new Expectation(request().withPath(calculatePath("some_forward_path"))) .thenForward(forward()) ))) ); } @Test public void shouldRetrieveActiveExpectationsAsJava() { // when mockServerClient.when(request().withPath(calculatePath("some_path.*")), exactly(4)) .respond(response().withBody("some_body")); mockServerClient.when(request().withPath(calculatePath("some_path.*"))) .respond(response().withBody("some_body")); mockServerClient.when(request().withPath(calculatePath("some_other_path"))) .respond(response().withBody("some_other_body")); mockServerClient.when(request().withPath(calculatePath("some_forward_path"))) .forward(forward()); // then assertThat( mockServerClient.retrieveActiveExpectations(request().withPath(calculatePath("some_path.*")), Format.JAVA), is(new ExpectationToJavaSerializer().serialize(Arrays.asList( new Expectation(request().withPath(calculatePath("some_path.*")), exactly(4), TimeToLive.unlimited()) .thenRespond(response().withBody("some_body")), new Expectation(request().withPath(calculatePath("some_path.*"))) .thenRespond(response().withBody("some_body")) ))) ); assertThat( mockServerClient.retrieveActiveExpectations(null, Format.JAVA), is(new ExpectationToJavaSerializer().serialize(Arrays.asList( new Expectation(request().withPath(calculatePath("some_path.*")), exactly(4), TimeToLive.unlimited()) .thenRespond(response().withBody("some_body")), new Expectation(request().withPath(calculatePath("some_path.*"))) .thenRespond(response().withBody("some_body")), new Expectation(request().withPath(calculatePath("some_other_path"))) .thenRespond(response().withBody("some_other_body")), new Expectation(request().withPath(calculatePath("some_forward_path"))) .thenForward(forward()) ))) ); assertThat( mockServerClient.retrieveActiveExpectations(request(), Format.JAVA), is(new ExpectationToJavaSerializer().serialize(Arrays.asList( new Expectation(request().withPath(calculatePath("some_path.*")), exactly(4), TimeToLive.unlimited()) .thenRespond(response().withBody("some_body")), new Expectation(request().withPath(calculatePath("some_path.*"))) .thenRespond(response().withBody("some_body")), new Expectation(request().withPath(calculatePath("some_other_path"))) .thenRespond(response().withBody("some_other_body")), new Expectation(request().withPath(calculatePath("some_forward_path"))) .thenForward(forward()) ))) ); } @Test public void shouldRetrieveRecordedExpectationsAsJson() { // when mockServerClient.when(request().withPath(calculatePath("some_path.*")), exactly(4)).forward( forward() .withHost("127.0.0.1") .withPort(insecureEchoServer.getPort()) ); assertEquals( response("some_body_one"), makeRequest( request().withPath(calculatePath("some_path_one")).withBody("some_body_one"), headersToIgnore ) ); assertEquals( response("some_body_three"), makeRequest( request().withPath(calculatePath("some_path_three")).withBody("some_body_three"), headersToIgnore ) ); // then Expectation[] recordedExpectations = new ExpectationSerializer(new MockServerLogger()).deserializeArray( mockServerClient.retrieveRecordedExpectations(request().withPath(calculatePath("some_path_one")), Format.JSON) ); assertThat(recordedExpectations.length, is(1)); verifyRequestsMatches( new HttpRequest[]{ recordedExpectations[0].getHttpRequest() }, request(calculatePath("some_path_one")).withBody("some_body_one") ); assertThat(recordedExpectations[0].getHttpResponse().getBodyAsString(), is("some_body_one")); // and recordedExpectations = new ExpectationSerializer(new MockServerLogger()).deserializeArray( mockServerClient.retrieveRecordedExpectations(request(), Format.JSON) ); assertThat(recordedExpectations.length, is(2)); verifyRequestsMatches( new HttpRequest[]{ recordedExpectations[0].getHttpRequest(), recordedExpectations[1].getHttpRequest() }, request(calculatePath("some_path_one")).withBody("some_body_one"), request(calculatePath("some_path_three")).withBody("some_body_three") ); assertThat(recordedExpectations[0].getHttpResponse().getBodyAsString(), is("some_body_one")); assertThat(recordedExpectations[1].getHttpResponse().getBodyAsString(), is("some_body_three")); // and recordedExpectations = new ExpectationSerializer(new MockServerLogger()).deserializeArray( mockServerClient.retrieveRecordedExpectations(null, Format.JSON) ); assertThat(recordedExpectations.length, is(2)); verifyRequestsMatches( new HttpRequest[]{ recordedExpectations[0].getHttpRequest(), recordedExpectations[1].getHttpRequest() }, request(calculatePath("some_path_one")).withBody("some_body_one"), request(calculatePath("some_path_three")).withBody("some_body_three") ); assertThat(recordedExpectations[0].getHttpResponse().getBodyAsString(), is("some_body_one")); assertThat(recordedExpectations[1].getHttpResponse().getBodyAsString(), is("some_body_three")); } @Test public void shouldClearExpectationsOnly() { // given - some expectations mockServerClient .when( request() .withPath(calculatePath("some_path1")) ) .respond( response() .withBody("some_body1") ); mockServerClient .when( request() .withPath(calculatePath("some_path2")) ) .respond( response() .withBody("some_body2") ); // and - some matching requests assertEquals( response() .withStatusCode(OK_200.code()) .withReasonPhrase(OK_200.reasonPhrase()) .withBody("some_body1"), makeRequest( request() .withPath(calculatePath("some_path1")), headersToIgnore) ); assertEquals( response() .withStatusCode(OK_200.code()) .withReasonPhrase(OK_200.reasonPhrase()) .withBody("some_body2"), makeRequest( request() .withPath(calculatePath("some_path2")), headersToIgnore) ); // when mockServerClient .clear( request() .withPath(calculatePath("some_path1")), ClearType.EXPECTATIONS ); // then - expectations cleared assertThat( mockServerClient.retrieveActiveExpectations(null), arrayContaining( new Expectation(request() .withPath(calculatePath("some_path2"))) .thenRespond( response() .withBody("some_body2") ) ) ); // and then - request log not cleared verifyRequestsMatches( mockServerClient.retrieveRecordedRequests(null), request(calculatePath("some_path1")), request(calculatePath("some_path2")) ); } @Test public void shouldClearLogsOnly() { // given - some expectations mockServerClient .when( request() .withPath(calculatePath("some_path1")) ) .respond( response() .withBody("some_body1") ); mockServerClient .when( request() .withPath(calculatePath("some_path2")) ) .respond( response() .withBody("some_body2") ); // and - some matching requests assertEquals( response() .withStatusCode(OK_200.code()) .withReasonPhrase(OK_200.reasonPhrase()) .withBody("some_body1"), makeRequest( request() .withPath(calculatePath("some_path1")), headersToIgnore) ); assertEquals( response() .withStatusCode(OK_200.code()) .withReasonPhrase(OK_200.reasonPhrase()) .withBody("some_body2"), makeRequest( request() .withPath(calculatePath("some_path2")), headersToIgnore) ); // when mockServerClient .clear( request() .withPath(calculatePath("some_path1")), ClearType.LOG ); // then - expectations cleared assertThat( mockServerClient.retrieveActiveExpectations(null), arrayContaining( new Expectation(request() .withPath(calculatePath("some_path1"))) .thenRespond( response() .withBody("some_body1") ), new Expectation(request() .withPath(calculatePath("some_path2"))) .thenRespond( response() .withBody("some_body2") ) ) ); // and then - request log cleared verifyRequestsMatches( mockServerClient.retrieveRecordedRequests(null), request(calculatePath("some_path2")) ); } @Test public void shouldClearAllExpectationsWithNull() { // given mockServerClient .when( request() .withPath(calculatePath("some_path1")) ) .respond( response() .withBody("some_body1") ); mockServerClient .when( request() .withPath(calculatePath("some_path2")) ) .respond( response() .withBody("some_body2") ); assertEquals( response() .withStatusCode(OK_200.code()) .withReasonPhrase(OK_200.reasonPhrase()) .withBody("some_body2"), makeRequest( request() .withPath(calculatePath("some_path2")), headersToIgnore) ); // when mockServerClient.clear(null); // then assertThat(mockServerClient.retrieveActiveExpectations(null), emptyArray()); assertThat(mockServerClient.retrieveRecordedRequests(null), emptyArray()); } @Test public void shouldClearAllExpectationsWithEmptyRequest() { // given mockServerClient .when( request() .withPath(calculatePath("some_path1")) ) .respond( response() .withBody("some_body1") ); mockServerClient .when( request() .withPath(calculatePath("some_path2")) ) .respond( response() .withBody("some_body2") ); assertEquals( response() .withStatusCode(OK_200.code()) .withReasonPhrase(OK_200.reasonPhrase()) .withBody("some_body2"), makeRequest( request() .withPath(calculatePath("some_path2")), headersToIgnore) ); // when mockServerClient.clear(request()); // then assertThat(mockServerClient.retrieveActiveExpectations(null), emptyArray()); assertThat(mockServerClient.retrieveRecordedRequests(null), emptyArray()); } @Test public void shouldClearExpectationsWithXPathBody() { // given mockServerClient .when( request() .withBody(xpath("/bookstore/book[year=2005]/price")) ) .respond( response() .withBody("some_body1") ); mockServerClient .when( request() .withBody(xpath("/bookstore/book[year=2006]/price")) ) .respond( response() .withBody("some_body2") ); // and StringBody xmlBody = new StringBody("" + "<?xml version=\"1.0\" encoding=\"ISO-8859-1\"?>" + NEW_LINE + "<bookstore>" + NEW_LINE + " <book category=\"COOKING\">" + NEW_LINE + " <title lang=\"en\">Everyday Italian</title>" + NEW_LINE + " <author>Giada De Laurentiis</author>" + NEW_LINE + " <year>2005</year>" + NEW_LINE + " <price>30.00</price>" + NEW_LINE + " </book>" + NEW_LINE + " <book category=\"CHILDREN\">" + NEW_LINE + " <title lang=\"en\">Harry Potter</title>" + NEW_LINE + " <author>J K. Rowling</author>" + NEW_LINE + " <year>2006</year>" + NEW_LINE + " <price>29.99</price>" + NEW_LINE + " </book>" + NEW_LINE + " <book category=\"WEB\">" + NEW_LINE + " <title lang=\"en\">Learning XML</title>" + NEW_LINE + " <author>Erik T. Ray</author>" + NEW_LINE + " <year>2003</year>" + NEW_LINE + " <price>31.95</price>" + NEW_LINE + " </book>" + NEW_LINE + "</bookstore>"); // then assertEquals( response() .withStatusCode(OK_200.code()) .withReasonPhrase(OK_200.reasonPhrase()) .withBody("some_body1"), makeRequest( request() .withBody(xmlBody), headersToIgnore) ); // when mockServerClient .clear( request() .withBody(xpath("/bookstore/book[year=2005]/price")) ); // then assertThat( mockServerClient.retrieveActiveExpectations(null), arrayContaining( new Expectation(request() .withBody(xpath("/bookstore/book[year=2006]/price"))) .thenRespond( response() .withBody("some_body2") ) ) ); // - in http assertEquals( response() .withStatusCode(OK_200.code()) .withReasonPhrase(OK_200.reasonPhrase()) .withBody("some_body2"), makeRequest( request() .withBody(xmlBody), headersToIgnore) ); // - in https assertEquals( response() .withStatusCode(OK_200.code()) .withReasonPhrase(OK_200.reasonPhrase()) .withBody("some_body2"), makeRequest( request() .withSecure(true) .withBody(xmlBody), headersToIgnore) ); } @Test public void shouldClearExpectationsWithJsonSchemaBody() { // given JsonSchemaBody jsonSchemaBodyOne = jsonSchema("{" + NEW_LINE + " \"$schema\": \"http://json-schema.org/draft-04/schema#\"," + NEW_LINE + " \"title\": \"Product\"," + NEW_LINE + " \"description\": \"A product from Acme's catalog\"," + NEW_LINE + " \"type\": \"object\"," + NEW_LINE + " \"properties\": {" + NEW_LINE + " \"id\": {" + NEW_LINE + " \"description\": \"The unique identifier for a product\"," + NEW_LINE + " \"type\": \"integer\"" + NEW_LINE + " }," + NEW_LINE + " \"name\": {" + NEW_LINE + " \"description\": \"Name of the product\"," + NEW_LINE + " \"type\": \"string\"" + NEW_LINE + " }," + NEW_LINE + " \"price\": {" + NEW_LINE + " \"type\": \"number\"," + NEW_LINE + " \"minimum\": 0," + NEW_LINE + " \"exclusiveMinimum\": true" + NEW_LINE + " }," + NEW_LINE + " \"tags\": {" + NEW_LINE + " \"type\": \"array\"," + NEW_LINE + " \"items\": {" + NEW_LINE + " \"type\": \"string\"" + NEW_LINE + " }," + NEW_LINE + " \"minItems\": 1," + NEW_LINE + " \"uniqueItems\": true" + NEW_LINE + " }" + NEW_LINE + " }," + NEW_LINE + " \"required\": [\"id\", \"name\", \"price\"]" + NEW_LINE + "}"); JsonSchemaBody jsonSchemaBodyTwo = jsonSchema("{" + NEW_LINE + " \"$schema\": \"http://json-schema.org/draft-04/schema#\"," + NEW_LINE + " \"title\": \"Product\"," + NEW_LINE + " \"description\": \"A product from Acme's catalog\"," + NEW_LINE + " \"type\": \"object\"," + NEW_LINE + " \"properties\": {" + NEW_LINE + " \"id\": {" + NEW_LINE + " \"description\": \"The unique identifier for a product\"," + NEW_LINE + " \"type\": \"integer\"" + NEW_LINE + " }," + NEW_LINE + " \"name\": {" + NEW_LINE + " \"description\": \"Name of the product\"," + NEW_LINE + " \"type\": \"string\"" + NEW_LINE + " }," + NEW_LINE + " \"price\": {" + NEW_LINE + " \"type\": \"number\"," + NEW_LINE + " \"minimum\": 10," + NEW_LINE + " \"exclusiveMinimum\": true" + NEW_LINE + " }," + NEW_LINE + " \"tags\": {" + NEW_LINE + " \"type\": \"array\"," + NEW_LINE + " \"items\": {" + NEW_LINE + " \"type\": \"string\"" + NEW_LINE + " }," + NEW_LINE + " \"minItems\": 1," + NEW_LINE + " \"uniqueItems\": true" + NEW_LINE + " }" + NEW_LINE + " }," + NEW_LINE + " \"required\": [\"id\", \"name\", \"price\"]" + NEW_LINE + "}"); mockServerClient .when( request() .withBody(jsonSchemaBodyOne) ) .respond( response() .withBody("some_body1") ); mockServerClient .when( request() .withBody(jsonSchemaBodyTwo) ) .respond( response() .withBody("some_body2") ); // then assertEquals( response() .withStatusCode(OK_200.code()) .withReasonPhrase(OK_200.reasonPhrase()) .withBody("some_body1"), makeRequest( request() .withBody("{" + NEW_LINE + " \"id\": 1," + NEW_LINE + " \"name\": \"A green door\"," + NEW_LINE + " \"price\": 12.50," + NEW_LINE + " \"tags\": [\"home\", \"green\"]" + NEW_LINE + "}"), headersToIgnore) ); // when mockServerClient .clear( request() .withBody(jsonSchemaBodyOne) ); // then assertThat( mockServerClient.retrieveActiveExpectations(null), arrayContaining( new Expectation(request() .withBody(jsonSchemaBodyTwo)) .thenRespond( response() .withBody("some_body2") ) ) ); // - in http assertEquals( response() .withStatusCode(OK_200.code()) .withReasonPhrase(OK_200.reasonPhrase()) .withBody("some_body2"), makeRequest( request() .withBody("{" + NEW_LINE + " \"id\": 1," + NEW_LINE + " \"name\": \"A green door\"," + NEW_LINE + " \"price\": 12.50," + NEW_LINE + " \"tags\": [\"home\", \"green\"]" + NEW_LINE + "}"), headersToIgnore) ); // - in https assertEquals( response() .withStatusCode(OK_200.code()) .withReasonPhrase(OK_200.reasonPhrase()) .withBody("some_body2"), makeRequest( request() .withSecure(true) .withBody("{" + NEW_LINE + " \"id\": 1," + NEW_LINE + " \"name\": \"A green door\"," + NEW_LINE + " \"price\": 12.50," + NEW_LINE + " \"tags\": [\"home\", \"green\"]" + NEW_LINE + "}"), headersToIgnore) ); } @Test public void shouldClearExpectationsWithParameterBody() { // given mockServerClient .when( request() .withBody(params(param("bodyParameterNameOne", "bodyParameterValueOne"))) ) .respond( response() .withBody("some_body1") ); mockServerClient .when( request() .withBody(params(param("bodyParameterNameTwo", "bodyParameterValueTwo"))) ) .respond( response() .withBody("some_body2") ); // then assertEquals( response() .withStatusCode(OK_200.code()) .withReasonPhrase(OK_200.reasonPhrase()) .withBody("some_body1"), makeRequest( request() .withBody(params(param("bodyParameterNameOne", "bodyParameterValueOne"))), headersToIgnore) ); // when mockServerClient .clear( request() .withBody(params(param("bodyParameterNameOne", "bodyParameterValueOne"))) ); // then assertThat( mockServerClient.retrieveActiveExpectations(null), arrayContaining( new Expectation(request() .withBody(params(param("bodyParameterNameTwo", "bodyParameterValueTwo")))) .thenRespond( response() .withBody("some_body2") ) ) ); // - in http assertEquals( response() .withStatusCode(OK_200.code()) .withReasonPhrase(OK_200.reasonPhrase()) .withBody("some_body2"), makeRequest( request() .withBody(params(param("bodyParameterNameTwo", "bodyParameterValueTwo"))), headersToIgnore) ); // - in https assertEquals( response() .withStatusCode(NOT_FOUND_404.code()) .withReasonPhrase(NOT_FOUND_404.reasonPhrase()), makeRequest( request() .withBody(params(param("bodyParameterNameOne", "bodyParameterValueOne"))), headersToIgnore) ); } @Test public void shouldEnsureThatInterruptedRequestsAreVerifiable() { mockServerClient .when( request(calculatePath("delayed")) ) .respond( response("delayed data") .withDelay(new Delay(TimeUnit.SECONDS, 3)) ); Future<HttpResponse> delayedFuture = Executors.newSingleThreadExecutor().submit(() -> httpClient.sendRequest( request(addContextToPath(calculatePath("delayed"))) .withHeader(HOST.toString(), "localhost:" + getServerPort()) ).get(10, TimeUnit.SECONDS)); Uninterruptibles.sleepUninterruptibly(1, TimeUnit.SECONDS); // Let request reach server delayedFuture.cancel(true); // Then interrupt requesting thread mockServerClient.verify(request(calculatePath("delayed"))); // We should be able to verify request that reached server even though its later interrupted } @Test public void shouldEnsureThatRequestDelaysDoNotAffectOtherRequests() throws Exception { mockServerClient .when( request("/slow") ) .respond( response("super slow") .withDelay(new Delay(TimeUnit.SECONDS, 5)) ); mockServerClient .when( request("/fast") ) .respond( response("quite fast") ); ExecutorService executorService = Executors.newFixedThreadPool(2); Future<Long> slowFuture = executorService.submit(() -> { long start = System.currentTimeMillis(); makeRequest(request("/slow"), Collections.emptySet()); return System.currentTimeMillis() - start; }); // Let fast request come to the server slightly after slow request Uninterruptibles.sleepUninterruptibly(1, TimeUnit.SECONDS); Future<Long> fastFuture = executorService.submit(() -> { long start = System.currentTimeMillis(); makeRequest(request("/fast"), Collections.emptySet()); return System.currentTimeMillis() - start; }); Long slowRequestElapsedMillis = slowFuture.get(); Long fastRequestElapsedMillis = fastFuture.get(); assertThat("Slow request takes less than expected", slowRequestElapsedMillis, is(greaterThan(4 * 1000L))); assertThat("Fast request takes longer than expected", fastRequestElapsedMillis, is(lessThan(1000L))); } }
adamkrol93/mockserver
mockserver-integration-testing/src/main/java/org/mockserver/integration/server/AbstractExtendedMockingIntegrationTest.java
938
package org.mockserver.integration.server; import com.google.common.util.concurrent.Uninterruptibles; import io.netty.util.CharsetUtil; import org.apache.commons.io.IOUtils; import org.junit.BeforeClass; import org.junit.Test; import org.mockserver.log.TimeService; import org.mockserver.log.model.LogEntry; import org.mockserver.logging.MockServerLogger; import org.mockserver.matchers.MatchType; import org.mockserver.matchers.TimeToLive; import org.mockserver.mock.Expectation; import org.mockserver.model.*; import org.mockserver.serialization.ExpectationSerializer; import org.mockserver.serialization.HttpRequestSerializer; import org.mockserver.serialization.LogEntrySerializer; import org.mockserver.serialization.java.ExpectationToJavaSerializer; import org.mockserver.verify.VerificationTimes; import org.slf4j.event.Level; import java.io.IOException; import java.nio.charset.StandardCharsets; import java.util.Arrays; import java.util.Collections; import java.util.List; import java.util.concurrent.*; import static io.netty.handler.codec.http.HttpHeaderNames.*; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.*; import static org.hamcrest.core.Is.is; import static org.hamcrest.core.StringStartsWith.startsWith; import static org.hamcrest.number.OrderingComparison.greaterThan; import static org.junit.Assert.assertEquals; import static org.junit.Assert.fail; import static org.mockserver.character.Character.NEW_LINE; import static org.mockserver.log.model.LogEntry.LogMessageType.RECEIVED_REQUEST; import static org.mockserver.matchers.Times.exactly; import static org.mockserver.model.BinaryBody.binary; import static org.mockserver.model.Cookie.cookie; import static org.mockserver.model.Header.header; import static org.mockserver.model.HttpForward.forward; import static org.mockserver.model.HttpRequest.request; import static org.mockserver.model.HttpResponse.notFoundResponse; import static org.mockserver.model.HttpResponse.response; import static org.mockserver.model.HttpStatusCode.*; import static org.mockserver.model.JsonBody.json; import static org.mockserver.model.JsonPathBody.jsonPath; import static org.mockserver.model.JsonSchemaBody.jsonSchema; import static org.mockserver.model.NottableString.not; import static org.mockserver.model.NottableString.string; import static org.mockserver.model.Parameter.param; import static org.mockserver.model.ParameterBody.params; import static org.mockserver.model.RegexBody.regex; import static org.mockserver.model.StringBody.exact; import static org.mockserver.model.StringBody.subString; import static org.mockserver.model.XPathBody.xpath; import static org.mockserver.model.XmlBody.xml; import static org.mockserver.model.XmlSchemaBody.xmlSchema; import static org.mockserver.model.XmlSchemaBody.xmlSchemaFromResource; /** * @author jamesdbloom */ public abstract class AbstractExtendedMockingIntegrationTest extends AbstractBasicMockingIntegrationTest { @BeforeClass public static void fixTime() { TimeService.fixedTime = true; } @Test public void shouldReturnResponseForRequestInSsl() { // when mockServerClient.when(request().withSecure(true)).respond(response().withBody("some_body")); // then // - in http assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()) .withReasonPhrase(HttpStatusCode.NOT_FOUND_404.reasonPhrase()), makeRequest( request() .withPath(calculatePath("")), headersToIgnore) ); // - in https assertEquals( response() .withStatusCode(OK_200.code()) .withReasonPhrase(OK_200.reasonPhrase()) .withBody("some_body"), makeRequest( request() .withSecure(true) .withPath(calculatePath("")), headersToIgnore) ); } @Test public void shouldReturnResponseForRequestNotInSsl() { // when mockServerClient.when(request().withSecure(false)).respond(response().withBody("some_body")); // then // - in http assertEquals( response() .withStatusCode(OK_200.code()) .withReasonPhrase(OK_200.reasonPhrase()) .withBody("some_body"), makeRequest( request() .withPath(calculatePath("")), headersToIgnore) ); // - in https assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()) .withReasonPhrase(HttpStatusCode.NOT_FOUND_404.reasonPhrase()), makeRequest( request() .withSecure(true) .withPath(calculatePath("")), headersToIgnore) ); } @Test public void shouldReturnResponseByMatchingPath() { // when mockServerClient .when( request() .withPath(calculatePath("some_path1")) ) .respond( response() .withBody("some_body1") ); mockServerClient .when( request() .withPath(calculatePath("some_path2")) ) .respond( response() .withBody("some_body2") ); // then // - in http assertEquals( response() .withStatusCode(OK_200.code()) .withReasonPhrase(OK_200.reasonPhrase()) .withBody("some_body2"), makeRequest( request() .withPath(calculatePath("some_path2")), headersToIgnore) ); assertEquals( response() .withStatusCode(OK_200.code()) .withReasonPhrase(OK_200.reasonPhrase()) .withBody("some_body1"), makeRequest( request() .withPath(calculatePath("some_path1")), headersToIgnore) ); // - in https assertEquals( response() .withStatusCode(OK_200.code()) .withReasonPhrase(OK_200.reasonPhrase()) .withBody("some_body2"), makeRequest( request() .withSecure(true) .withPath(calculatePath("some_path2")), headersToIgnore) ); assertEquals( response() .withStatusCode(OK_200.code()) .withReasonPhrase(OK_200.reasonPhrase()) .withBody("some_body1"), makeRequest( request() .withSecure(true) .withPath(calculatePath("some_path1")), headersToIgnore) ); } @Test public void shouldReturnResponseByMatchingPathExactTimes() { // when mockServerClient .when( request() .withPath(calculatePath("some_path")), exactly(2) ) .respond( response() .withBody("some_body") ); // then // - in http assertEquals( response() .withStatusCode(OK_200.code()) .withReasonPhrase(OK_200.reasonPhrase()) .withBody("some_body"), makeRequest( request() .withPath(calculatePath("some_path")), headersToIgnore) ); // - in https assertEquals( response() .withStatusCode(OK_200.code()) .withReasonPhrase(OK_200.reasonPhrase()) .withBody("some_body"), makeRequest( request() .withSecure(true) .withPath(calculatePath("some_path")), headersToIgnore) ); // - in http assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()) .withReasonPhrase(HttpStatusCode.NOT_FOUND_404.reasonPhrase()), makeRequest( request() .withPath(calculatePath("some_path")), headersToIgnore) ); // - in https assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()) .withReasonPhrase(HttpStatusCode.NOT_FOUND_404.reasonPhrase()), makeRequest( request() .withSecure(true) .withPath(calculatePath("some_path")), headersToIgnore) ); } @Test public void shouldReturnResponseWhenTimeToLiveHasNotExpired() { // when mockServerClient .when( request().withPath(calculatePath("some_path")), exactly(2), TimeToLive.exactly(TimeUnit.HOURS, 1L) ) .respond( response().withBody("some_body") ); // then // - in http assertEquals( response() .withStatusCode(OK_200.code()) .withReasonPhrase(OK_200.reasonPhrase()) .withBody("some_body"), makeRequest( request() .withPath(calculatePath("some_path")), headersToIgnore) ); // - in https assertEquals( response() .withStatusCode(OK_200.code()) .withReasonPhrase(OK_200.reasonPhrase()) .withBody("some_body"), makeRequest( request() .withSecure(true) .withPath(calculatePath("some_path")), headersToIgnore) ); // - in http assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()) .withReasonPhrase(HttpStatusCode.NOT_FOUND_404.reasonPhrase()), makeRequest( request() .withPath(calculatePath("some_path")), headersToIgnore) ); // - in https assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()) .withReasonPhrase(HttpStatusCode.NOT_FOUND_404.reasonPhrase()), makeRequest( request() .withSecure(true) .withPath(calculatePath("some_path")), headersToIgnore) ); } @Test public void shouldReturnMatchRequestWithBodyInUTF16() { // when String body = "我说中国话"; mockServerClient .when( request() .withBody(body, StandardCharsets.UTF_16) ) .respond( response() .withBody(body, StandardCharsets.UTF_8) ); // then // - in http assertEquals( response() .withStatusCode(OK_200.code()) .withReasonPhrase(OK_200.reasonPhrase()) .withHeader(CONTENT_TYPE.toString(), MediaType.PLAIN_TEXT_UTF_8.toString()) .withBody(body, MediaType.PLAIN_TEXT_UTF_8), makeRequest( request() .withPath(calculatePath("")) .withBody(body, StandardCharsets.UTF_16), headersToIgnore) ); // - in https assertEquals( response() .withStatusCode(OK_200.code()) .withReasonPhrase(OK_200.reasonPhrase()) .withHeader(CONTENT_TYPE.toString(), MediaType.PLAIN_TEXT_UTF_8.toString()) .withBody(body, MediaType.PLAIN_TEXT_UTF_8), makeRequest( request() .withSecure(true) .withPath(calculatePath("")) .withBody(body, StandardCharsets.UTF_16), headersToIgnore) ); } @Test public void shouldReturnMatchRequestWithBodyInUTF8WithContentTypeHeader() { // when String body = "我说中国话"; mockServerClient .when( request() .withHeader(CONTENT_TYPE.toString(), MediaType.PLAIN_TEXT_UTF_8.toString()) .withBody(body) ) .respond( response() .withBody(body, StandardCharsets.UTF_8) ); // then // - in http assertEquals( response() .withStatusCode(OK_200.code()) .withReasonPhrase(OK_200.reasonPhrase()) .withHeader(CONTENT_TYPE.toString(), MediaType.PLAIN_TEXT_UTF_8.toString()) .withBody(body, MediaType.PLAIN_TEXT_UTF_8), makeRequest( request() .withHeader(CONTENT_TYPE.toString(), MediaType.PLAIN_TEXT_UTF_8.toString()) .withPath(calculatePath("")) .withBody(body, StandardCharsets.UTF_8), headersToIgnore) ); // - in https assertEquals( response() .withStatusCode(OK_200.code()) .withReasonPhrase(OK_200.reasonPhrase()) .withHeader(CONTENT_TYPE.toString(), MediaType.PLAIN_TEXT_UTF_8.toString()) .withBody(body, MediaType.PLAIN_TEXT_UTF_8), makeRequest( request() .withHeader(CONTENT_TYPE.toString(), MediaType.PLAIN_TEXT_UTF_8.toString()) .withSecure(true) .withPath(calculatePath("")) .withBody(body, StandardCharsets.UTF_8), headersToIgnore) ); } @Test public void shouldReturnResponseWithBodyInUTF16() { // when String body = "我说中国话"; mockServerClient .when( request() .withHeader(CONTENT_TYPE.toString(), MediaType.create("text", "plain").withCharset(StandardCharsets.UTF_16).toString()) .withBody(body) ) .respond( response() .withHeader(CONTENT_TYPE.toString(), MediaType.create("text", "plain").withCharset(StandardCharsets.UTF_16).toString()) .withBody(body, StandardCharsets.UTF_16) ); // then // - in http assertEquals( response() .withStatusCode(OK_200.code()) .withReasonPhrase(OK_200.reasonPhrase()) .withHeader(CONTENT_TYPE.toString(), MediaType.create("text", "plain").withCharset(StandardCharsets.UTF_16).toString()) .withBody(body, StandardCharsets.UTF_16), makeRequest( request() .withHeader(CONTENT_TYPE.toString(), MediaType.create("text", "plain").withCharset(StandardCharsets.UTF_16).toString()) .withPath(calculatePath("")) .withBody(body), headersToIgnore) ); // - in https assertEquals( response() .withStatusCode(OK_200.code()) .withReasonPhrase(OK_200.reasonPhrase()) .withHeader(CONTENT_TYPE.toString(), MediaType.create("text", "plain").withCharset(StandardCharsets.UTF_16).toString()) .withBody(body, StandardCharsets.UTF_16), makeRequest( request() .withHeader(CONTENT_TYPE.toString(), MediaType.create("text", "plain").withCharset(StandardCharsets.UTF_16).toString()) .withSecure(true) .withPath(calculatePath("")) .withBody(body), headersToIgnore) ); } @Test public void shouldReturnResponseWithBodyInUTF8WithContentTypeHeader() { // when String body = "我说中国话"; mockServerClient .when( request() ) .respond( response() .withHeader(CONTENT_TYPE.toString(), MediaType.PLAIN_TEXT_UTF_8.toString()) .withBody(body) ); // then // - in http assertEquals( response() .withStatusCode(OK_200.code()) .withReasonPhrase(OK_200.reasonPhrase()) .withHeader(CONTENT_TYPE.toString(), MediaType.PLAIN_TEXT_UTF_8.toString()) .withBody(body, MediaType.PLAIN_TEXT_UTF_8), makeRequest( request() .withPath(calculatePath("")), headersToIgnore) ); // - in https assertEquals( response() .withStatusCode(OK_200.code()) .withReasonPhrase(OK_200.reasonPhrase()) .withHeader(CONTENT_TYPE.toString(), MediaType.PLAIN_TEXT_UTF_8.toString()) .withBody(body, MediaType.PLAIN_TEXT_UTF_8), makeRequest( request() .withSecure(true) .withPath(calculatePath("")), headersToIgnore) ); } @Test public void shouldReturnResponseWithBodyInUTF8WithNoContentTypeHeader() { // when String body = "我说中国话"; mockServerClient .when( request() ) .respond( response() .withBody(body, CharsetUtil.UTF_8) ); // then // - in http assertEquals( response() .withStatusCode(OK_200.code()) .withReasonPhrase(OK_200.reasonPhrase()) .withHeader(CONTENT_TYPE.toString(), MediaType.PLAIN_TEXT_UTF_8.toString()) .withBody(body, CharsetUtil.UTF_8), makeRequest( request() .withPath(calculatePath("")), headersToIgnore) ); // - in https assertEquals( response() .withStatusCode(OK_200.code()) .withReasonPhrase(OK_200.reasonPhrase()) .withHeader(CONTENT_TYPE.toString(), MediaType.PLAIN_TEXT_UTF_8.toString()) .withBody(body, CharsetUtil.UTF_8), makeRequest( request() .withSecure(true) .withPath(calculatePath("")), headersToIgnore) ); } @Test public void shouldReturnResponseByMatchingSubStringBody() { // when mockServerClient .when( request() .withBody( subString("random") ), exactly(2) ) .respond( response() .withBody("some_sub_string_body_response") ); // then // - in http assertEquals( response() .withStatusCode(OK_200.code()) .withReasonPhrase(OK_200.reasonPhrase()) .withBody("some_sub_string_body_response"), makeRequest( request() .withMethod("POST") .withPath(calculatePath("some_path")) .withBody("some_random_body"), headersToIgnore) ); // - in https assertEquals( response() .withStatusCode(OK_200.code()) .withReasonPhrase(OK_200.reasonPhrase()) .withBody("some_sub_string_body_response"), makeRequest( request() .withSecure(true) .withMethod("POST") .withPath(calculatePath("some_path")) .withBody("some_random_body"), headersToIgnore) ); } @Test public void shouldReturnResponseByMatchingNotRegexBody() { // when mockServerClient .when( request() .withMethod("POST") .withBody(Body.not(regex("10\\.\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}"))) ) .respond( response() .withBody("some_not_regex_body_response") ); // then // - in http // should not match (because body matches regex) assertEquals( response() .withStatusCode(NOT_FOUND_404.code()) .withReasonPhrase(NOT_FOUND_404.reasonPhrase()), makeRequest( request() .withMethod("POST") .withBody("10.2.3.123"), headersToIgnore) ); // should match (because body doesn't matches regex) assertEquals( response() .withStatusCode(OK_200.code()) .withReasonPhrase(OK_200.reasonPhrase()) .withBody("some_not_regex_body_response"), makeRequest( request() .withMethod("POST") .withBody("10.2.3.1234"), headersToIgnore) ); // - in https // should not match (because body matches regex) assertEquals( response() .withStatusCode(NOT_FOUND_404.code()) .withReasonPhrase(NOT_FOUND_404.reasonPhrase()), makeRequest( request() .withSecure(true) .withMethod("POST") .withBody("10.2.3.123"), headersToIgnore) ); // should match (because body doesn't matches regex) assertEquals( response() .withStatusCode(OK_200.code()) .withReasonPhrase(OK_200.reasonPhrase()) .withBody("some_not_regex_body_response"), makeRequest( request() .withSecure(true) .withMethod("POST") .withBody("10.2.3.1234"), headersToIgnore) ); } @Test public void shouldReturnResponseByMatchingNotSubStringBody() { // when mockServerClient .when( request() .withMethod("POST") .withBody(Body.not(subString("some_body"))) ) .respond( response() .withBody("some_not_regex_body_response") ); // then // - in http // should not match (because body matches regex) assertEquals( response() .withStatusCode(NOT_FOUND_404.code()) .withReasonPhrase(NOT_FOUND_404.reasonPhrase()), makeRequest( request() .withMethod("POST") .withBody("some_body_full_string"), headersToIgnore) ); // should match (because body doesn't matches regex) assertEquals( response() .withStatusCode(OK_200.code()) .withReasonPhrase(OK_200.reasonPhrase()) .withBody("some_not_regex_body_response"), makeRequest( request() .withMethod("POST") .withBody("some_other_body_full_string"), headersToIgnore) ); // - in https // should not match (because body matches regex) assertEquals( response() .withStatusCode(NOT_FOUND_404.code()) .withReasonPhrase(NOT_FOUND_404.reasonPhrase()), makeRequest( request() .withSecure(true) .withMethod("POST") .withBody("some_body_full_string"), headersToIgnore) ); // should match (because body doesn't matches regex) assertEquals( response() .withStatusCode(OK_200.code()) .withReasonPhrase(OK_200.reasonPhrase()) .withBody("some_not_regex_body_response"), makeRequest( request() .withSecure(true) .withMethod("POST") .withBody("some_other_body_full_string"), headersToIgnore) ); } @Test public void shouldReturnResponseByMatchingNotExactBody() { // when mockServerClient .when( request() .withMethod("POST") .withBody(Body.not(exact("some_body"))) ) .respond( response() .withBody("some_not_regex_body_response") ); // then // - in http // should not match (because body matches regex) assertEquals( response() .withStatusCode(NOT_FOUND_404.code()) .withReasonPhrase(NOT_FOUND_404.reasonPhrase()), makeRequest( request() .withMethod("POST") .withBody("some_body"), headersToIgnore) ); // should match (because body doesn't matches regex) assertEquals( response() .withStatusCode(OK_200.code()) .withReasonPhrase(OK_200.reasonPhrase()) .withBody("some_not_regex_body_response"), makeRequest( request() .withMethod("POST") .withBody("some_other_body"), headersToIgnore) ); // - in https // should not match (because body matches regex) assertEquals( response() .withStatusCode(NOT_FOUND_404.code()) .withReasonPhrase(NOT_FOUND_404.reasonPhrase()), makeRequest( request() .withSecure(true) .withMethod("POST") .withBody("some_body"), headersToIgnore) ); // should match (because body doesn't matches regex) assertEquals( response() .withStatusCode(OK_200.code()) .withReasonPhrase(OK_200.reasonPhrase()) .withBody("some_not_regex_body_response"), makeRequest( request() .withSecure(true) .withMethod("POST") .withBody("some_other_body"), headersToIgnore) ); } @Test public void shouldReturnResponseByMatchingBodyWithXPath() { // when mockServerClient.when(request().withBody(xpath("/bookstore/book[price>30]/price")), exactly(2)).respond(response().withBody("some_body")); // then // - in http assertEquals( response() .withStatusCode(OK_200.code()) .withReasonPhrase(OK_200.reasonPhrase()) .withBody("some_body"), makeRequest( request() .withPath(calculatePath("some_path")) .withMethod("POST") .withBody(new StringBody("" + "<?xml version=\"1.0\" encoding=\"ISO-8859-1\"?>" + NEW_LINE + "<bookstore>" + NEW_LINE + " <book category=\"COOKING\">" + NEW_LINE + " <title lang=\"en\">Everyday Italian</title>" + NEW_LINE + " <author>Giada De Laurentiis</author>" + NEW_LINE + " <year>2005</year>" + NEW_LINE + " <price>30.00</price>" + NEW_LINE + " </book>" + NEW_LINE + " <book category=\"CHILDREN\">" + NEW_LINE + " <title lang=\"en\">Harry Potter</title>" + NEW_LINE + " <author>J K. Rowling</author>" + NEW_LINE + " <year>2005</year>" + NEW_LINE + " <price>29.99</price>" + NEW_LINE + " </book>" + NEW_LINE + " <book category=\"WEB\">" + NEW_LINE + " <title lang=\"en\">Learning XML</title>" + NEW_LINE + " <author>Erik T. Ray</author>" + NEW_LINE + " <year>2003</year>" + NEW_LINE + " <price>31.95</price>" + NEW_LINE + " </book>" + NEW_LINE + "</bookstore>")), headersToIgnore) ); // - in https assertEquals( response() .withStatusCode(OK_200.code()) .withReasonPhrase(OK_200.reasonPhrase()) .withBody("some_body"), makeRequest( request() .withSecure(true) .withPath(calculatePath("some_path")) .withMethod("POST") .withBody(new StringBody("" + "<?xml version=\"1.0\" encoding=\"ISO-8859-1\"?>" + NEW_LINE + "<bookstore>" + NEW_LINE + " <book category=\"COOKING\">" + NEW_LINE + " <title lang=\"en\">Everyday Italian</title>" + NEW_LINE + " <author>Giada De Laurentiis</author>" + NEW_LINE + " <year>2005</year>" + NEW_LINE + " <price>30.00</price>" + NEW_LINE + " </book>" + NEW_LINE + " <book category=\"CHILDREN\">" + NEW_LINE + " <title lang=\"en\">Harry Potter</title>" + NEW_LINE + " <author>J K. Rowling</author>" + NEW_LINE + " <year>2005</year>" + NEW_LINE + " <price>29.99</price>" + NEW_LINE + " </book>" + NEW_LINE + " <book category=\"WEB\">" + NEW_LINE + " <title lang=\"en\">Learning XML</title>" + NEW_LINE + " <author>Erik T. Ray</author>" + NEW_LINE + " <year>2003</year>" + NEW_LINE + " <price>31.95</price>" + NEW_LINE + " </book>" + NEW_LINE + "</bookstore>")), headersToIgnore) ); } @Test public void shouldReturnResponseByMatchingBodyWithXmlSchema() { // when mockServerClient.when(request() .withBody( xmlSchema("<?xml version=\"1.0\" encoding=\"UTF-8\"?>" + NEW_LINE + "<xs:schema xmlns:xs=\"http://www.w3.org/2001/XMLSchema\" elementFormDefault=\"qualified\" attributeFormDefault=\"unqualified\">" + NEW_LINE + " <!-- XML Schema Generated from XML Document on Wed Jun 28 2017 21:52:45 GMT+0100 (BST) -->" + NEW_LINE + " <!-- with XmlGrid.net Free Online Service http://xmlgrid.net -->" + NEW_LINE + " <xs:element name=\"notes\">" + NEW_LINE + " <xs:complexType>" + NEW_LINE + " <xs:sequence>" + NEW_LINE + " <xs:element name=\"note\" maxOccurs=\"unbounded\">" + NEW_LINE + " <xs:complexType>" + NEW_LINE + " <xs:sequence>" + NEW_LINE + " <xs:element name=\"to\" minOccurs=\"1\" maxOccurs=\"1\" type=\"xs:string\"></xs:element>" + NEW_LINE + " <xs:element name=\"from\" minOccurs=\"1\" maxOccurs=\"1\" type=\"xs:string\"></xs:element>" + NEW_LINE + " <xs:element name=\"heading\" minOccurs=\"1\" maxOccurs=\"1\" type=\"xs:string\"></xs:element>" + NEW_LINE + " <xs:element name=\"body\" minOccurs=\"1\" maxOccurs=\"1\" type=\"xs:string\"></xs:element>" + NEW_LINE + " </xs:sequence>" + NEW_LINE + " </xs:complexType>" + NEW_LINE + " </xs:element>" + NEW_LINE + " </xs:sequence>" + NEW_LINE + " </xs:complexType>" + NEW_LINE + " </xs:element>" + NEW_LINE + "</xs:schema>")), exactly(2) ) .respond( response() .withBody("some_body") ); // then // - in http assertEquals( response() .withStatusCode(NOT_FOUND_404.code()) .withReasonPhrase(NOT_FOUND_404.reasonPhrase()), makeRequest( request() .withMethod("POST") .withBody("<?xml version=\"1.0\" encoding=\"utf-8\"?>" + NEW_LINE + "<notes>" + NEW_LINE + " <note>" + NEW_LINE + " <to>Bob</to>" + NEW_LINE + " <heading>Reminder</heading>" + NEW_LINE + " <body>Buy Bread</body>" + NEW_LINE + " </note>" + NEW_LINE + " <note>" + NEW_LINE + " <to>Jack</to>" + NEW_LINE + " <from>Jill</from>" + NEW_LINE + " <heading>Reminder</heading>" + NEW_LINE + " <body>Wash Shirts</body>" + NEW_LINE + " </note>" + NEW_LINE + "</notes>"), headersToIgnore) ); assertEquals( response() .withStatusCode(OK_200.code()) .withReasonPhrase(OK_200.reasonPhrase()) .withBody("some_body"), makeRequest( request() .withPath(calculatePath("some_path")) .withMethod("POST") .withBody("<?xml version=\"1.0\" encoding=\"utf-8\"?>" + NEW_LINE + "<notes>" + NEW_LINE + " <note>" + NEW_LINE + " <to>Bob</to>" + NEW_LINE + " <from>Bill</from>" + NEW_LINE + " <heading>Reminder</heading>" + NEW_LINE + " <body>Buy Bread</body>" + NEW_LINE + " </note>" + NEW_LINE + " <note>" + NEW_LINE + " <to>Jack</to>" + NEW_LINE + " <from>Jill</from>" + NEW_LINE + " <heading>Reminder</heading>" + NEW_LINE + " <body>Wash Shirts</body>" + NEW_LINE + " </note>" + NEW_LINE + "</notes>"), headersToIgnore) ); // - in https assertEquals( response() .withStatusCode(OK_200.code()) .withReasonPhrase(OK_200.reasonPhrase()) .withBody("some_body"), makeRequest( request() .withSecure(true) .withPath(calculatePath("some_path")) .withMethod("POST") .withBody("<?xml version=\"1.0\" encoding=\"utf-8\"?>" + NEW_LINE + "<notes>" + NEW_LINE + " <note>" + NEW_LINE + " <to>Bob</to>" + NEW_LINE + " <from>Bill</from>" + NEW_LINE + " <heading>Reminder</heading>" + NEW_LINE + " <body>Buy Bread</body>" + NEW_LINE + " </note>" + NEW_LINE + " <note>" + NEW_LINE + " <to>Jack</to>" + NEW_LINE + " <from>Jill</from>" + NEW_LINE + " <heading>Reminder</heading>" + NEW_LINE + " <body>Wash Shirts</body>" + NEW_LINE + " </note>" + NEW_LINE + "</notes>"), headersToIgnore) ); } @Test public void shouldReturnResponseByMatchingBodyWithXmlSchemaByClasspath() { // when mockServerClient.when(request() .withBody( xmlSchemaFromResource("org/mockserver/model/testXmlSchema.xsd")), exactly(2) ) .respond( response() .withBody("some_body") ); // then // - in http assertEquals( response() .withStatusCode(NOT_FOUND_404.code()) .withReasonPhrase(NOT_FOUND_404.reasonPhrase()), makeRequest( request() .withMethod("POST") .withBody("<?xml version=\"1.0\" encoding=\"utf-8\"?>" + NEW_LINE + "<notes>" + NEW_LINE + " <note>" + NEW_LINE + " <to>Bob</to>" + NEW_LINE + " <heading>Reminder</heading>" + NEW_LINE + " <body>Buy Bread</body>" + NEW_LINE + " </note>" + NEW_LINE + " <note>" + NEW_LINE + " <to>Jack</to>" + NEW_LINE + " <from>Jill</from>" + NEW_LINE + " <heading>Reminder</heading>" + NEW_LINE + " <body>Wash Shirts</body>" + NEW_LINE + " </note>" + NEW_LINE + "</notes>"), headersToIgnore) ); assertEquals( response() .withStatusCode(OK_200.code()) .withReasonPhrase(OK_200.reasonPhrase()) .withBody("some_body"), makeRequest( request() .withPath(calculatePath("some_path")) .withMethod("POST") .withBody("<?xml version=\"1.0\" encoding=\"utf-8\"?>" + NEW_LINE + "<notes>" + NEW_LINE + " <note>" + NEW_LINE + " <to>Bob</to>" + NEW_LINE + " <from>Bill</from>" + NEW_LINE + " <heading>Reminder</heading>" + NEW_LINE + " <body>Buy Bread</body>" + NEW_LINE + " </note>" + NEW_LINE + " <note>" + NEW_LINE + " <to>Jack</to>" + NEW_LINE + " <from>Jill</from>" + NEW_LINE + " <heading>Reminder</heading>" + NEW_LINE + " <body>Wash Shirts</body>" + NEW_LINE + " </note>" + NEW_LINE + "</notes>"), headersToIgnore) ); // - in https assertEquals( response() .withStatusCode(OK_200.code()) .withReasonPhrase(OK_200.reasonPhrase()) .withBody("some_body"), makeRequest( request() .withSecure(true) .withPath(calculatePath("some_path")) .withMethod("POST") .withBody("<?xml version=\"1.0\" encoding=\"utf-8\"?>" + NEW_LINE + "<notes>" + NEW_LINE + " <note>" + NEW_LINE + " <to>Bob</to>" + NEW_LINE + " <from>Bill</from>" + NEW_LINE + " <heading>Reminder</heading>" + NEW_LINE + " <body>Buy Bread</body>" + NEW_LINE + " </note>" + NEW_LINE + " <note>" + NEW_LINE + " <to>Jack</to>" + NEW_LINE + " <from>Jill</from>" + NEW_LINE + " <heading>Reminder</heading>" + NEW_LINE + " <body>Wash Shirts</body>" + NEW_LINE + " </note>" + NEW_LINE + "</notes>"), headersToIgnore) ); } @Test public void shouldReturnResponseByMatchingBodyWithXml() { // when mockServerClient.when(request().withBody(xml("" + "<bookstore>" + NEW_LINE + " <book nationality=\"ITALIAN\" category=\"COOKING\"><title lang=\"en\">Everyday Italian</title><author>Giada De Laurentiis</author><year>2005</year><price>30.00</price></book>" + NEW_LINE + "</bookstore>")), exactly(2)).respond(response().withBody("some_body")); // then // - in http assertEquals( response() .withStatusCode(OK_200.code()) .withReasonPhrase(OK_200.reasonPhrase()) .withBody("some_body"), makeRequest( request() .withPath(calculatePath("some_path")) .withMethod("POST") .withBody(new StringBody("" + "<?xml version=\"1.0\" encoding=\"ISO-8859-1\"?>" + NEW_LINE + "<bookstore>" + NEW_LINE + " <book category=\"COOKING\" nationality=\"ITALIAN\">" + NEW_LINE + " <title lang=\"en\">Everyday Italian</title>" + NEW_LINE + " <author>Giada De Laurentiis</author>" + NEW_LINE + " <year>2005</year>" + NEW_LINE + " <price>30.00</price>" + NEW_LINE + " </book>" + NEW_LINE + "</bookstore>")), headersToIgnore) ); // - in https assertEquals( response() .withStatusCode(OK_200.code()) .withReasonPhrase(OK_200.reasonPhrase()) .withBody("some_body"), makeRequest( request() .withSecure(true) .withPath(calculatePath("some_path")) .withMethod("POST") .withBody(new StringBody("" + "<?xml version=\"1.0\" encoding=\"ISO-8859-1\"?>" + NEW_LINE + "<bookstore>" + NEW_LINE + " <book category=\"COOKING\" nationality=\"ITALIAN\">" + NEW_LINE + " <title lang=\"en\">Everyday Italian</title>" + NEW_LINE + " <author>Giada De Laurentiis</author>" + NEW_LINE + " <year>2005</year>" + NEW_LINE + " <price>30.00</price>" + NEW_LINE + " </book>" + NEW_LINE + "</bookstore>")), headersToIgnore) ); } @Test public void shouldReturnResponseByMatchingBodyWithXmlWithSpecialCharacters() { // when mockServerClient .when( request() .withBody( xml( "" + "<bookstore>" + NEW_LINE + " <book nationality=\"ITALIAN\" category=\"COOKING\"><title>Everyday Italian</title><author>我说中国话</author></book>" + NEW_LINE + "</bookstore>", StandardCharsets.UTF_8 ) ), exactly(2) ) .respond( response() .withBody("some_body") ); // then // - in http assertEquals( response() .withStatusCode(OK_200.code()) .withReasonPhrase(OK_200.reasonPhrase()) .withBody("some_body"), makeRequest( request() .withPath(calculatePath("some_path")) .withMethod("POST") .withHeader("Content-Type", "application/xml; charset=utf-8") .withBody(new StringBody("" + "<?xml version=\"1.0\" encoding=\"UTF-8\"?>" + NEW_LINE + "<bookstore>" + NEW_LINE + " <book category=\"COOKING\" nationality=\"ITALIAN\">" + NEW_LINE + " <title>Everyday Italian</title>" + NEW_LINE + " <author>我说中国话</author>" + NEW_LINE + " </book>" + NEW_LINE + "</bookstore>")), headersToIgnore) ); // - in https assertEquals( response() .withStatusCode(OK_200.code()) .withReasonPhrase(OK_200.reasonPhrase()) .withBody("some_body"), makeRequest( request() .withSecure(true) .withPath(calculatePath("some_path")) .withMethod("POST") .withHeader("Content-Type", "application/xml; charset=utf-8") .withBody(new StringBody("" + "<?xml version=\"1.0\" encoding=\"UTF-8\"?>" + NEW_LINE + "<bookstore>" + NEW_LINE + " <book category=\"COOKING\" nationality=\"ITALIAN\">" + NEW_LINE + " <title>Everyday Italian</title>" + NEW_LINE + " <author>我说中国话</author>" + NEW_LINE + " </book>" + NEW_LINE + "</bookstore>")), headersToIgnore) ); } @Test public void shouldReturnResponseByMatchingBodyWithXmlWithSpecialCharactersClientCharsetDifferent() { // when mockServerClient .when( request() .withBody( xml( "" + "<bookstore>" + NEW_LINE + " <book nationality=\"ITALIAN\" category=\"COOKING\"><title>Everyday Italian</title><author>ÄÑçîüÏ</author></book>" + NEW_LINE + "</bookstore>", StandardCharsets.UTF_8 ) ), exactly(2) ) .respond( response() .withBody("some_body") ); // then // - in http assertEquals( response() .withStatusCode(OK_200.code()) .withReasonPhrase(OK_200.reasonPhrase()) .withBody("some_body"), makeRequest( request() .withPath(calculatePath("some_path")) .withMethod("POST") .withHeader("Content-Type", "application/xml; charset=" + StandardCharsets.ISO_8859_1.name()) .withBody(binary(("" + "<?xml version=\"1.0\" encoding=\"ISO-8859-1\"?>" + NEW_LINE + "<bookstore>" + NEW_LINE + " <book category=\"COOKING\" nationality=\"ITALIAN\">" + NEW_LINE + " <title>Everyday Italian</title>" + NEW_LINE + " <author>ÄÑçîüÏ</author>" + NEW_LINE + " </book>" + NEW_LINE + "</bookstore>").getBytes(StandardCharsets.ISO_8859_1))), headersToIgnore) ); // - in https assertEquals( response() .withStatusCode(OK_200.code()) .withReasonPhrase(OK_200.reasonPhrase()) .withBody("some_body"), makeRequest( request() .withSecure(true) .withPath(calculatePath("some_path")) .withMethod("POST") .withHeader("Content-Type", "application/xml; charset=" + StandardCharsets.ISO_8859_1.name()) .withBody(binary(("" + "<?xml version=\"1.0\" encoding=\"ISO-8859-1\"?>" + NEW_LINE + "<bookstore>" + NEW_LINE + " <book category=\"COOKING\" nationality=\"ITALIAN\">" + NEW_LINE + " <title>Everyday Italian</title>" + NEW_LINE + " <author>ÄÑçîüÏ</author>" + NEW_LINE + " </book>" + NEW_LINE + "</bookstore>").getBytes(StandardCharsets.ISO_8859_1))), headersToIgnore) ); } @Test public void shouldReturnResponseByMatchingBodyWithJson() { // when mockServerClient .when( request() .withBody(json("{" + NEW_LINE + " \"id\": 1," + NEW_LINE + " \"name\": \"A green door\"," + NEW_LINE + " \"price\": 12.50," + NEW_LINE + " \"tags\": [\"home\", \"green\"]" + NEW_LINE + "}")), exactly(2) ) .respond( response() .withStatusCode(ACCEPTED_202.code()) .withReasonPhrase(ACCEPTED_202.reasonPhrase()) .withBody("some_body") ); // then // - in http assertEquals( response() .withStatusCode(ACCEPTED_202.code()) .withReasonPhrase(ACCEPTED_202.reasonPhrase()) .withBody("some_body"), makeRequest( request() .withPath(calculatePath("some_path")) .withMethod("POST") .withBody("{" + NEW_LINE + " \"id\": 1," + NEW_LINE + " \"extra ignored field\": \"some value\"," + NEW_LINE + " \"name\": \"A green door\"," + NEW_LINE + " \"price\": 12.50," + NEW_LINE + " \"tags\": [\"home\", \"green\"]" + NEW_LINE + "}"), headersToIgnore) ); // - in https assertEquals( response() .withStatusCode(ACCEPTED_202.code()) .withReasonPhrase(ACCEPTED_202.reasonPhrase()) .withBody("some_body"), makeRequest( request() .withSecure(true) .withPath(calculatePath("some_path")) .withMethod("POST") .withBody("{" + NEW_LINE + " \"id\": 1," + NEW_LINE + " \"extra ignored array\": [\"one\", \"two\"]," + NEW_LINE + " \"name\": \"A green door\"," + NEW_LINE + " \"price\": 12.50," + NEW_LINE + " \"tags\": [\"home\", \"green\"]" + NEW_LINE + "}"), headersToIgnore) ); } @Test public void shouldReturnResponseByMatchingBodyWithJsonAsRawBody() { // when assertEquals( response() .withStatusCode(CREATED_201.code()) .withReasonPhrase(CREATED_201.reasonPhrase()), makeRequest( request() .withPath(calculatePath("mockserver/expectation")) .withMethod("PUT") .withBody("{" + NEW_LINE + " \"httpRequest\" : {" + NEW_LINE + " \"body\" : {" + NEW_LINE + " \"id\": 1," + NEW_LINE + " \"name\": \"A green door\"," + NEW_LINE + " \"price\": 12.50," + NEW_LINE + " \"tags\": [\"home\", \"green\"]" + NEW_LINE + " }" + NEW_LINE + " }," + NEW_LINE + " \"httpResponse\" : {" + NEW_LINE + " \"body\" : {" + NEW_LINE + " \"id\": 1," + NEW_LINE + " \"name\": \"A green door\"," + NEW_LINE + " \"price\": 12.50," + NEW_LINE + " \"tags\": [\"home\", \"green\"]" + NEW_LINE + " }" + NEW_LINE + " }" + NEW_LINE + "}"), headersToIgnore) ); // then assertEquals( response() .withStatusCode(OK_200.code()) .withReasonPhrase(OK_200.reasonPhrase()) .withHeader(CONTENT_TYPE.toString(), MediaType.create("application", "json").toString()) .withBody(json("{\"id\":1,\"name\":\"A green door\",\"price\":12.5,\"tags\":[\"home\",\"green\"]}", MediaType.create("application", "json"))), makeRequest( request() .withPath(calculatePath("some_path")) .withMethod("POST") .withBody("{" + NEW_LINE + " \"id\" : 1," + NEW_LINE + " \"name\" : \"A green door\"," + NEW_LINE + " \"price\" : 12.5," + NEW_LINE + " \"tags\" : [ \"home\", \"green\" ]" + NEW_LINE + "}"), headersToIgnore) ); } @Test public void shouldReturnResponseByMatchingBodyWithJsonWithCharsetUTF8() { // when mockServerClient .when( request() .withBody(json("{" + NEW_LINE + " \"ταυτότητα\": 1," + NEW_LINE + " \"όνομα\": \"μια πράσινη πόρτα\"," + NEW_LINE + " \"τιμή\": 12.50," + NEW_LINE + " \"ετικέτες\": [\"σπίτι\", \"πράσινος\"]" + NEW_LINE + "}", StandardCharsets.UTF_16, MatchType.ONLY_MATCHING_FIELDS)), exactly(2) ) .respond( response() .withStatusCode(ACCEPTED_202.code()) .withReasonPhrase(ACCEPTED_202.reasonPhrase()) .withBody("some_body") ); // then // - in http assertEquals( response() .withStatusCode(ACCEPTED_202.code()) .withReasonPhrase(ACCEPTED_202.reasonPhrase()) .withBody("some_body"), makeRequest( request() .withPath(calculatePath("some_path")) .withMethod("POST") .withBody(json("{" + NEW_LINE + " \"ταυτότητα\": 1," + NEW_LINE + " \"επιπλέον αγνοούνται τομέα\": \"κάποια αξία\"," + NEW_LINE + " \"όνομα\": \"μια πράσινη πόρτα\"," + NEW_LINE + " \"τιμή\": 12.50," + NEW_LINE + " \"ετικέτες\": [\"σπίτι\", \"πράσινος\"]" + NEW_LINE + "}", StandardCharsets.UTF_16, MatchType.ONLY_MATCHING_FIELDS)), headersToIgnore) ); // - in https assertEquals( response() .withStatusCode(ACCEPTED_202.code()) .withReasonPhrase(ACCEPTED_202.reasonPhrase()) .withBody("some_body"), makeRequest( request() .withSecure(true) .withPath(calculatePath("some_path")) .withMethod("POST") .withBody(json("{" + NEW_LINE + " \"ταυτότητα\": 1," + NEW_LINE + " \"επιπλέον αγνοούνται σειρά\": [\"ένας\", \"δυο\"]," + NEW_LINE + " \"όνομα\": \"μια πράσινη πόρτα\"," + NEW_LINE + " \"τιμή\": 12.50," + NEW_LINE + " \"ετικέτες\": [\"σπίτι\", \"πράσινος\"]" + NEW_LINE + "}", StandardCharsets.UTF_16, MatchType.ONLY_MATCHING_FIELDS)), headersToIgnore) ); } @Test public void shouldReturnResponseByMatchingBodyWithJsonWithContentTypeHeader() { // when mockServerClient .when( request() .withBody(json("{" + NEW_LINE + " \"ταυτότητα\": 1," + NEW_LINE + " \"όνομα\": \"μια πράσινη πόρτα\"," + NEW_LINE + " \"τιμή\": 12.50," + NEW_LINE + " \"ετικέτες\": [\"σπίτι\", \"πράσινος\"]" + NEW_LINE + "}", StandardCharsets.UTF_16, MatchType.ONLY_MATCHING_FIELDS)), exactly(2) ) .respond( response() .withStatusCode(ACCEPTED_202.code()) .withReasonPhrase(ACCEPTED_202.reasonPhrase()) .withBody("some_body") ); // then // - in http assertEquals( response() .withStatusCode(ACCEPTED_202.code()) .withReasonPhrase(ACCEPTED_202.reasonPhrase()) .withBody("some_body"), makeRequest( request() .withHeader(CONTENT_TYPE.toString(), MediaType.create("text", "plain").withCharset(StandardCharsets.UTF_16).toString()) .withPath(calculatePath("some_path")) .withMethod("POST") .withBody(json("{" + NEW_LINE + " \"ταυτότητα\": 1," + NEW_LINE + " \"επιπλέον αγνοούνται τομέα\": \"κάποια αξία\"," + NEW_LINE + " \"όνομα\": \"μια πράσινη πόρτα\"," + NEW_LINE + " \"τιμή\": 12.50," + NEW_LINE + " \"ετικέτες\": [\"σπίτι\", \"πράσινος\"]" + NEW_LINE + "}")), headersToIgnore) ); // - in https assertEquals( response() .withStatusCode(ACCEPTED_202.code()) .withReasonPhrase(ACCEPTED_202.reasonPhrase()) .withBody("some_body"), makeRequest( request() .withSecure(true) .withHeader(CONTENT_TYPE.toString(), MediaType.create("text", "plain").withCharset(StandardCharsets.UTF_16).toString()) .withPath(calculatePath("some_path")) .withMethod("POST") .withBody(json("{" + NEW_LINE + " \"ταυτότητα\": 1," + NEW_LINE + " \"επιπλέον αγνοούνται σειρά\": [\"ένας\", \"δυο\"]," + NEW_LINE + " \"όνομα\": \"μια πράσινη πόρτα\"," + NEW_LINE + " \"τιμή\": 12.50," + NEW_LINE + " \"ετικέτες\": [\"σπίτι\", \"πράσινος\"]" + NEW_LINE + "}")), headersToIgnore) ); } @Test public void shouldReturnResponseByMatchingBodyWithJsonWithMatchType() { // when mockServerClient .when( request() .withBody(json("{" + NEW_LINE + " \"id\": 1," + NEW_LINE + " \"name\": \"A green door\"," + NEW_LINE + " \"price\": 12.50," + NEW_LINE + " \"tags\": [\"home\", \"green\"]" + NEW_LINE + "}", MatchType.ONLY_MATCHING_FIELDS)), exactly(2) ) .respond( response() .withBody("some_body") ); // then // - in http assertEquals( response("some_body"), makeRequest( request() .withPath(calculatePath("some_path")) .withMethod("POST") .withBody("{" + NEW_LINE + " \"id\": 1," + NEW_LINE + " \"extra field\": \"some value\"," + NEW_LINE + " \"name\": \"A green door\"," + NEW_LINE + " \"price\": 12.50," + NEW_LINE + " \"tags\": [\"home\", \"green\"]" + NEW_LINE + "}"), headersToIgnore) ); // - in https assertEquals( response("some_body"), makeRequest( request() .withSecure(true) .withPath(calculatePath("some_path")) .withMethod("POST") .withBody("{" + NEW_LINE + " \"id\": 1," + NEW_LINE + " \"extra field\": \"some value\"," + NEW_LINE + " \"name\": \"A green door\"," + NEW_LINE + " \"price\": 12.50," + NEW_LINE + " \"tags\": [\"home\", \"green\"]" + NEW_LINE + "}"), headersToIgnore) ); } @Test public void shouldReturnResponseByMatchingBodyWithJsonSchema() { // when mockServerClient.when(request().withBody(jsonSchema("{" + NEW_LINE + " \"$schema\": \"http://json-schema.org/draft-04/schema#\"," + NEW_LINE + " \"title\": \"Product\"," + NEW_LINE + " \"description\": \"A product from Acme's catalog\"," + NEW_LINE + " \"type\": \"object\"," + NEW_LINE + " \"properties\": {" + NEW_LINE + " \"id\": {" + NEW_LINE + " \"description\": \"The unique identifier for a product\"," + NEW_LINE + " \"type\": \"integer\"" + NEW_LINE + " }," + NEW_LINE + " \"name\": {" + NEW_LINE + " \"description\": \"Name of the product\"," + NEW_LINE + " \"type\": \"string\"" + NEW_LINE + " }," + NEW_LINE + " \"price\": {" + NEW_LINE + " \"type\": \"number\"," + NEW_LINE + " \"minimum\": 0," + NEW_LINE + " \"exclusiveMinimum\": true" + NEW_LINE + " }," + NEW_LINE + " \"tags\": {" + NEW_LINE + " \"type\": \"array\"," + NEW_LINE + " \"items\": {" + NEW_LINE + " \"type\": \"string\"" + NEW_LINE + " }," + NEW_LINE + " \"minItems\": 1," + NEW_LINE + " \"uniqueItems\": true" + NEW_LINE + " }" + NEW_LINE + " }," + NEW_LINE + " \"required\": [\"id\", \"name\", \"price\"]" + NEW_LINE + "}")), exactly(2)).respond(response().withBody("some_body")); // then // - in http assertEquals( response() .withStatusCode(OK_200.code()) .withReasonPhrase(OK_200.reasonPhrase()) .withBody("some_body"), makeRequest( request() .withPath(calculatePath("some_path")) .withMethod("POST") .withBody("{" + NEW_LINE + " \"id\": 1," + NEW_LINE + " \"name\": \"A green door\"," + NEW_LINE + " \"price\": 12.50," + NEW_LINE + " \"tags\": [\"home\", \"green\"]" + NEW_LINE + "}"), headersToIgnore) ); // - in https assertEquals( response() .withStatusCode(OK_200.code()) .withReasonPhrase(OK_200.reasonPhrase()) .withBody("some_body"), makeRequest( request() .withSecure(true) .withPath(calculatePath("some_path")) .withMethod("POST") .withBody("{" + NEW_LINE + " \"id\": 1," + NEW_LINE + " \"name\": \"A green door\"," + NEW_LINE + " \"price\": 12.50," + NEW_LINE + " \"tags\": [\"home\", \"green\"]" + NEW_LINE + "}"), headersToIgnore) ); } @Test public void shouldReturnResponseByMatchingBodyWithJsonPath() { // when mockServerClient.when(request().withBody(jsonPath("$..book[?(@.price <= $['expensive'])]")), exactly(2)).respond(response().withBody("some_body")); // then // - in http assertEquals( response() .withStatusCode(OK_200.code()) .withReasonPhrase(OK_200.reasonPhrase()) .withBody("some_body"), makeRequest( request() .withPath(calculatePath("some_path")) .withMethod("POST") .withBody(new StringBody("" + "{" + NEW_LINE + " \"store\": {" + NEW_LINE + " \"book\": [" + NEW_LINE + " {" + NEW_LINE + " \"category\": \"reference\"," + NEW_LINE + " \"author\": \"Nigel Rees\"," + NEW_LINE + " \"title\": \"Sayings of the Century\"," + NEW_LINE + " \"price\": 8.95" + NEW_LINE + " }," + NEW_LINE + " {" + NEW_LINE + " \"category\": \"fiction\"," + NEW_LINE + " \"author\": \"Herman Melville\"," + NEW_LINE + " \"title\": \"Moby Dick\"," + NEW_LINE + " \"isbn\": \"0-553-21311-3\"," + NEW_LINE + " \"price\": 8.99" + NEW_LINE + " }" + NEW_LINE + " ]," + NEW_LINE + " \"bicycle\": {" + NEW_LINE + " \"color\": \"red\"," + NEW_LINE + " \"price\": 19.95" + NEW_LINE + " }" + NEW_LINE + " }," + NEW_LINE + " \"expensive\": 10" + NEW_LINE + "}")), headersToIgnore) ); // - in https assertEquals( response() .withStatusCode(OK_200.code()) .withReasonPhrase(OK_200.reasonPhrase()) .withBody("some_body"), makeRequest( request() .withSecure(true) .withPath(calculatePath("some_path")) .withMethod("POST") .withBody(new StringBody("" + "{" + NEW_LINE + " \"store\": {" + NEW_LINE + " \"book\": [" + NEW_LINE + " {" + NEW_LINE + " \"category\": \"reference\"," + NEW_LINE + " \"author\": \"Nigel Rees\"," + NEW_LINE + " \"title\": \"Sayings of the Century\"," + NEW_LINE + " \"price\": 8.95" + NEW_LINE + " }," + NEW_LINE + " {" + NEW_LINE + " \"category\": \"fiction\"," + NEW_LINE + " \"author\": \"Herman Melville\"," + NEW_LINE + " \"title\": \"Moby Dick\"," + NEW_LINE + " \"isbn\": \"0-553-21311-3\"," + NEW_LINE + " \"price\": 8.99" + NEW_LINE + " }" + NEW_LINE + " ]," + NEW_LINE + " \"bicycle\": {" + NEW_LINE + " \"color\": \"red\"," + NEW_LINE + " \"price\": 19.95" + NEW_LINE + " }" + NEW_LINE + " }," + NEW_LINE + " \"expensive\": 10" + NEW_LINE + "}")), headersToIgnore) ); } @Test public void shouldReturnPDFResponseByMatchingPath() throws IOException { // when byte[] pdfBytes = IOUtils.toByteArray(getClass().getClassLoader().getResourceAsStream("test.pdf")); mockServerClient .when( request() .withPath(calculatePath("ws/rest/user/[0-9]+/document/[0-9]+\\.pdf")) ) .respond( response() .withStatusCode(OK_200.code()) .withReasonPhrase(OK_200.reasonPhrase()) .withHeaders( header(CONTENT_TYPE.toString(), MediaType.PDF.toString()), header(CONTENT_DISPOSITION.toString(), "form-data; name=\"test.pdf\"; filename=\"test.pdf\""), header(CACHE_CONTROL.toString(), "must-revalidate, post-check=0, pre-check=0") ) .withBody(binary(pdfBytes)) ); // then // - in http assertEquals( response() .withStatusCode(OK_200.code()) .withReasonPhrase(OK_200.reasonPhrase()) .withHeaders( header(CONTENT_DISPOSITION.toString(), "form-data; name=\"test.pdf\"; filename=\"test.pdf\""), header(CACHE_CONTROL.toString(), "must-revalidate, post-check=0, pre-check=0"), header(CONTENT_TYPE.toString(), MediaType.PDF.toString()) ) .withBody(binary(pdfBytes, MediaType.PDF)), makeRequest( request() .withPath(calculatePath("ws/rest/user/1/document/2.pdf")) .withMethod("GET"), headersToIgnore) ); // - in https assertEquals( response() .withStatusCode(OK_200.code()) .withReasonPhrase(OK_200.reasonPhrase()) .withHeaders( header(CONTENT_DISPOSITION.toString(), "form-data; name=\"test.pdf\"; filename=\"test.pdf\""), header(CACHE_CONTROL.toString(), "must-revalidate, post-check=0, pre-check=0"), header(CONTENT_TYPE.toString(), MediaType.PDF.toString()) ) .withBody(binary(pdfBytes, MediaType.PDF)), makeRequest( request() .withSecure(true) .withPath(calculatePath("ws/rest/user/1/document/2.pdf")) .withMethod("GET"), headersToIgnore) ); } @Test public void shouldReturnPNGResponseByMatchingPath() throws IOException { // when byte[] pngBytes = IOUtils.toByteArray(getClass().getClassLoader().getResourceAsStream("test.png")); mockServerClient .when( request() .withPath(calculatePath("ws/rest/user/[0-9]+/icon/[0-9]+\\.png")) ) .respond( response() .withStatusCode(OK_200.code()) .withReasonPhrase(OK_200.reasonPhrase()) .withHeaders( header(CONTENT_TYPE.toString(), MediaType.PNG.toString()), header(CONTENT_DISPOSITION.toString(), "form-data; name=\"test.png\"; filename=\"test.png\"") ) .withBody(binary(pngBytes)) ); // then // - in http assertEquals( response() .withStatusCode(OK_200.code()) .withReasonPhrase(OK_200.reasonPhrase()) .withHeaders( header(CONTENT_DISPOSITION.toString(), "form-data; name=\"test.png\"; filename=\"test.png\""), header(CONTENT_TYPE.toString(), MediaType.PNG.toString()) ) .withBody(binary(pngBytes, MediaType.PNG)), makeRequest( request() .withPath(calculatePath("ws/rest/user/1/icon/1.png")) .withMethod("GET"), headersToIgnore) ); // - in https assertEquals( response() .withStatusCode(OK_200.code()) .withReasonPhrase(OK_200.reasonPhrase()) .withHeaders( header(CONTENT_DISPOSITION.toString(), "form-data; name=\"test.png\"; filename=\"test.png\""), header(CONTENT_TYPE.toString(), MediaType.PNG.toString()) ) .withBody(binary(pngBytes, MediaType.PNG)), makeRequest( request() .withSecure(true) .withPath(calculatePath("ws/rest/user/1/icon/1.png")) .withMethod("GET"), headersToIgnore) ); } @Test public void shouldReturnPDFResponseByMatchingBinaryPDFBody() throws IOException { // when byte[] pdfBytes = IOUtils.toByteArray(getClass().getClassLoader().getResourceAsStream("test.pdf")); mockServerClient .when( request() .withBody(binary(pdfBytes, MediaType.PDF)) ) .respond( response() .withStatusCode(OK_200.code()) .withReasonPhrase(OK_200.reasonPhrase()) .withHeaders( header(CONTENT_TYPE.toString(), MediaType.PDF.toString()), header(CONTENT_DISPOSITION.toString(), "form-data; name=\"test.pdf\"; filename=\"test.pdf\""), header(CACHE_CONTROL.toString(), "must-revalidate, post-check=0, pre-check=0") ) .withBody(binary(pdfBytes)) ); // then // - in http assertEquals( response() .withStatusCode(OK_200.code()) .withReasonPhrase(OK_200.reasonPhrase()) .withHeaders( header(CONTENT_DISPOSITION.toString(), "form-data; name=\"test.pdf\"; filename=\"test.pdf\""), header(CACHE_CONTROL.toString(), "must-revalidate, post-check=0, pre-check=0"), header(CONTENT_TYPE.toString(), MediaType.PDF.toString()) ) .withBody(binary(pdfBytes, MediaType.PDF)), makeRequest( request() .withPath(calculatePath("ws/rest/user/1/document/2.pdf")) .withBody(binary(pdfBytes, MediaType.PDF)) .withMethod("POST"), headersToIgnore) ); // - in https assertEquals( response() .withStatusCode(OK_200.code()) .withReasonPhrase(OK_200.reasonPhrase()) .withHeaders( header(CONTENT_DISPOSITION.toString(), "form-data; name=\"test.pdf\"; filename=\"test.pdf\""), header(CACHE_CONTROL.toString(), "must-revalidate, post-check=0, pre-check=0"), header(CONTENT_TYPE.toString(), MediaType.PDF.toString()) ) .withBody(binary(pdfBytes, MediaType.PDF)), makeRequest( request() .withSecure(true) .withPath(calculatePath("ws/rest/user/1/document/2.pdf")) .withBody(binary(pdfBytes, MediaType.PDF)) .withMethod("POST"), headersToIgnore) ); } @Test public void shouldReturnPNGResponseByMatchingBinaryPNGBody() throws IOException { // when byte[] pngBytes = IOUtils.toByteArray(getClass().getClassLoader().getResourceAsStream("test.png")); mockServerClient .when( request() .withBody(binary(pngBytes, MediaType.ANY_IMAGE_TYPE)) ) .respond( response() .withStatusCode(OK_200.code()) .withReasonPhrase(OK_200.reasonPhrase()) .withHeaders( header(CONTENT_TYPE.toString(), MediaType.PNG.toString()), header(CONTENT_DISPOSITION.toString(), "form-data; name=\"test.png\"; filename=\"test.png\"") ) .withBody(binary(pngBytes)) ); // then // - in http assertEquals( response() .withStatusCode(OK_200.code()) .withReasonPhrase(OK_200.reasonPhrase()) .withHeaders( header(CONTENT_DISPOSITION.toString(), "form-data; name=\"test.png\"; filename=\"test.png\""), header(CONTENT_TYPE.toString(), MediaType.PNG.toString()) ) .withBody(binary(pngBytes, MediaType.PNG)), makeRequest( request() .withPath(calculatePath("ws/rest/user/1/icon/1.png")) .withBody(binary(pngBytes, MediaType.ANY_IMAGE_TYPE)) .withMethod("POST"), headersToIgnore) ); // - in https assertEquals( response() .withStatusCode(OK_200.code()) .withReasonPhrase(OK_200.reasonPhrase()) .withHeaders( header(CONTENT_DISPOSITION.toString(), "form-data; name=\"test.png\"; filename=\"test.png\""), header(CONTENT_TYPE.toString(), MediaType.PNG.toString()) ) .withBody(binary(pngBytes, MediaType.PNG)), makeRequest( request() .withSecure(true) .withPath(calculatePath("ws/rest/user/1/icon/1.png")) .withBody(binary(pngBytes, MediaType.ANY_IMAGE_TYPE)) .withMethod("POST"), headersToIgnore) ); } @Test public void shouldReturnResponseByNotMatchingPathWithNotOperator() { // when mockServerClient .when( request() .withPath(not(calculatePath("some_path"))) ) .respond( response() .withStatusCode(ACCEPTED_202.code()) .withReasonPhrase(ACCEPTED_202.reasonPhrase()) .withBody("some_body_response") ); // then // - in http assertEquals( response() .withStatusCode(ACCEPTED_202.code()) .withReasonPhrase(ACCEPTED_202.reasonPhrase()) .withBody("some_body_response"), makeRequest( request() .withPath(calculatePath("some_other_path")), headersToIgnore) ); // - in https assertEquals( response() .withStatusCode(ACCEPTED_202.code()) .withReasonPhrase(ACCEPTED_202.reasonPhrase()) .withBody("some_body_response"), makeRequest( request() .withPath(calculatePath("some_other_path")), headersToIgnore) ); } @Test public void shouldReturnResponseByNotMatchingMethodWithNotOperator() { // when mockServerClient .when( request() .withMethod(not("GET")) ) .respond( response() .withStatusCode(ACCEPTED_202.code()) .withReasonPhrase(ACCEPTED_202.reasonPhrase()) .withBody("some_body_response") ); // then // - in http assertEquals( response() .withStatusCode(ACCEPTED_202.code()) .withReasonPhrase(ACCEPTED_202.reasonPhrase()) .withBody("some_body_response"), makeRequest( request() .withMethod("POST"), headersToIgnore) ); // - in https assertEquals( response() .withStatusCode(ACCEPTED_202.code()) .withReasonPhrase(ACCEPTED_202.reasonPhrase()) .withBody("some_body_response"), makeRequest( request() .withMethod("POST"), headersToIgnore) ); } @Test public void shouldReturnResponseByMatchingPathAndMethodAndBody() { // when mockServerClient .when( request() .withMethod("POST") .withPath(calculatePath("some_pathRequest")) .withBody("some_bodyRequest") ) .respond( response() .withStatusCode(ACCEPTED_202.code()) .withReasonPhrase(ACCEPTED_202.reasonPhrase()) .withBody("some_body_response") .withHeaders(header("headerNameResponse", "headerValueResponse")) ); // then // - in http assertEquals( response() .withStatusCode(ACCEPTED_202.code()) .withReasonPhrase(ACCEPTED_202.reasonPhrase()) .withBody("some_body_response") .withHeaders( header("headerNameResponse", "headerValueResponse") ), makeRequest( request() .withMethod("POST") .withPath(calculatePath("some_pathRequest")) .withQueryStringParameters( param("queryStringParameterOneName", "queryStringParameterOneValue"), param("queryStringParameterTwoName", "queryStringParameterTwoValue") ) .withBody("some_bodyRequest") .withHeaders(header("headerNameRequest", "headerValueRequest")) .withCookies(cookie("cookieNameRequest", "cookieValueRequest")), headersToIgnore) ); // - in https assertEquals( response() .withStatusCode(ACCEPTED_202.code()) .withReasonPhrase(ACCEPTED_202.reasonPhrase()) .withBody("some_body_response") .withHeaders( header("headerNameResponse", "headerValueResponse") ), makeRequest( request() .withMethod("POST") .withSecure(true) .withPath(calculatePath("some_pathRequest")) .withQueryStringParameters( param("queryStringParameterOneName", "queryStringParameterOneValue"), param("queryStringParameterTwoName", "queryStringParameterTwoValue") ) .withBody("some_bodyRequest") .withHeaders(header("headerNameRequest", "headerValueRequest")) .withCookies(cookie("cookieNameRequest", "cookieValueRequest")), headersToIgnore) ); } @Test public void shouldReturnResponseByMatchingPathAndMethodAndQueryStringParameters() { // when mockServerClient .when( request() .withMethod("GET") .withPath(calculatePath("some_pathRequest")) .withQueryStringParameters( param("queryStringParameterOneName", "queryStringParameterOneValue"), param("queryStringParameterTwoName", "queryStringParameterTwoValue") ) ) .respond( response() .withStatusCode(ACCEPTED_202.code()) .withReasonPhrase(ACCEPTED_202.reasonPhrase()) .withBody("some_body_response") .withCookies(cookie("cookieNameResponse", "cookieValueResponse")) ); // then // - in http assertEquals( response() .withStatusCode(ACCEPTED_202.code()) .withReasonPhrase(ACCEPTED_202.reasonPhrase()) .withBody("some_body_response") .withCookies(cookie("cookieNameResponse", "cookieValueResponse")) .withHeaders( header(SET_COOKIE.toString(), "cookieNameResponse=cookieValueResponse") ), makeRequest( request() .withMethod("GET") .withPath(calculatePath("some_pathRequest")) .withQueryStringParameters( param("queryStringParameterOneName", "queryStringParameterOneValue"), param("queryStringParameterTwoName", "queryStringParameterTwoValue") ) .withHeaders(header("headerNameRequest", "headerValueRequest")) .withCookies(cookie("cookieNameRequest", "cookieValueRequest")), headersToIgnore) ); // - in https assertEquals( response() .withStatusCode(ACCEPTED_202.code()) .withReasonPhrase(ACCEPTED_202.reasonPhrase()) .withBody("some_body_response") .withCookies(cookie("cookieNameResponse", "cookieValueResponse")) .withHeaders( header(SET_COOKIE.toString(), "cookieNameResponse=cookieValueResponse") ), makeRequest( request() .withMethod("GET") .withSecure(true) .withPath(calculatePath("some_pathRequest")) .withQueryStringParameters( param("queryStringParameterOneName", "queryStringParameterOneValue"), param("queryStringParameterTwoName", "queryStringParameterTwoValue") ) .withHeaders(header("headerNameRequest", "headerValueRequest")) .withCookies(cookie("cookieNameRequest", "cookieValueRequest")), headersToIgnore) ); } @Test public void shouldReturnResponseByMatchingPathAndMethodAndHeaders() { // when mockServerClient .when( request() .withMethod("GET") .withPath(calculatePath("some_pathRequest")) .withHeaders( header("requestHeaderNameOne", "requestHeaderValueOne_One", "requestHeaderValueOne_Two"), header("requestHeaderNameTwo", "requestHeaderValueTwo") ) ) .respond( response() .withStatusCode(ACCEPTED_202.code()) .withReasonPhrase(ACCEPTED_202.reasonPhrase()) .withBody("some_body_response") .withCookies(cookie("cookieNameResponse", "cookieValueResponse")) ); // then // - in http assertEquals( response() .withStatusCode(ACCEPTED_202.code()) .withReasonPhrase(ACCEPTED_202.reasonPhrase()) .withBody("some_body_response") .withCookies(cookie("cookieNameResponse", "cookieValueResponse")) .withHeaders( header(SET_COOKIE.toString(), "cookieNameResponse=cookieValueResponse") ), makeRequest( request() .withMethod("GET") .withPath(calculatePath("some_pathRequest")) .withHeaders( header("requestHeaderNameOne", "requestHeaderValueOne_One", "requestHeaderValueOne_Two"), header("requestHeaderNameTwo", "requestHeaderValueTwo") ) .withCookies(cookie("cookieNameRequest", "cookieValueRequest")), headersToIgnore) ); // - in https assertEquals( response() .withStatusCode(ACCEPTED_202.code()) .withReasonPhrase(ACCEPTED_202.reasonPhrase()) .withBody("some_body_response") .withCookies(cookie("cookieNameResponse", "cookieValueResponse")) .withHeaders( header(SET_COOKIE.toString(), "cookieNameResponse=cookieValueResponse") ), makeRequest( request() .withMethod("GET") .withSecure(true) .withPath(calculatePath("some_pathRequest")) .withHeaders( header("requestHeaderNameOne", "requestHeaderValueOne_One", "requestHeaderValueOne_Two"), header("requestHeaderNameTwo", "requestHeaderValueTwo") ) .withCookies(cookie("cookieNameRequest", "cookieValueRequest")), headersToIgnore) ); } @Test public void shouldReturnResponseByMatchingPathAndMethodAndCookies() { // when mockServerClient .when( request() .withMethod("GET") .withPath(calculatePath("some_pathRequest")) .withCookies( cookie("requestCookieNameOne", "requestCookieValueOne"), cookie("requestCookieNameTwo", "requestCookieValueTwo") ) ) .respond( response() .withStatusCode(ACCEPTED_202.code()) .withReasonPhrase(ACCEPTED_202.reasonPhrase()) .withBody("some_body_response") .withCookies( cookie("responseCookieNameOne", "responseCookieValueOne"), cookie("responseCookieNameTwo", "responseCookieValueTwo") ) ); // then // - in http - cookie objects assertEquals( response() .withStatusCode(ACCEPTED_202.code()) .withReasonPhrase(ACCEPTED_202.reasonPhrase()) .withBody("some_body_response") .withCookies( cookie("responseCookieNameOne", "responseCookieValueOne"), cookie("responseCookieNameTwo", "responseCookieValueTwo") ) .withHeaders( header(SET_COOKIE.toString(), "responseCookieNameOne=responseCookieValueOne", "responseCookieNameTwo=responseCookieValueTwo") ), makeRequest( request() .withMethod("GET") .withPath(calculatePath("some_pathRequest")) .withHeaders( header("headerNameRequest", "headerValueRequest"), header(CONTENT_TYPE.toString(), MediaType.create("text", "plain").toString()) ) .withCookies( cookie("requestCookieNameOne", "requestCookieValueOne"), cookie("requestCookieNameTwo", "requestCookieValueTwo") ), headersToIgnore) ); // - in http - cookie header assertEquals( response() .withStatusCode(ACCEPTED_202.code()) .withReasonPhrase(ACCEPTED_202.reasonPhrase()) .withBody("some_body_response") .withCookies( cookie("responseCookieNameOne", "responseCookieValueOne"), cookie("responseCookieNameTwo", "responseCookieValueTwo") ) .withHeaders( header(SET_COOKIE.toString(), "responseCookieNameOne=responseCookieValueOne", "responseCookieNameTwo=responseCookieValueTwo") ), makeRequest( request() .withMethod("GET") .withPath(calculatePath("some_pathRequest")) .withHeaders( header("headerNameRequest", "headerValueRequest"), header("Cookie", "requestCookieNameOne=requestCookieValueOne; requestCookieNameTwo=requestCookieValueTwo") ), headersToIgnore) ); // - in https - cookie objects assertEquals( response() .withStatusCode(ACCEPTED_202.code()) .withReasonPhrase(ACCEPTED_202.reasonPhrase()) .withBody("some_body_response") .withCookies( cookie("responseCookieNameOne", "responseCookieValueOne"), cookie("responseCookieNameTwo", "responseCookieValueTwo") ) .withHeaders( header(SET_COOKIE.toString(), "responseCookieNameOne=responseCookieValueOne", "responseCookieNameTwo=responseCookieValueTwo") ), makeRequest( request() .withMethod("GET") .withSecure(true) .withPath(calculatePath("some_pathRequest")) .withHeaders( header("headerNameRequest", "headerValueRequest") ) .withCookies( cookie("requestCookieNameOne", "requestCookieValueOne"), cookie("requestCookieNameTwo", "requestCookieValueTwo") ), headersToIgnore) ); // - in https - cookie header assertEquals( response() .withStatusCode(ACCEPTED_202.code()) .withReasonPhrase(ACCEPTED_202.reasonPhrase()) .withBody("some_body_response") .withCookies( cookie("responseCookieNameOne", "responseCookieValueOne"), cookie("responseCookieNameTwo", "responseCookieValueTwo") ) .withHeaders( header(SET_COOKIE.toString(), "responseCookieNameOne=responseCookieValueOne", "responseCookieNameTwo=responseCookieValueTwo") ), makeRequest( request() .withMethod("GET") .withSecure(true) .withPath(calculatePath("some_pathRequest")) .withHeaders( header("headerNameRequest", "headerValueRequest"), header("Cookie", "requestCookieNameOne=requestCookieValueOne; requestCookieNameTwo=requestCookieValueTwo") ), headersToIgnore) ); } @Test public void shouldReturnResponseByMatchingPathAndMethodAndQueryStringParametersAndBodyParameters() { // when mockServerClient .when( request() .withMethod("POST") .withPath(calculatePath("some_pathRequest")) .withQueryStringParameters( param("queryStringParameterOneName", "queryStringParameterOneValueOne", "queryStringParameterOneValueTwo"), param("queryStringParameterTwoName", "queryStringParameterTwoValue") ) .withBody(params(param("bodyParameterName", "bodyParameterValue"))) ) .respond( response() .withStatusCode(ACCEPTED_202.code()) .withReasonPhrase(ACCEPTED_202.reasonPhrase()) .withBody("some_body") ); // then // - in http - url query string assertEquals( response() .withStatusCode(ACCEPTED_202.code()) .withReasonPhrase(ACCEPTED_202.reasonPhrase()) .withBody("some_body"), makeRequest( request() .withMethod("POST") .withPath(calculatePath("some_pathRequest")) .withQueryStringParameters( param("queryStringParameterOneName", "queryStringParameterOneValueOne", "queryStringParameterOneValueTwo"), param("queryStringParameterTwoName", "queryStringParameterTwoValue") ) .withBody(params(param("bodyParameterName", "bodyParameterValue"))), headersToIgnore) ); // - in https - query string parameter objects assertEquals( response() .withStatusCode(ACCEPTED_202.code()) .withReasonPhrase(ACCEPTED_202.reasonPhrase()) .withBody("some_body"), makeRequest( request() .withSecure(true) .withMethod("POST") .withPath(calculatePath("some_pathRequest")) .withQueryStringParameters( param("queryStringParameterOneName", "queryStringParameterOneValueOne", "queryStringParameterOneValueTwo"), param("queryStringParameterTwoName", "queryStringParameterTwoValue") ) .withBody(params(param("bodyParameterName", "bodyParameterValue"))), headersToIgnore) ); } @Test public void shouldReturnResponseByMatchingPathAndMethodAndQueryStringParametersAndBody() { // when mockServerClient .when( request() .withMethod("POST") .withPath(calculatePath("some_pathRequest")) .withQueryStringParameters( param("queryStringParameterOneName", "queryStringParameterOneValueOne", "queryStringParameterOneValueTwo"), param("queryStringParameterTwoName", "queryStringParameterTwoValue") ) .withBody("some_bodyRequest") ) .respond( response() .withStatusCode(ACCEPTED_202.code()) .withReasonPhrase(ACCEPTED_202.reasonPhrase()) .withBody("some_body_response") .withHeaders(header("headerNameResponse", "headerValueResponse")) .withCookies(cookie("cookieNameResponse", "cookieValueResponse")) ); // then // - in http - url query string assertEquals( response() .withStatusCode(ACCEPTED_202.code()) .withReasonPhrase(ACCEPTED_202.reasonPhrase()) .withBody("some_body_response") .withCookies(cookie("cookieNameResponse", "cookieValueResponse")) .withHeaders( header("headerNameResponse", "headerValueResponse"), header(SET_COOKIE.toString(), "cookieNameResponse=cookieValueResponse") ), makeRequest( request() .withMethod("POST") .withPath(calculatePath("some_pathRequest")) .withQueryStringParameters( param("queryStringParameterOneName", "queryStringParameterOneValueOne", "queryStringParameterOneValueTwo"), param("queryStringParameterTwoName", "queryStringParameterTwoValue") ) .withBody("some_bodyRequest") .withHeaders(header("headerNameRequest", "headerValueRequest")) .withCookies(cookie("cookieNameRequest", "cookieValueRequest")), headersToIgnore) ); // - in http - query string parameter objects assertEquals( response() .withStatusCode(ACCEPTED_202.code()) .withReasonPhrase(ACCEPTED_202.reasonPhrase()) .withBody("some_body_response") .withCookies(cookie("cookieNameResponse", "cookieValueResponse")) .withHeaders( header("headerNameResponse", "headerValueResponse"), header(SET_COOKIE.toString(), "cookieNameResponse=cookieValueResponse") ), makeRequest( request() .withMethod("POST") .withPath(calculatePath("some_pathRequest")) .withQueryStringParameters( param("queryStringParameterOneName", "queryStringParameterOneValueOne", "queryStringParameterOneValueTwo"), param("queryStringParameterTwoName", "queryStringParameterTwoValue") ) .withBody("some_bodyRequest") .withHeaders(header("headerNameRequest", "headerValueRequest")) .withCookies(cookie("cookieNameRequest", "cookieValueRequest")), headersToIgnore) ); // - in https - url string and query string parameter objects assertEquals( response() .withStatusCode(ACCEPTED_202.code()) .withReasonPhrase(ACCEPTED_202.reasonPhrase()) .withBody("some_body_response") .withCookies(cookie("cookieNameResponse", "cookieValueResponse")) .withHeaders( header("headerNameResponse", "headerValueResponse"), header(SET_COOKIE.toString(), "cookieNameResponse=cookieValueResponse") ), makeRequest( request() .withMethod("POST") .withPath(calculatePath("some_pathRequest")) .withQueryStringParameters( param("queryStringParameterOneName", "queryStringParameterOneValueOne", "queryStringParameterOneValueTwo"), param("queryStringParameterTwoName", "queryStringParameterTwoValue") ) .withBody("some_bodyRequest") .withHeaders(header("headerNameRequest", "headerValueRequest")) .withCookies(cookie("cookieNameRequest", "cookieValueRequest")), headersToIgnore) ); } @Test public void shouldReturnResponseByMatchingPathAndMethodAndBodyParameters() { // when mockServerClient .when( request() .withMethod("POST") .withPath(calculatePath("some_pathRequest")) .withBody(params( param("bodyParameterOneName", "Parameter One Value One", "Parameter One Value Two"), param("bodyParameterTwoName", "Parameter Two") )) ) .respond( response() .withStatusCode(ACCEPTED_202.code()) .withReasonPhrase(ACCEPTED_202.reasonPhrase()) .withBody("some_body_response") .withHeaders(header("headerNameResponse", "headerValueResponse")) .withCookies(cookie("cookieNameResponse", "cookieValueResponse")) ); // then // - in http - body string assertEquals( response() .withStatusCode(ACCEPTED_202.code()) .withReasonPhrase(ACCEPTED_202.reasonPhrase()) .withBody("some_body_response") .withCookies(cookie("cookieNameResponse", "cookieValueResponse")) .withHeaders( header("headerNameResponse", "headerValueResponse"), header(SET_COOKIE.toString(), "cookieNameResponse=cookieValueResponse") ), makeRequest( request() .withMethod("POST") .withPath(calculatePath("some_pathRequest")) .withBody(new StringBody("bodyParameterOneName=Parameter+One+Value+One" + "&bodyParameterOneName=Parameter+One+Value+Two" + "&bodyParameterTwoName=Parameter+Two")) .withHeaders(header("headerNameRequest", "headerValueRequest")) .withCookies(cookie("cookieNameRequest", "cookieValueRequest")), headersToIgnore) ); // - in http - body parameter objects assertEquals( response() .withStatusCode(ACCEPTED_202.code()) .withReasonPhrase(ACCEPTED_202.reasonPhrase()) .withBody("some_body_response") .withCookies(cookie("cookieNameResponse", "cookieValueResponse")) .withHeaders( header("headerNameResponse", "headerValueResponse"), header(SET_COOKIE.toString(), "cookieNameResponse=cookieValueResponse") ), makeRequest( request() .withMethod("POST") .withPath(calculatePath("some_pathRequest")) .withBody(params( param("bodyParameterOneName", "Parameter One Value One", "Parameter One Value Two"), param("bodyParameterTwoName", "Parameter Two") )) .withHeaders(header("headerNameRequest", "headerValueRequest")) .withCookies(cookie("cookieNameRequest", "cookieValueRequest")), headersToIgnore) ); // - in https - url string and query string parameter objects assertEquals( response() .withStatusCode(ACCEPTED_202.code()) .withReasonPhrase(ACCEPTED_202.reasonPhrase()) .withBody("some_body_response") .withCookies(cookie("cookieNameResponse", "cookieValueResponse")) .withHeaders( header("headerNameResponse", "headerValueResponse"), header(SET_COOKIE.toString(), "cookieNameResponse=cookieValueResponse") ), makeRequest( request() .withMethod("POST") .withPath(calculatePath("some_pathRequest")) .withBody(params( param("bodyParameterOneName", "Parameter One Value One", "Parameter One Value Two"), param("bodyParameterTwoName", "Parameter Two") )) .withHeaders(header("headerNameRequest", "headerValueRequest")) .withCookies(cookie("cookieNameRequest", "cookieValueRequest")), headersToIgnore) ); } @Test public void shouldReturnResponseByMatchingPathAndMethodAndParametersAndHeadersAndCookies() { // when mockServerClient .when( request() .withMethod("PUT") .withPath(calculatePath("some_pathRequest")) .withBody(new StringBody("bodyParameterOneName=Parameter+One+Value+One" + "&bodyParameterOneName=Parameter+One+Value+Two" + "&bodyParameterTwoName=Parameter+Two")) .withHeaders(header("headerNameRequest", "headerValueRequest")) .withCookies(cookie("cookieNameRequest", "cookieValueRequest")) ) .respond( response() .withStatusCode(ACCEPTED_202.code()) .withReasonPhrase(ACCEPTED_202.reasonPhrase()) .withBody("some_body_response") .withHeaders(header("headerNameResponse", "headerValueResponse")) .withCookies(cookie("cookieNameResponse", "cookieValueResponse")) ); // then // - in http - body string assertEquals( response() .withStatusCode(ACCEPTED_202.code()) .withReasonPhrase(ACCEPTED_202.reasonPhrase()) .withBody("some_body_response") .withCookies(cookie("cookieNameResponse", "cookieValueResponse")) .withHeaders( header("headerNameResponse", "headerValueResponse"), header(SET_COOKIE.toString(), "cookieNameResponse=cookieValueResponse") ), makeRequest( request() .withMethod("PUT") .withPath(calculatePath("some_pathRequest")) .withBody(new StringBody("bodyParameterOneName=Parameter+One+Value+One" + "&bodyParameterOneName=Parameter+One+Value+Two" + "&bodyParameterTwoName=Parameter+Two")) .withHeaders( header("headerNameRequest", "headerValueRequest"), header("Cookie", "cookieNameRequest=cookieValueRequest") ), headersToIgnore) ); // - in http - body parameter objects assertEquals( response() .withStatusCode(ACCEPTED_202.code()) .withReasonPhrase(ACCEPTED_202.reasonPhrase()) .withBody("some_body_response") .withCookies(cookie("cookieNameResponse", "cookieValueResponse")) .withHeaders( header("headerNameResponse", "headerValueResponse"), header(SET_COOKIE.toString(), "cookieNameResponse=cookieValueResponse") ), makeRequest( request() .withMethod("PUT") .withPath(calculatePath("some_pathRequest")) .withBody(params( param("bodyParameterOneName", "Parameter One Value One", "Parameter One Value Two"), param("bodyParameterTwoName", "Parameter Two") )) .withHeaders(header("headerNameRequest", "headerValueRequest")) .withCookies(cookie("cookieNameRequest", "cookieValueRequest")), headersToIgnore) ); } @Test public void shouldReturnResponseByNotMatchingBodyParameterWithNotOperatorForNameAndValue() { // when mockServerClient .when( request() .withMethod("POST") .withPath(calculatePath("some_pathRequest")) .withBody(params( param(not("bodyParameterOneName"), not("Parameter One Value One"), not("Parameter One Value Two")), param("bodyParameterTwoName", "Parameter Two") )) ) .respond( response() .withStatusCode(ACCEPTED_202.code()) .withReasonPhrase(ACCEPTED_202.reasonPhrase()) .withBody("some_body_response") ); // then // wrong query string parameter name assertEquals( response() .withStatusCode(ACCEPTED_202.code()) .withReasonPhrase(ACCEPTED_202.reasonPhrase()) .withBody("some_body_response"), makeRequest( request() .withMethod("POST") .withPath(calculatePath("some_pathRequest")) .withBody(params( param("OTHERBodyParameterOneName", "Parameter One Value One", "Parameter One Value Two"), param("bodyParameterTwoName", "Parameter Two") )) .withHeaders(header("headerNameRequest", "headerValueRequest")) .withCookies(cookie("cookieNameRequest", "cookieValueRequest")), headersToIgnore) ); // wrong query string parameter name assertEquals( response() .withStatusCode(ACCEPTED_202.code()) .withReasonPhrase(ACCEPTED_202.reasonPhrase()) .withBody("some_body_response"), makeRequest( request() .withMethod("POST") .withPath(calculatePath("some_pathRequest")) .withBody(new StringBody("OTHERBodyParameterOneName=Parameter+One+Value+One" + "&OTHERBodyParameterOneName=Parameter+One+Value+Two" + "&bodyParameterTwoName=Parameter+Two")) .withHeaders(header("headerNameRequest", "headerValueRequest")) .withCookies(cookie("cookieNameRequest", "cookieValueRequest")), headersToIgnore) ); // wrong query string parameter value assertEquals( response() .withStatusCode(ACCEPTED_202.code()) .withReasonPhrase(ACCEPTED_202.reasonPhrase()) .withBody("some_body_response"), makeRequest( request() .withMethod("POST") .withPath(calculatePath("some_pathRequest")) .withBody(params( param("bodyParameterOneName", "OTHER Parameter One Value One", "OTHER Parameter One Value Two"), param("bodyParameterTwoName", "Parameter Two") )) .withHeaders(header("headerNameRequest", "headerValueRequest")) .withCookies(cookie("cookieNameRequest", "cookieValueRequest")), headersToIgnore) ); // wrong query string parameter value assertEquals( response() .withStatusCode(ACCEPTED_202.code()) .withReasonPhrase(ACCEPTED_202.reasonPhrase()) .withBody("some_body_response"), makeRequest( request() .withMethod("POST") .withPath(calculatePath("some_pathRequest")) .withBody(new StringBody("bodyParameterOneName=OTHER Parameter+One+Value+One" + "&bodyParameterOneName=OTHER Parameter+One+Value+Two" + "&bodyParameterTwoName=Parameter+Two")) .withHeaders(header("headerNameRequest", "headerValueRequest")) .withCookies(cookie("cookieNameRequest", "cookieValueRequest")), headersToIgnore) ); } @Test public void shouldReturnResponseByNotMatchingBodyParameterWithNotOperatorForName() { // when mockServerClient .when( request() .withMethod("POST") .withPath(calculatePath("some_pathRequest")) .withBody(params( param(not("bodyParameterOneName"), string("Parameter One Value One"), string("Parameter One Value Two")), param("bodyParameterTwoName", "Parameter Two") )) ) .respond( response() .withStatusCode(ACCEPTED_202.code()) .withReasonPhrase(ACCEPTED_202.reasonPhrase()) .withBody("some_body_response") ); // then // wrong query string parameter name assertEquals( response() .withStatusCode(ACCEPTED_202.code()) .withReasonPhrase(ACCEPTED_202.reasonPhrase()) .withBody("some_body_response"), makeRequest( request() .withMethod("POST") .withPath(calculatePath("some_pathRequest")) .withBody(params( param("OTHERBodyParameterOneName", "Parameter One Value One", "Parameter One Value Two"), param("bodyParameterTwoName", "Parameter Two") )) .withHeaders(header("headerNameRequest", "headerValueRequest")) .withCookies(cookie("cookieNameRequest", "cookieValueRequest")), headersToIgnore) ); // wrong query string parameter name assertEquals( response() .withStatusCode(ACCEPTED_202.code()) .withReasonPhrase(ACCEPTED_202.reasonPhrase()) .withBody("some_body_response"), makeRequest( request() .withMethod("POST") .withPath(calculatePath("some_pathRequest")) .withBody(new StringBody("OTHERBodyParameterOneName=Parameter+One+Value+One" + "&OTHERBodyParameterOneName=Parameter+One+Value+Two" + "&bodyParameterTwoName=Parameter+Two")) .withHeaders(header("headerNameRequest", "headerValueRequest")) .withCookies(cookie("cookieNameRequest", "cookieValueRequest")), headersToIgnore) ); } @Test public void shouldReturnResponseByNotMatchingBodyParameterWithNotOperatorForValue() { // when mockServerClient .when( request() .withMethod("POST") .withPath(calculatePath("some_pathRequest")) .withBody(params( param(string("bodyParameterOneName"), not("Parameter One Value One"), not("Parameter One Value Two")), param("bodyParameterTwoName", "Parameter Two") )) ) .respond( response() .withStatusCode(ACCEPTED_202.code()) .withReasonPhrase(ACCEPTED_202.reasonPhrase()) .withBody("some_body_response") ); // then // wrong query string parameter value assertEquals( response() .withStatusCode(ACCEPTED_202.code()) .withReasonPhrase(ACCEPTED_202.reasonPhrase()) .withBody("some_body_response"), makeRequest( request() .withMethod("POST") .withPath(calculatePath("some_pathRequest")) .withBody(params( param("bodyParameterOneName", "OTHER Parameter One Value One", "OTHER Parameter One Value Two"), param("bodyParameterTwoName", "Parameter Two") )) .withHeaders(header("headerNameRequest", "headerValueRequest")) .withCookies(cookie("cookieNameRequest", "cookieValueRequest")), headersToIgnore) ); // wrong query string parameter value assertEquals( response() .withStatusCode(ACCEPTED_202.code()) .withReasonPhrase(ACCEPTED_202.reasonPhrase()) .withBody("some_body_response"), makeRequest( request() .withMethod("POST") .withPath(calculatePath("some_pathRequest")) .withBody(new StringBody("bodyParameterOneName=OTHER Parameter+One+Value+One" + "&bodyParameterOneName=OTHER Parameter+One+Value+Two" + "&bodyParameterTwoName=Parameter+Two")) .withHeaders(header("headerNameRequest", "headerValueRequest")) .withCookies(cookie("cookieNameRequest", "cookieValueRequest")), headersToIgnore) ); } @Test public void shouldReturnResponseByNotMatchingQueryStringParameterWithNotOperatorForNameAndValue() { // when mockServerClient .when( request() .withMethod("POST") .withPath(calculatePath("some_pathRequest")) .withQueryStringParameters( param(not("queryStringParameterOneName"), not("Parameter One Value One"), not("Parameter One Value Two")), param("queryStringParameterTwoName", "Parameter Two") ) ) .respond( response() .withStatusCode(ACCEPTED_202.code()) .withReasonPhrase(ACCEPTED_202.reasonPhrase()) .withBody("some_body_response") ); // then // wrong query string parameter name assertEquals( response() .withStatusCode(ACCEPTED_202.code()) .withReasonPhrase(ACCEPTED_202.reasonPhrase()) .withBody("some_body_response"), makeRequest( request() .withMethod("POST") .withPath(calculatePath("some_pathRequest")) .withQueryStringParameters( param("OTHERQueryStringParameterOneName", "Parameter One Value One", "Parameter One Value Two"), param("queryStringParameterTwoName", "Parameter Two") ), headersToIgnore) ); // wrong query string parameter value assertEquals( response() .withStatusCode(ACCEPTED_202.code()) .withReasonPhrase(ACCEPTED_202.reasonPhrase()) .withBody("some_body_response"), makeRequest( request() .withMethod("POST") .withPath(calculatePath("some_pathRequest")) .withQueryStringParameters( param("queryStringParameterOneName", "OTHER Parameter One Value One", "OTHER Parameter One Value Two"), param("queryStringParameterTwoName", "Parameter Two") ), headersToIgnore) ); } @Test public void shouldReturnResponseByNotMatchingQueryStringParameterWithNotOperatorForName() { // when mockServerClient .when( request() .withMethod("POST") .withPath(calculatePath("some_pathRequest")) .withQueryStringParameters( param(not("queryStringParameterOneName"), string("Parameter One Value One"), string("Parameter One Value Two")), param("queryStringParameterTwoName", "Parameter Two") ) ) .respond( response() .withStatusCode(ACCEPTED_202.code()) .withReasonPhrase(ACCEPTED_202.reasonPhrase()) .withBody("some_body_response") ); // then // wrong query string parameter name assertEquals( response() .withStatusCode(ACCEPTED_202.code()) .withReasonPhrase(ACCEPTED_202.reasonPhrase()) .withBody("some_body_response"), makeRequest( request() .withMethod("POST") .withPath(calculatePath("some_pathRequest")) .withQueryStringParameters( param("OTHERQueryStringParameterOneName", "Parameter One Value One", "Parameter One Value Two"), param("queryStringParameterTwoName", "Parameter Two") ), headersToIgnore) ); } @Test public void shouldReturnResponseByNotMatchingQueryStringParameterWithNotOperatorForValue() { // when mockServerClient .when( request() .withMethod("POST") .withPath(calculatePath("some_pathRequest")) .withQueryStringParameters( param(string("queryStringParameterOneName"), not("Parameter One Value One"), not("Parameter One Value Two")), param("queryStringParameterTwoName", "Parameter Two") ) ) .respond( response() .withStatusCode(ACCEPTED_202.code()) .withReasonPhrase(ACCEPTED_202.reasonPhrase()) .withBody("some_body_response") ); // then // wrong query string parameter value assertEquals( response() .withStatusCode(ACCEPTED_202.code()) .withReasonPhrase(ACCEPTED_202.reasonPhrase()) .withBody("some_body_response"), makeRequest( request() .withMethod("POST") .withPath(calculatePath("some_pathRequest")) .withQueryStringParameters( param("queryStringParameterOneName", "OTHER Parameter One Value One", "OTHER Parameter One Value Two"), param("queryStringParameterTwoName", "Parameter Two") ), headersToIgnore) ); } @Test public void shouldReturnResponseByNotMatchingCookieWithNotOperatorForNameAndValue() { // when mockServerClient .when( request() .withMethod("GET") .withPath(calculatePath("some_pathRequest")) .withCookies( cookie(not("requestCookieNameOne"), not("requestCookieValueOne")), cookie("requestCookieNameTwo", "requestCookieValueTwo") ) ) .respond( response() .withStatusCode(ACCEPTED_202.code()) .withReasonPhrase(ACCEPTED_202.reasonPhrase()) .withBody("some_body_response") ); // then // wrong query string cookie name assertEquals( response() .withStatusCode(ACCEPTED_202.code()) .withReasonPhrase(ACCEPTED_202.reasonPhrase()) .withBody("some_body_response"), makeRequest( request() .withMethod("GET") .withPath(calculatePath("some_pathRequest")) .withCookies( cookie("OTHERrequestCookieNameOne", "requestCookieValueOne"), cookie("requestCookieNameTwo", "requestCookieValueTwo") ), headersToIgnore) ); // wrong query string cookie value assertEquals( response() .withStatusCode(ACCEPTED_202.code()) .withReasonPhrase(ACCEPTED_202.reasonPhrase()) .withBody("some_body_response"), makeRequest( request() .withMethod("GET") .withPath(calculatePath("some_pathRequest")) .withCookies( cookie("requestCookieNameOne", "OTHERrequestCookieValueOne"), cookie("requestCookieNameTwo", "requestCookieValueTwo") ), headersToIgnore) ); } @Test public void shouldReturnResponseByNotMatchingCookieWithNotOperatorForName() { // when mockServerClient .when( request() .withMethod("GET") .withPath(calculatePath("some_pathRequest")) .withCookies( cookie(not("requestCookieNameOne"), string("requestCookieValueOne")), cookie("requestCookieNameTwo", "requestCookieValueTwo") ) ) .respond( response() .withStatusCode(ACCEPTED_202.code()) .withReasonPhrase(ACCEPTED_202.reasonPhrase()) .withBody("some_body_response") ); // then // wrong query string cookie name assertEquals( response() .withStatusCode(ACCEPTED_202.code()) .withReasonPhrase(ACCEPTED_202.reasonPhrase()) .withBody("some_body_response"), makeRequest( request() .withMethod("GET") .withPath(calculatePath("some_pathRequest")) .withCookies( cookie("OTHERrequestCookieNameOne", "requestCookieValueOne"), cookie("requestCookieNameTwo", "requestCookieValueTwo") ), headersToIgnore) ); } @Test public void shouldReturnResponseByNotMatchingCookieWithNotOperatorForValue() { // when mockServerClient .when( request() .withMethod("GET") .withPath(calculatePath("some_pathRequest")) .withCookies( cookie(string("requestCookieNameOne"), not("requestCookieValueOne")), cookie("requestCookieNameTwo", "requestCookieValueTwo") ) ) .respond( response() .withStatusCode(ACCEPTED_202.code()) .withReasonPhrase(ACCEPTED_202.reasonPhrase()) .withBody("some_body_response") ); // then // wrong query string cookie value assertEquals( response() .withStatusCode(ACCEPTED_202.code()) .withReasonPhrase(ACCEPTED_202.reasonPhrase()) .withBody("some_body_response"), makeRequest( request() .withMethod("GET") .withPath(calculatePath("some_pathRequest")) .withCookies( cookie("requestCookieNameOne", "OTHERrequestCookieValueOne"), cookie("requestCookieNameTwo", "requestCookieValueTwo") ), headersToIgnore) ); } @Test public void shouldReturnResponseByNotMatchingHeaderWithNotOperatorForNameAndValue() { // when mockServerClient .when( request() .withMethod("GET") .withPath(calculatePath("some_pathRequest")) .withHeaders( header(not("requestHeaderNameOne"), not("requestHeaderValueOne")), header("requestHeaderNameTwo", "requestHeaderValueTwo") ) ) .respond( response() .withStatusCode(ACCEPTED_202.code()) .withReasonPhrase(ACCEPTED_202.reasonPhrase()) .withBody("some_body_response") ); // then // wrong query string header name assertEquals( response() .withStatusCode(ACCEPTED_202.code()) .withReasonPhrase(ACCEPTED_202.reasonPhrase()) .withBody("some_body_response"), makeRequest( request() .withMethod("GET") .withPath(calculatePath("some_pathRequest")) .withHeaders( header("OTHERrequestHeaderNameOne", "requestHeaderValueOne"), header("requestHeaderNameTwo", "requestHeaderValueTwo") ), headersToIgnore) ); // wrong query string header value assertEquals( response() .withStatusCode(ACCEPTED_202.code()) .withReasonPhrase(ACCEPTED_202.reasonPhrase()) .withBody("some_body_response"), makeRequest( request() .withMethod("GET") .withPath(calculatePath("some_pathRequest")) .withHeaders( header("requestHeaderNameOne", "OTHERrequestHeaderValueOne"), header("requestHeaderNameTwo", "requestHeaderValueTwo") ), headersToIgnore) ); } @Test public void shouldReturnResponseByNotMatchingHeaderWithNotOperatorForName() { // when mockServerClient .when( request() .withMethod("GET") .withPath(calculatePath("some_pathRequest")) .withHeaders( header(not("requestHeaderNameOne"), string("requestHeaderValueOne")), header("requestHeaderNameTwo", "requestHeaderValueTwo") ) ) .respond( response() .withStatusCode(ACCEPTED_202.code()) .withReasonPhrase(ACCEPTED_202.reasonPhrase()) .withBody("some_body_response") ); // then // wrong query string header name assertEquals( response() .withStatusCode(ACCEPTED_202.code()) .withReasonPhrase(ACCEPTED_202.reasonPhrase()) .withBody("some_body_response"), makeRequest( request() .withMethod("GET") .withPath(calculatePath("some_pathRequest")) .withHeaders( header("OTHERrequestHeaderNameOne", "requestHeaderValueOne"), header("requestHeaderNameTwo", "requestHeaderValueTwo") ), headersToIgnore) ); } @Test public void shouldReturnResponseByNotMatchingHeaderWithNotOperatorForValue() { // when mockServerClient .when( request() .withMethod("GET") .withPath(calculatePath("some_pathRequest")) .withHeaders( header(string("requestHeaderNameOne"), not("requestHeaderValueOne")), header("requestHeaderNameTwo", "requestHeaderValueTwo") ) ) .respond( response() .withStatusCode(ACCEPTED_202.code()) .withReasonPhrase(ACCEPTED_202.reasonPhrase()) .withBody("some_body_response") ); // then // wrong query string header value assertEquals( response() .withStatusCode(ACCEPTED_202.code()) .withReasonPhrase(ACCEPTED_202.reasonPhrase()) .withBody("some_body_response"), makeRequest( request() .withMethod("GET") .withPath(calculatePath("some_pathRequest")) .withHeaders( header("requestHeaderNameOne", "OTHERrequestHeaderValueOne"), header("requestHeaderNameTwo", "requestHeaderValueTwo") ), headersToIgnore) ); } @Test public void shouldNotReturnResponseForWhenTimeToLiveExpired() { // when mockServerClient .when( request().withPath(calculatePath("some_path")), exactly(2), TimeToLive.exactly(TimeUnit.SECONDS, 3L) ) .respond( response().withBody("some_body").withDelay(TimeUnit.SECONDS, 3L) ); // then assertEquals( response() .withStatusCode(OK_200.code()) .withReasonPhrase(OK_200.reasonPhrase()) .withBody("some_body"), makeRequest( request() .withPath(calculatePath("some_path")), headersToIgnore) ); // - in http assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()) .withReasonPhrase(HttpStatusCode.NOT_FOUND_404.reasonPhrase()), makeRequest( request() .withPath(calculatePath("some_path")), headersToIgnore) ); // - in https assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()) .withReasonPhrase(HttpStatusCode.NOT_FOUND_404.reasonPhrase()), makeRequest( request() .withSecure(true) .withPath(calculatePath("some_path")), headersToIgnore) ); } @Test public void shouldNotReturnResponseForMatchingBodyWithNotOperator() { // when mockServerClient .when( request() .withBody(Not.not(json("{" + NEW_LINE + " \"id\": 1," + NEW_LINE + " \"name\": \"A green door\"," + NEW_LINE + " \"price\": 12.50," + NEW_LINE + " \"tags\": [\"home\", \"green\"]" + NEW_LINE + "}"))), exactly(2) ) .respond( response() .withStatusCode(ACCEPTED_202.code()) .withReasonPhrase(ACCEPTED_202.reasonPhrase()) .withBody("some_body") ); // then // - in http assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()) .withReasonPhrase(HttpStatusCode.NOT_FOUND_404.reasonPhrase()), makeRequest( request() .withPath(calculatePath("some_path")) .withMethod("POST") .withBody("{" + NEW_LINE + " \"id\": 1," + NEW_LINE + " \"extra_ignored_field\": \"some value\"," + NEW_LINE + " \"name\": \"A green door\"," + NEW_LINE + " \"price\": 12.50," + NEW_LINE + " \"tags\": [\"home\", \"green\"]" + NEW_LINE + "}"), headersToIgnore) ); // - in https assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()) .withReasonPhrase(HttpStatusCode.NOT_FOUND_404.reasonPhrase()), makeRequest( request() .withSecure(true) .withPath(calculatePath("some_path")) .withMethod("POST") .withBody("{" + NEW_LINE + " \"id\": 1," + NEW_LINE + " \"extra_ignored_array\": [\"one\", \"two\"]," + NEW_LINE + " \"name\": \"A green door\"," + NEW_LINE + " \"price\": 12.50," + NEW_LINE + " \"tags\": [\"home\", \"green\"]" + NEW_LINE + "}"), headersToIgnore) ); } @Test public void shouldNotReturnResponseForNonMatchingXPathBody() { // when mockServerClient.when(request().withBody(new XPathBody("/bookstore/book[price>35]/price")), exactly(2)).respond(response().withBody("some_body")); // then // - in http assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()) .withReasonPhrase(HttpStatusCode.NOT_FOUND_404.reasonPhrase()), makeRequest( request() .withSecure(true) .withPath(calculatePath("some_path")) .withMethod("POST") .withBody(new StringBody("" + "<?xml version=\"1.0\" encoding=\"ISO-8859-1\"?>" + NEW_LINE + "<bookstore>" + NEW_LINE + " <book category=\"COOKING\">" + NEW_LINE + " <title lang=\"en\">Everyday Italian</title>" + NEW_LINE + " <author>Giada De Laurentiis</author>" + NEW_LINE + " <year>2005</year>" + NEW_LINE + " <price>30.00</price>" + NEW_LINE + " </book>" + NEW_LINE + " <book category=\"CHILDREN\">" + NEW_LINE + " <title lang=\"en\">Harry Potter</title>" + NEW_LINE + " <author>J K. Rowling</author>" + NEW_LINE + " <year>2005</year>" + NEW_LINE + " <price>29.99</price>" + NEW_LINE + " </book>" + NEW_LINE + " <book category=\"WEB\">" + NEW_LINE + " <title lang=\"en\">Learning XML</title>" + NEW_LINE + " <author>Erik T. Ray</author>" + NEW_LINE + " <year>2003</year>" + NEW_LINE + " <price>31.95</price>" + NEW_LINE + " </book>" + NEW_LINE + "</bookstore>")), headersToIgnore) ); // - in https assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()) .withReasonPhrase(HttpStatusCode.NOT_FOUND_404.reasonPhrase()), makeRequest( request() .withSecure(true) .withPath(calculatePath("some_path")) .withMethod("POST") .withBody(new StringBody("" + "<?xml version=\"1.0\" encoding=\"ISO-8859-1\"?>" + NEW_LINE + "<bookstore>" + NEW_LINE + " <book category=\"COOKING\">" + NEW_LINE + " <title lang=\"en\">Everyday Italian</title>" + NEW_LINE + " <author>Giada De Laurentiis</author>" + NEW_LINE + " <year>2005</year>" + NEW_LINE + " <price>30.00</price>" + NEW_LINE + " </book>" + NEW_LINE + " <book category=\"CHILDREN\">" + NEW_LINE + " <title lang=\"en\">Harry Potter</title>" + NEW_LINE + " <author>J K. Rowling</author>" + NEW_LINE + " <year>2005</year>" + NEW_LINE + " <price>29.99</price>" + NEW_LINE + " </book>" + NEW_LINE + " <book category=\"WEB\">" + NEW_LINE + " <title lang=\"en\">Learning XML</title>" + NEW_LINE + " <author>Erik T. Ray</author>" + NEW_LINE + " <year>2003</year>" + NEW_LINE + " <price>31.95</price>" + NEW_LINE + " </book>" + NEW_LINE + "</bookstore>")), headersToIgnore) ); } @Test public void shouldNotReturnResponseForNonMatchingXmlBody() { // when mockServerClient.when(request().withBody(xml("" + "<?xml version=\"1.0\" encoding=\"ISO-8859-1\"?>" + NEW_LINE + "<bookstore>" + NEW_LINE + " <book category=\"COOKING\" nationality=\"ITALIAN\">" + NEW_LINE + " <title lang=\"en\">Everyday Italian</title>" + NEW_LINE + " <author>Giada De Laurentiis</author>" + NEW_LINE + " <year>2005</year>" + NEW_LINE + " <price>30.00</price>" + NEW_LINE + " </book>" + NEW_LINE + "</bookstore>")), exactly(2)).respond(response().withBody("some_body")); // then // - in http assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()) .withReasonPhrase(HttpStatusCode.NOT_FOUND_404.reasonPhrase()), makeRequest( request() .withSecure(true) .withPath(calculatePath("some_path")) .withMethod("POST") .withBody(new StringBody("" + "<?xml version=\"1.0\" encoding=\"ISO-8859-1\"?>" + NEW_LINE + "<bookstore>" + NEW_LINE + " <book category=\"COOKING\">" + NEW_LINE + " <title lang=\"en\">Everyday Italian</title>" + NEW_LINE + " <author>Giada De Laurentiis</author>" + NEW_LINE + " <year>2005</year>" + NEW_LINE + " <price>30.00</price>" + NEW_LINE + " </book>" + NEW_LINE + "</bookstore>")), headersToIgnore) ); // - in https assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()) .withReasonPhrase(HttpStatusCode.NOT_FOUND_404.reasonPhrase()), makeRequest( request() .withSecure(true) .withPath(calculatePath("some_path")) .withMethod("POST") .withBody(new StringBody("" + "<?xml version=\"1.0\" encoding=\"ISO-8859-1\"?>" + NEW_LINE + "<bookstore>" + NEW_LINE + " <book category=\"COOKING\">" + NEW_LINE + " <title lang=\"en\">Everyday Italian</title>" + NEW_LINE + " <author>Giada De Laurentiis</author>" + NEW_LINE + " <year>2005</year>" + NEW_LINE + " <price>30.00</price>" + NEW_LINE + " </book>" + NEW_LINE + "</bookstore>")), headersToIgnore) ); } @Test public void shouldNotReturnResponseForNonMatchingJsonBody() { // when mockServerClient.when(request().withBody(json("{" + NEW_LINE + " \"id\": 1," + NEW_LINE + " \"name\": \"A green door\"," + NEW_LINE + " \"price\": 12.50," + NEW_LINE + " \"tags\": [\"home\", \"green\"]" + NEW_LINE + "}")), exactly(2)).respond(response().withBody("some_body")); // then // - in http assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()) .withReasonPhrase(HttpStatusCode.NOT_FOUND_404.reasonPhrase()), makeRequest( request() .withPath(calculatePath("some_path")) .withMethod("POST") .withBody("{" + NEW_LINE + " \"id\": 1," + NEW_LINE + " \"name\": \"---- XXXX WRONG VALUE XXXX ----\"," + NEW_LINE + " \"price\": 12.50," + NEW_LINE + " \"tags\": [\"home\", \"green\"]" + NEW_LINE + "}"), headersToIgnore) ); // - in https assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()) .withReasonPhrase(HttpStatusCode.NOT_FOUND_404.reasonPhrase()), makeRequest( request() .withSecure(true) .withPath(calculatePath("some_path")) .withMethod("POST") .withBody("{" + NEW_LINE + " \"id\": 1," + NEW_LINE + " \"name\": \"---- XXXX WRONG VALUE XXXX ----\"," + NEW_LINE + " \"price\": 12.50," + NEW_LINE + " \"tags\": [\"home\", \"green\"]" + NEW_LINE + "}"), headersToIgnore) ); } @Test public void shouldNotReturnResponseForNonMatchingJsonBodyWithMatchType() { // when mockServerClient .when( request() .withBody(json("{" + NEW_LINE + " \"id\": 1," + NEW_LINE + " \"name\": \"A green door\"," + NEW_LINE + " \"price\": 12.50," + NEW_LINE + " \"tags\": [\"home\", \"green\"]" + NEW_LINE + "}", MatchType.STRICT)), exactly(2)) .respond( response() .withBody("some_body") ); // then // - in http assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()) .withReasonPhrase(HttpStatusCode.NOT_FOUND_404.reasonPhrase()), makeRequest( request() .withPath(calculatePath("some_path")) .withMethod("POST") .withBody("{" + NEW_LINE + " \"id\": 1," + NEW_LINE + " \"extra field\": \"some value\"," + NEW_LINE + " \"name\": \"A green door\"," + NEW_LINE + " \"price\": 12.50," + NEW_LINE + " \"tags\": [\"home\", \"green\"]" + NEW_LINE + "}"), headersToIgnore) ); // - in https assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()) .withReasonPhrase(HttpStatusCode.NOT_FOUND_404.reasonPhrase()), makeRequest( request() .withSecure(true) .withPath(calculatePath("some_path")) .withMethod("POST") .withBody("{" + NEW_LINE + " \"id\": 1," + NEW_LINE + " \"extra field\": \"some value\"," + NEW_LINE + " \"name\": \"A green door\"," + NEW_LINE + " \"price\": 12.50," + NEW_LINE + " \"tags\": [\"home\", \"green\"]" + NEW_LINE + "}"), headersToIgnore) ); } @Test public void shouldNotReturnResponseForNonMatchingJsonSchema() { // when mockServerClient.when(request().withBody(jsonSchema("{" + NEW_LINE + " \"$schema\": \"http://json-schema.org/draft-04/schema#\"," + NEW_LINE + " \"title\": \"Product\"," + NEW_LINE + " \"description\": \"A product from Acme's catalog\"," + NEW_LINE + " \"type\": \"object\"," + NEW_LINE + " \"properties\": {" + NEW_LINE + " \"id\": {" + NEW_LINE + " \"description\": \"The unique identifier for a product\"," + NEW_LINE + " \"type\": \"integer\"" + NEW_LINE + " }," + NEW_LINE + " \"name\": {" + NEW_LINE + " \"description\": \"Name of the product\"," + NEW_LINE + " \"type\": \"string\"" + NEW_LINE + " }," + NEW_LINE + " \"price\": {" + NEW_LINE + " \"type\": \"number\"," + NEW_LINE + " \"minimum\": 0," + NEW_LINE + " \"exclusiveMinimum\": true" + NEW_LINE + " }," + NEW_LINE + " \"tags\": {" + NEW_LINE + " \"type\": \"array\"," + NEW_LINE + " \"items\": {" + NEW_LINE + " \"type\": \"string\"" + NEW_LINE + " }," + NEW_LINE + " \"minItems\": 1," + NEW_LINE + " \"uniqueItems\": true" + NEW_LINE + " }" + NEW_LINE + " }," + NEW_LINE + " \"required\": [\"id\", \"name\", \"price\"]" + NEW_LINE + "}")), exactly(2)).respond(response().withBody("some_body")); // then // - in http assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()) .withReasonPhrase(HttpStatusCode.NOT_FOUND_404.reasonPhrase()), makeRequest( request() .withPath(calculatePath("some_path")) .withMethod("POST") .withBody("{" + NEW_LINE + " \"id\": 1," + NEW_LINE + " \"wrong field name\": \"A green door\"," + NEW_LINE + " \"price\": 12.50," + NEW_LINE + " \"tags\": [\"home\", \"green\"]" + NEW_LINE + "}"), headersToIgnore) ); // - in https assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()) .withReasonPhrase(HttpStatusCode.NOT_FOUND_404.reasonPhrase()), makeRequest( request() .withSecure(true) .withPath(calculatePath("some_path")) .withMethod("POST") .withBody("{" + NEW_LINE + " \"id\": 1," + NEW_LINE + " \"name\": \"A green door\"," + NEW_LINE + " \"wrong field name\": 12.50," + NEW_LINE + " \"tags\": [\"home\", \"green\"]" + NEW_LINE + "}"), headersToIgnore) ); } @Test public void shouldNotReturnResponseForNonMatchingJsonPathBody() { // when mockServerClient.when(request().withBody(new JsonPathBody("$..book[?(@.price > $['expensive'])]")), exactly(2)).respond(response().withBody("some_body")); // then // - in http assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()) .withReasonPhrase(HttpStatusCode.NOT_FOUND_404.reasonPhrase()), makeRequest( request() .withSecure(true) .withPath(calculatePath("some_path")) .withMethod("POST") .withBody(new StringBody("" + "{" + NEW_LINE + " \"store\": {" + NEW_LINE + " \"book\": [" + NEW_LINE + " {" + NEW_LINE + " \"category\": \"reference\"," + NEW_LINE + " \"author\": \"Nigel Rees\"," + NEW_LINE + " \"title\": \"Sayings of the Century\"," + NEW_LINE + " \"price\": 8.95" + NEW_LINE + " }," + NEW_LINE + " {" + NEW_LINE + " \"category\": \"fiction\"," + NEW_LINE + " \"author\": \"Herman Melville\"," + NEW_LINE + " \"title\": \"Moby Dick\"," + NEW_LINE + " \"isbn\": \"0-553-21311-3\"," + NEW_LINE + " \"price\": 8.99" + NEW_LINE + " }" + NEW_LINE + " ]," + NEW_LINE + " \"bicycle\": {" + NEW_LINE + " \"color\": \"red\"," + NEW_LINE + " \"price\": 19.95" + NEW_LINE + " }" + NEW_LINE + " }," + NEW_LINE + " \"expensive\": 10" + NEW_LINE + "}")), headersToIgnore) ); // - in https assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()) .withReasonPhrase(HttpStatusCode.NOT_FOUND_404.reasonPhrase()), makeRequest( request() .withSecure(true) .withPath(calculatePath("some_path")) .withMethod("POST") .withBody(new StringBody("" + "{" + NEW_LINE + " \"store\": {" + NEW_LINE + " \"book\": [" + NEW_LINE + " {" + NEW_LINE + " \"category\": \"reference\"," + NEW_LINE + " \"author\": \"Nigel Rees\"," + NEW_LINE + " \"title\": \"Sayings of the Century\"," + NEW_LINE + " \"price\": 8.95" + NEW_LINE + " }," + NEW_LINE + " {" + NEW_LINE + " \"category\": \"fiction\"," + NEW_LINE + " \"author\": \"Herman Melville\"," + NEW_LINE + " \"title\": \"Moby Dick\"," + NEW_LINE + " \"isbn\": \"0-553-21311-3\"," + NEW_LINE + " \"price\": 8.99" + NEW_LINE + " }" + NEW_LINE + " ]," + NEW_LINE + " \"bicycle\": {" + NEW_LINE + " \"color\": \"red\"," + NEW_LINE + " \"price\": 19.95" + NEW_LINE + " }" + NEW_LINE + " }," + NEW_LINE + " \"expensive\": 10" + NEW_LINE + "}")), headersToIgnore) ); } @Test public void shouldNotReturnResponseForMatchingPathWithNotOperator() { // when mockServerClient .when( request() .withPath(not(calculatePath("some_path"))) ) .respond( response() .withStatusCode(ACCEPTED_202.code()) .withReasonPhrase(ACCEPTED_202.reasonPhrase()) .withBody("some_body_response") ); // then // - in http assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()) .withReasonPhrase(HttpStatusCode.NOT_FOUND_404.reasonPhrase()), makeRequest( request() .withPath(calculatePath("some_path")), headersToIgnore) ); // - in https assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()) .withReasonPhrase(HttpStatusCode.NOT_FOUND_404.reasonPhrase()), makeRequest( request() .withPath(calculatePath("some_path")), headersToIgnore) ); } @Test public void shouldNotReturnResponseForMatchingMethodWithNotOperator() { // when mockServerClient .when( request() .withMethod(not("GET")) ) .respond( response() .withStatusCode(ACCEPTED_202.code()) .withReasonPhrase(ACCEPTED_202.reasonPhrase()) .withBody("some_body_response") ); // then // - in http assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()) .withReasonPhrase(HttpStatusCode.NOT_FOUND_404.reasonPhrase()), makeRequest( request() .withMethod("GET"), headersToIgnore) ); // - in https assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()) .withReasonPhrase(HttpStatusCode.NOT_FOUND_404.reasonPhrase()), makeRequest( request() .withMethod("GET"), headersToIgnore) ); } @Test public void shouldNotReturnResponseForNonMatchingBodyParameterName() { // when mockServerClient .when( request() .withMethod("POST") .withPath(calculatePath("some_pathRequest")) .withBody(params( param("bodyParameterOneName", "Parameter One Value One", "Parameter One Value Two"), param("bodyParameterTwoName", "Parameter Two") )) ) .respond( response() .withStatusCode(ACCEPTED_202.code()) .withReasonPhrase(ACCEPTED_202.reasonPhrase()) .withBody("some_body_response") .withHeaders(header("headerNameResponse", "headerValueResponse")) .withCookies(cookie("cookieNameResponse", "cookieValueResponse")) ); // then // wrong query string parameter name assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()) .withReasonPhrase(HttpStatusCode.NOT_FOUND_404.reasonPhrase()), makeRequest( request() .withMethod("POST") .withPath(calculatePath("some_pathRequest")) .withBody(params( param("OTHERBodyParameterOneName", "Parameter One Value One", "Parameter One Value Two"), param("bodyParameterTwoName", "Parameter Two") )) .withHeaders(header("headerNameRequest", "headerValueRequest")) .withCookies(cookie("cookieNameRequest", "cookieValueRequest")), headersToIgnore) ); // wrong query string parameter name assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()) .withReasonPhrase(HttpStatusCode.NOT_FOUND_404.reasonPhrase()), makeRequest( request() .withMethod("POST") .withPath(calculatePath("some_pathRequest")) .withBody(new StringBody("OTHERBodyParameterOneName=Parameter+One+Value+One" + "&bodyParameterOneName=Parameter+One+Value+Two" + "&bodyParameterTwoName=Parameter+Two")) .withHeaders(header("headerNameRequest", "headerValueRequest")) .withCookies(cookie("cookieNameRequest", "cookieValueRequest")), headersToIgnore) ); } @Test public void shouldNotReturnResponseForMatchingBodyParameterWithNotOperator() { // when mockServerClient .when( request() .withMethod("POST") .withPath(calculatePath("some_pathRequest")) .withBody(params( param(not("bodyParameterOneName"), not("Parameter One Value One"), not("Parameter One Value Two")), param("bodyParameterTwoName", "Parameter Two") )) ) .respond( response() .withStatusCode(ACCEPTED_202.code()) .withReasonPhrase(ACCEPTED_202.reasonPhrase()) .withBody("some_body_response") ); // then // wrong query string parameter name assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()) .withReasonPhrase(HttpStatusCode.NOT_FOUND_404.reasonPhrase()), makeRequest( request() .withMethod("POST") .withPath(calculatePath("some_pathRequest")) .withBody(params( param("bodyParameterOneName", "Parameter One Value One", "Parameter One Value Two"), param("bodyParameterTwoName", "Parameter Two") )) .withHeaders(header("headerNameRequest", "headerValueRequest")) .withCookies(cookie("cookieNameRequest", "cookieValueRequest")), headersToIgnore) ); // wrong query string parameter name assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()) .withReasonPhrase(HttpStatusCode.NOT_FOUND_404.reasonPhrase()), makeRequest( request() .withMethod("POST") .withPath(calculatePath("some_pathRequest")) .withBody(new StringBody("bodyParameterOneName=Other Parameter+One+Value+One" + "&bodyParameterOneName=Parameter+One+Value+Two" + "&bodyParameterTwoName=Parameter+Two")) .withHeaders(header("headerNameRequest", "headerValueRequest")) .withCookies(cookie("cookieNameRequest", "cookieValueRequest")), headersToIgnore) ); } @Test public void shouldNotReturnResponseForNonMatchingBodyParameterValue() { // when mockServerClient .when( request() .withMethod("POST") .withPath(calculatePath("some_pathRequest")) .withBody(params( param("bodyParameterOneName", "Parameter One Value One", "Parameter One Value Two"), param("bodyParameterTwoName", "Parameter Two") )) ) .respond( response() .withStatusCode(ACCEPTED_202.code()) .withReasonPhrase(ACCEPTED_202.reasonPhrase()) .withBody("some_body_response") .withHeaders(header("headerNameResponse", "headerValueResponse")) .withCookies(cookie("cookieNameResponse", "cookieValueResponse")) ); // then // wrong body parameter value assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()) .withReasonPhrase(HttpStatusCode.NOT_FOUND_404.reasonPhrase()), makeRequest( request() .withMethod("POST") .withPath(calculatePath("some_pathRequest")) .withBody(params( param("bodyParameterOneName", "Other Parameter One Value One", "Parameter One Value Two"), param("bodyParameterTwoName", "Parameter Two") )) .withHeaders(header("headerNameRequest", "headerValueRequest")) .withCookies(cookie("cookieNameRequest", "cookieValueRequest")), headersToIgnore) ); // wrong body parameter value assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()) .withReasonPhrase(HttpStatusCode.NOT_FOUND_404.reasonPhrase()), makeRequest( request() .withMethod("POST") .withPath(calculatePath("some_pathRequest")) .withBody(new StringBody("bodyParameterOneName=Other Parameter+One+Value+One" + "&bodyParameterOneName=Parameter+One+Value+Two" + "&bodyParameterTwoName=Parameter+Two")) .withHeaders(header("headerNameRequest", "headerValueRequest")) .withCookies(cookie("cookieNameRequest", "cookieValueRequest")), headersToIgnore) ); } @Test public void shouldNotReturnResponseForNonMatchingQueryStringParameterName() { // when mockServerClient .when( request() .withMethod("POST") .withPath(calculatePath("some_pathRequest")) .withQueryStringParameters( param("queryStringParameterOneName", "queryStringParameterOneValueOne", "queryStringParameterOneValueTwo"), param("queryStringParameterTwoName", "queryStringParameterTwoValue") ) .withBody("some_bodyRequest") ) .respond( response() .withStatusCode(ACCEPTED_202.code()) .withReasonPhrase(ACCEPTED_202.reasonPhrase()) .withBody("some_body_response") .withHeaders(header("headerNameResponse", "headerValueResponse")) .withCookies(cookie("cookieNameResponse", "cookieValueResponse")) ); // then // wrong query string parameter name assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()) .withReasonPhrase(HttpStatusCode.NOT_FOUND_404.reasonPhrase()), makeRequest( request() .withMethod("POST") .withPath(calculatePath("some_pathRequest")) .withQueryStringParameters( param("OTHERQueryStringParameterOneName", "queryStringParameterOneValueOne", "queryStringParameterOneValueTwo"), param("queryStringParameterTwoName", "queryStringParameterTwoValue") ) .withBody("some_bodyRequest") .withHeaders( header("headerNameRequest", "headerValueRequest") ) .withCookies(cookie("cookieNameRequest", "cookieValueRequest")), headersToIgnore) ); } @Test public void shouldNotReturnResponseForNonMatchingQueryStringParameterValue() { // when mockServerClient .when( request() .withMethod("POST") .withPath(calculatePath("some_pathRequest")) .withQueryStringParameters( param("queryStringParameterOneName", "queryStringParameterOneValueOne", "queryStringParameterOneValueTwo"), param("queryStringParameterTwoName", "queryStringParameterTwoValue") ) .withBody("some_bodyRequest") ) .respond( response() .withStatusCode(ACCEPTED_202.code()) .withReasonPhrase(ACCEPTED_202.reasonPhrase()) .withBody("some_body_response") .withHeaders(header("headerNameResponse", "headerValueResponse")) .withCookies(cookie("cookieNameResponse", "cookieValueResponse")) ); // then // wrong query string parameter value assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()) .withReasonPhrase(HttpStatusCode.NOT_FOUND_404.reasonPhrase()), makeRequest( request() .withMethod("POST") .withPath(calculatePath("some_pathRequest")) .withQueryStringParameters( param("queryStringParameterOneName", "OTHERqueryStringParameterOneValueOne", "queryStringParameterOneValueTwo"), param("queryStringParameterTwoName", "queryStringParameterTwoValue") ) .withBody("some_bodyRequest") .withHeaders(header("headerNameRequest", "headerValueRequest")) .withCookies(cookie("cookieNameRequest", "cookieValueRequest")), headersToIgnore) ); } @Test public void shouldNotReturnResponseForMatchingQueryStringParameterWithNotOperator() { // when mockServerClient .when( request() .withMethod("POST") .withPath(calculatePath("some_pathRequest")) .withQueryStringParameters( param(not("queryStringParameterOneName"), not("Parameter One Value One"), not("Parameter One Value Two")), param("queryStringParameterTwoName", "Parameter Two") ) ) .respond( response() .withStatusCode(ACCEPTED_202.code()) .withReasonPhrase(ACCEPTED_202.reasonPhrase()) .withBody("some_body_response") ); // then // wrong query string parameter name assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()) .withReasonPhrase(HttpStatusCode.NOT_FOUND_404.reasonPhrase()), makeRequest( request() .withMethod("POST") .withPath(calculatePath("some_pathRequest")) .withQueryStringParameters( param("queryStringParameterOneName", "Parameter One Value One", "Parameter One Value Two"), param("queryStringParameterTwoName", "Parameter Two") ), headersToIgnore) ); // wrong query string parameter name assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()) .withReasonPhrase(HttpStatusCode.NOT_FOUND_404.reasonPhrase()), makeRequest( request() .withMethod("POST") .withPath(calculatePath("some_pathRequest")) .withQueryStringParameters( param("queryStringParameterOneName", "Parameter One Value One", "Parameter One Value Two"), param("queryStringParameterTwoName", "Parameter Two") ), headersToIgnore) ); } @Test public void shouldNotReturnResponseForNonMatchingCookieName() { // when mockServerClient .when( request() .withMethod("GET") .withPath(calculatePath("some_path")) .withQueryStringParameters( param("queryStringParameterOneName", "queryStringParameterOneValue"), param("queryStringParameterTwoName", "queryStringParameterTwoValue") ) .withBody(exact("some_body")) .withHeaders(header("headerName", "headerValue")) .withCookies(cookie("cookieName", "cookieValue")) ) .respond( response() .withStatusCode(ACCEPTED_202.code()) .withReasonPhrase(ACCEPTED_202.reasonPhrase()) .withBody("some_body") .withHeaders(header("headerName", "headerValue")) .withCookies(cookie("cookieName", "cookieValue")) ); // then // - in http assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()) .withReasonPhrase(HttpStatusCode.NOT_FOUND_404.reasonPhrase()), makeRequest( request() .withMethod("GET") .withPath(calculatePath("some_path")) .withQueryStringParameters( param("queryStringParameterOneName", "queryStringParameterOneValue"), param("queryStringParameterTwoName", "queryStringParameterTwoValue") ) .withBody(exact("some_body")) .withHeaders(header("headerName", "headerValue")) .withCookies(cookie("cookieOtherName", "cookieValue")), headersToIgnore) ); // - in https assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()) .withReasonPhrase(HttpStatusCode.NOT_FOUND_404.reasonPhrase()), makeRequest( request() .withMethod("GET") .withSecure(true) .withPath(calculatePath("some_path")) .withQueryStringParameters( param("queryStringParameterOneName", "queryStringParameterOneValue"), param("queryStringParameterTwoName", "queryStringParameterTwoValue") ) .withBody(exact("some_body")) .withHeaders(header("headerName", "headerValue")) .withCookies(cookie("cookieOtherName", "cookieValue")), headersToIgnore) ); } @Test public void shouldNotReturnResponseForNonMatchingCookieValue() { // when mockServerClient .when( request() .withMethod("GET") .withPath(calculatePath("some_path")) .withQueryStringParameters( param("queryStringParameterOneName", "queryStringParameterOneValue"), param("queryStringParameterTwoName", "queryStringParameterTwoValue") ) .withBody(exact("some_body")) .withHeaders(header("headerName", "headerValue")) .withCookies(cookie("cookieName", "cookieValue")) ) .respond( response() .withStatusCode(ACCEPTED_202.code()) .withReasonPhrase(ACCEPTED_202.reasonPhrase()) .withBody("some_body") .withHeaders(header("headerName", "headerValue")) .withCookies(cookie("cookieName", "cookieValue")) ); // then // - in http assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()) .withReasonPhrase(HttpStatusCode.NOT_FOUND_404.reasonPhrase()), makeRequest( request() .withMethod("GET") .withPath(calculatePath("some_path")) .withQueryStringParameters( param("queryStringParameterOneName", "queryStringParameterOneValue"), param("queryStringParameterTwoName", "queryStringParameterTwoValue") ) .withBody(exact("some_body")) .withHeaders(header("headerName", "headerValue")) .withCookies(cookie("cookieName", "cookieOtherValue")), headersToIgnore) ); // - in https assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()) .withReasonPhrase(HttpStatusCode.NOT_FOUND_404.reasonPhrase()), makeRequest( request() .withMethod("GET") .withSecure(true) .withPath(calculatePath("some_path")) .withQueryStringParameters( param("queryStringParameterOneName", "queryStringParameterOneValue"), param("queryStringParameterTwoName", "queryStringParameterTwoValue") ) .withBody(exact("some_body")) .withHeaders(header("headerName", "headerValue")) .withCookies(cookie("cookieName", "cookieOtherValue")), headersToIgnore) ); } @Test public void shouldNotReturnResponseForMatchingCookieWithNotOperator() { // when mockServerClient .when( request() .withMethod("GET") .withPath(calculatePath("some_pathRequest")) .withCookies( cookie(not("requestCookieNameOne"), not("requestCookieValueOne")), cookie("requestCookieNameTwo", "requestCookieValueTwo") ) ) .respond( response() .withStatusCode(ACCEPTED_202.code()) .withReasonPhrase(ACCEPTED_202.reasonPhrase()) .withBody("some_body_response") ); // then // wrong query string parameter name assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()) .withReasonPhrase(HttpStatusCode.NOT_FOUND_404.reasonPhrase()), makeRequest( request() .withMethod("GET") .withPath(calculatePath("some_pathRequest")) .withCookies( cookie("requestCookieNameOne", "requestCookieValueOne"), cookie("requestCookieNameTwo", "requestCookieValueTwo") ), headersToIgnore) ); // wrong query string parameter name assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()) .withReasonPhrase(HttpStatusCode.NOT_FOUND_404.reasonPhrase()), makeRequest( request() .withMethod("GET") .withPath(calculatePath("some_pathRequest")) .withCookies( cookie("requestCookieNameOne", "requestCookieValueOne"), cookie("requestCookieNameTwo", "requestCookieValueTwo") ), headersToIgnore) ); } @Test public void shouldNotReturnResponseForNonMatchingHeaderName() { // when mockServerClient .when( request() .withMethod("GET") .withPath(calculatePath("some_path")) .withQueryStringParameters( param("queryStringParameterOneName", "queryStringParameterOneValue"), param("queryStringParameterTwoName", "queryStringParameterTwoValue") ) .withBody(exact("some_body")) .withHeaders(header("headerName", "headerValue")) .withCookies(cookie("cookieName", "cookieValue")) ) .respond( response() .withStatusCode(ACCEPTED_202.code()) .withReasonPhrase(ACCEPTED_202.reasonPhrase()) .withBody("some_body") .withHeaders(header("headerName", "headerValue")) .withCookies(cookie("cookieName", "cookieValue")) ); // then // - in http assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()) .withReasonPhrase(HttpStatusCode.NOT_FOUND_404.reasonPhrase()), makeRequest( request() .withMethod("GET") .withPath(calculatePath("some_path")) .withQueryStringParameters( param("queryStringParameterOneName", "queryStringParameterOneValue"), param("queryStringParameterTwoName", "queryStringParameterTwoValue") ) .withBody(exact("some_body")) .withHeaders(header("headerOtherName", "headerValue")) .withCookies(cookie("cookieName", "cookieValue")), headersToIgnore) ); // - in https assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()) .withReasonPhrase(HttpStatusCode.NOT_FOUND_404.reasonPhrase()), makeRequest( request() .withMethod("GET") .withSecure(true) .withPath(calculatePath("some_path")) .withQueryStringParameters( param("queryStringParameterOneName", "queryStringParameterOneValue"), param("queryStringParameterTwoName", "queryStringParameterTwoValue") ) .withBody(exact("some_body")) .withHeaders(header("headerOtherName", "headerValue")) .withCookies(cookie("cookieName", "cookieValue")), headersToIgnore) ); } @Test public void shouldNotReturnResponseForNonMatchingHeaderValue() { // when mockServerClient .when( request() .withMethod("GET") .withPath(calculatePath("some_path")) .withQueryStringParameters( param("queryStringParameterOneName", "queryStringParameterOneValue"), param("queryStringParameterTwoName", "queryStringParameterTwoValue") ) .withBody(exact("some_body")) .withHeaders(header("headerName", "headerValue")) .withCookies(cookie("cookieName", "cookieValue")) ) .respond( response() .withStatusCode(ACCEPTED_202.code()) .withReasonPhrase(ACCEPTED_202.reasonPhrase()) .withBody("some_body") .withHeaders(header("headerName", "headerValue")) .withCookies(cookie("cookieName", "cookieValue")) ); // then // - in http assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()) .withReasonPhrase(HttpStatusCode.NOT_FOUND_404.reasonPhrase()), makeRequest( request() .withMethod("GET") .withPath(calculatePath("some_path")) .withQueryStringParameters( param("queryStringParameterOneName", "queryStringParameterOneValue"), param("queryStringParameterTwoName", "queryStringParameterTwoValue") ) .withBody(exact("some_body")) .withHeaders(header("headerName", "headerOtherValue")) .withCookies(cookie("cookieName", "cookieValue")), headersToIgnore) ); // - in https assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()) .withReasonPhrase(HttpStatusCode.NOT_FOUND_404.reasonPhrase()), makeRequest( request() .withMethod("GET") .withSecure(true) .withPath(calculatePath("some_path")) .withQueryStringParameters( param("queryStringParameterOneName", "queryStringParameterOneValue"), param("queryStringParameterTwoName", "queryStringParameterTwoValue") ) .withBody(exact("some_body")) .withHeaders(header("headerName", "headerOtherValue")) .withCookies(cookie("cookieName", "cookieValue")), headersToIgnore) ); } @Test public void shouldNotReturnResponseForMatchingHeaderWithNotOperator() { // when mockServerClient .when( request() .withMethod("GET") .withPath(calculatePath("some_pathRequest")) .withHeaders( header(not("requestHeaderNameOne"), not("requestHeaderValueOne")), header("requestHeaderNameTwo", "requestHeaderValueTwo") ) ) .respond( response() .withStatusCode(ACCEPTED_202.code()) .withReasonPhrase(ACCEPTED_202.reasonPhrase()) .withBody("some_body_response") ); // then // wrong query string parameter name assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()) .withReasonPhrase(HttpStatusCode.NOT_FOUND_404.reasonPhrase()), makeRequest( request() .withMethod("GET") .withPath(calculatePath("some_pathRequest")) .withHeaders( header("requestHeaderNameOne", "requestHeaderValueOne"), header("requestHeaderNameTwo", "requestHeaderValueTwo") ), headersToIgnore) ); // wrong query string parameter name assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()) .withReasonPhrase(HttpStatusCode.NOT_FOUND_404.reasonPhrase()), makeRequest( request() .withMethod("GET") .withPath(calculatePath("some_pathRequest")) .withHeaders( header("requestHeaderNameOne", "requestHeaderValueOne"), header("requestHeaderNameTwo", "requestHeaderValueTwo") ), headersToIgnore) ); } @Test public void shouldVerifyReceivedRequestInSsl() { // when mockServerClient .when( request() .withPath(calculatePath("some.*path")), exactly(2) ) .respond( response() .withBody("some_body") ); // then // - in http assertEquals( response() .withStatusCode(OK_200.code()) .withReasonPhrase(OK_200.reasonPhrase()) .withBody("some_body"), makeRequest( request() .withPath(calculatePath("some_path")), headersToIgnore) ); mockServerClient.verify(request() .withPath(calculatePath("some_path")) .withSecure(false)); mockServerClient.verify(request() .withPath(calculatePath("some_path")) .withSecure(false), VerificationTimes.exactly(1)); // - in https assertEquals( response() .withStatusCode(OK_200.code()) .withReasonPhrase(OK_200.reasonPhrase()) .withBody("some_body"), makeRequest( request() .withPath(calculatePath("some_secure_path")) .withSecure(true), headersToIgnore) ); mockServerClient.verify(request() .withPath(calculatePath("some_secure_path")) .withSecure(true)); mockServerClient.verify(request() .withPath(calculatePath("some_secure_path")) .withSecure(true), VerificationTimes.exactly(1)); } @Test public void shouldVerifyReceivedRequestsWithRegexBody() { // when mockServerClient .when( request() .withMethod("POST") .withPath(calculatePath("some_path")) .withBody("{type: 'some_random_type', value: 'some_random_value'}"), exactly(2) ) .respond( response() .withBody("some_response") ); // then // - in http assertEquals( response() .withStatusCode(OK_200.code()) .withReasonPhrase(OK_200.reasonPhrase()) .withBody("some_response"), makeRequest( request() .withMethod("POST") .withPath(calculatePath("some_path")) .withBody("{type: 'some_random_type', value: 'some_random_value'}"), headersToIgnore) ); mockServerClient.verify( request() .withBody(regex("\\{type\\: \\'some_random_type\\'\\, value\\: \\'some_random_value\\'\\}")) ); mockServerClient.verify( request() .withBody(regex("\\{type\\: \\'some_random_type\\'\\, value\\: \\'some_random_value\\'\\}")), VerificationTimes.exactly(1) ); // - in https assertEquals( response() .withStatusCode(OK_200.code()) .withReasonPhrase(OK_200.reasonPhrase()) .withBody("some_response"), makeRequest( request() .withSecure(true) .withMethod("POST") .withPath(calculatePath("some_path")) .withBody("{type: 'some_random_type', value: 'some_random_value'}"), headersToIgnore) ); mockServerClient.verify( request() .withSecure(true) .withBody(regex("\\{type\\: \\'some_random_type\\'\\, value\\: \\'some_random_value\\'\\}")) ); mockServerClient.verify( request() .withSecure(true) .withBody(regex("\\{type\\: \\'some_random_type\\'\\, value\\: \\'some_random_value\\'\\}")), VerificationTimes.atLeast(1) ); } @Test public void shouldVerifyReceivedRequestsWithNoBody() { // when mockServerClient.when(request().withPath(calculatePath("some_path")), exactly(2)).respond(response()); // then // - in http assertEquals( response() .withStatusCode(OK_200.code()) .withReasonPhrase(OK_200.reasonPhrase()), makeRequest( request() .withPath(calculatePath("some_path")), headersToIgnore) ); mockServerClient.verify(request() .withPath(calculatePath("some_path"))); mockServerClient.verify(request() .withPath(calculatePath("some_path")), VerificationTimes.exactly(1)); } @Test public void shouldVerifyReceivedRequestsWithNoMatchingExpectation() { // when makeRequest( request() .withPath(calculatePath("some_path")), headersToIgnore); mockServerClient.verify(request() .withPath(calculatePath("some_path"))); mockServerClient.verify(request() .withPath(calculatePath("some_path")), VerificationTimes.exactly(1)); mockServerClient.verify(request() .withPath(calculatePath("some_path")), VerificationTimes.once()); } @Test public void shouldVerifyTooManyRequestsReceived() { // when mockServerClient.when(request().withPath(calculatePath("some_path")), exactly(2)).respond(response().withBody("some_body")); // then assertEquals( response() .withStatusCode(OK_200.code()) .withReasonPhrase(OK_200.reasonPhrase()) .withBody("some_body"), makeRequest( request() .withPath(calculatePath("some_path")), headersToIgnore) ); try { mockServerClient.verify(request() .withPath(calculatePath("some_path")), VerificationTimes.exactly(0)); fail(); } catch (AssertionError ae) { assertThat(ae.getMessage(), startsWith("Request not found exactly 0 times, expected:<{" + NEW_LINE + " \"path\" : \"" + calculatePath("some_path") + "\"" + NEW_LINE + "}> but was:<{" + NEW_LINE + " \"method\" : \"GET\"," + NEW_LINE + " \"path\" : \"" + calculatePath("some_path") + "\"," + NEW_LINE)); } } @Test public void shouldVerifyNoMatchingRequestsReceived() { // when mockServerClient.when(request().withPath(calculatePath("some_path")), exactly(2)).respond(response().withBody("some_body")); // then assertEquals( response() .withStatusCode(OK_200.code()) .withReasonPhrase(OK_200.reasonPhrase()) .withBody("some_body"), makeRequest( request() .withPath(calculatePath("some_path")), headersToIgnore) ); try { mockServerClient.verify(request() .withPath(calculatePath("some_other_path")), VerificationTimes.exactly(2)); fail(); } catch (AssertionError ae) { assertThat(ae.getMessage(), startsWith("Request not found exactly 2 times, expected:<{" + NEW_LINE + " \"path\" : \"" + calculatePath("some_other_path") + "\"" + NEW_LINE + "}> but was:<{" + NEW_LINE + " \"method\" : \"GET\"," + NEW_LINE + " \"path\" : \"" + calculatePath("some_path") + "\"," + NEW_LINE)); } } @Test public void shouldNotVerifyNoRequestsReceived() { // when mockServerClient.when(request().withPath(calculatePath("some_path")), exactly(2)).respond(response().withBody("some_body")); // then assertEquals( response() .withStatusCode(OK_200.code()) .withReasonPhrase(OK_200.reasonPhrase()) .withBody("some_body"), makeRequest( request() .withPath(calculatePath("some_path")), headersToIgnore) ); try { mockServerClient.verifyZeroInteractions(); fail(); } catch (AssertionError ae) { assertThat(ae.getMessage(), startsWith("Request not found exactly 0 times, expected:<{ }> but was:<{" + NEW_LINE + " \"method\" : \"GET\"," + NEW_LINE + " \"path\" : \"" + calculatePath("some_path") + "\"," + NEW_LINE)); } } @Test public void shouldVerifyNoMatchingRequestsReceivedInSsl() { // when mockServerClient.when(request().withPath(calculatePath("some.*path")), exactly(2)).respond(response().withBody("some_body")); // then // - in http assertEquals( response() .withStatusCode(OK_200.code()) .withReasonPhrase(OK_200.reasonPhrase()) .withBody("some_body"), makeRequest( request() .withPath(calculatePath("some_path")), headersToIgnore) ); try { mockServerClient.verify( request() .withPath(calculatePath("some_path")) .withSecure(true), VerificationTimes.atLeast(1) ); fail(); } catch (AssertionError ae) { assertThat(ae.getMessage(), startsWith("Request not found at least once, expected:<{" + NEW_LINE + " \"path\" : \"" + calculatePath("some_path") + "\"," + NEW_LINE + " \"secure\" : true" + NEW_LINE + "}> but was:<{" + NEW_LINE + " \"method\" : \"GET\"," + NEW_LINE + " \"path\" : \"" + calculatePath("some_path") + "\"," + NEW_LINE)); } // - in https assertEquals( response() .withStatusCode(OK_200.code()) .withReasonPhrase(OK_200.reasonPhrase()) .withBody("some_body"), makeRequest( request() .withPath(calculatePath("some_secure_path")) .withSecure(true), headersToIgnore) ); try { mockServerClient.verify( request() .withPath(calculatePath("some_secure_path")) .withSecure(false), VerificationTimes.atLeast(1) ); fail(); } catch (AssertionError ae) { assertThat(ae.getMessage(), startsWith("Request not found at least once, expected:<{" + NEW_LINE + " \"path\" : \"" + calculatePath("some_secure_path") + "\"," + NEW_LINE + " \"secure\" : false" + NEW_LINE + "}> but was:<[ {" + NEW_LINE + " \"method\" : \"GET\"," + NEW_LINE + " \"path\" : \"" + calculatePath("some_path") + "\"," + NEW_LINE)); } } @Test public void shouldVerifySequenceOfRequestsReceivedIncludingThoseNotMatchingAnException() { // when mockServerClient.when(request().withPath(calculatePath("some_path.*")), exactly(4)).respond(response().withBody("some_body")); // then assertEquals( response("some_body"), makeRequest( request().withPath(calculatePath("some_path_one")), headersToIgnore) ); assertEquals( notFoundResponse(), makeRequest( request().withPath(calculatePath("not_found")), headersToIgnore) ); assertEquals( response("some_body"), makeRequest( request().withPath(calculatePath("some_path_three")), headersToIgnore) ); mockServerClient.verify(request(calculatePath("some_path_one")), request(calculatePath("some_path_three"))); mockServerClient.verify(request(calculatePath("some_path_one")), request(calculatePath("not_found"))); mockServerClient.verify(request(calculatePath("some_path_one")), request(calculatePath("not_found")), request(calculatePath("some_path_three"))); mockServerClient.verify(request(calculatePath("some_path_one")), request(calculatePath("not_found")), request(calculatePath("some_path_three"))); } @Test public void shouldVerifySequenceOfRequestsNotReceived() { // when mockServerClient.when(request().withPath(calculatePath("some_path.*")), exactly(6)).respond(response().withBody("some_body")); // then assertEquals( response("some_body"), makeRequest( request().withPath(calculatePath("some_path_one")), headersToIgnore) ); assertEquals( response("some_body"), makeRequest( request().withPath(calculatePath("some_path_two")), headersToIgnore) ); assertEquals( response("some_body"), makeRequest( request().withPath(calculatePath("some_path_three")), headersToIgnore) ); try { mockServerClient.verify(request(calculatePath("some_path_two")), request(calculatePath("some_path_one"))); fail(); } catch (AssertionError ae) { assertThat(ae.getMessage(), startsWith("Request sequence not found, expected:<[ {" + NEW_LINE + " \"path\" : \"" + calculatePath("some_path_two") + "\"" + NEW_LINE + "}, {" + NEW_LINE + " \"path\" : \"" + calculatePath("some_path_one") + "\"" + NEW_LINE + "} ]> but was:<[ {" + NEW_LINE + " \"method\" : \"GET\"," + NEW_LINE + " \"path\" : \"" + calculatePath("some_path_one") + "\"," + NEW_LINE)); } try { mockServerClient.verify(request(calculatePath("some_path_three")), request(calculatePath("some_path_two"))); fail(); } catch (AssertionError ae) { assertThat(ae.getMessage(), startsWith("Request sequence not found, expected:<[ {" + NEW_LINE + " \"path\" : \"" + calculatePath("some_path_three") + "\"" + NEW_LINE + "}, {" + NEW_LINE + " \"path\" : \"" + calculatePath("some_path_two") + "\"" + NEW_LINE + "} ]> but was:<[ {" + NEW_LINE + " \"method\" : \"GET\"," + NEW_LINE + " \"path\" : \"" + calculatePath("some_path_one") + "\"," + NEW_LINE)); } try { mockServerClient.verify(request(calculatePath("some_path_four"))); fail(); } catch (AssertionError ae) { assertThat(ae.getMessage(), startsWith("Request sequence not found, expected:<[ {" + NEW_LINE + " \"path\" : \"" + calculatePath("some_path_four") + "\"" + NEW_LINE + "} ]> but was:<[ {" + NEW_LINE + " \"method\" : \"GET\"," + NEW_LINE + " \"path\" : \"" + calculatePath("some_path_one") + "\"," + NEW_LINE)); } } @Test public void shouldRetrieveRecordedRequestsAsJson() { // when mockServerClient.when(request().withPath(calculatePath("some_path.*")), exactly(4)).respond(response().withBody("some_body")); assertEquals( response("some_body"), makeRequest( request().withPath(calculatePath("some_path_one")), headersToIgnore) ); assertEquals( notFoundResponse(), makeRequest( request().withPath(calculatePath("not_found")), headersToIgnore) ); assertEquals( response("some_body"), makeRequest( request().withPath(calculatePath("some_path_three")), headersToIgnore) ); // then verifyRequestsMatches( new HttpRequestSerializer(new MockServerLogger()).deserializeArray(mockServerClient.retrieveRecordedRequests(request().withPath(calculatePath("some_path.*")), Format.JSON)), request(calculatePath("some_path_one")), request(calculatePath("some_path_three")) ); verifyRequestsMatches( new HttpRequestSerializer(new MockServerLogger()).deserializeArray(mockServerClient.retrieveRecordedRequests(request(), Format.JSON)), request(calculatePath("some_path_one")), request(calculatePath("not_found")), request(calculatePath("some_path_three")) ); verifyRequestsMatches( new HttpRequestSerializer(new MockServerLogger()).deserializeArray(mockServerClient.retrieveRecordedRequests(null, Format.JSON)), request(calculatePath("some_path_one")), request(calculatePath("not_found")), request(calculatePath("some_path_three")) ); } @Test public void shouldRetrieveRecordedRequestsAsLogEntries() { // given mockServerClient.when(request().withPath(calculatePath("some_path.*")), exactly(4)).respond(response().withBody("some_body")); assertEquals( response("some_body"), makeRequest( request().withPath(calculatePath("some_path_one")), headersToIgnore) ); assertEquals( notFoundResponse(), makeRequest( request().withPath(calculatePath("not_found")), headersToIgnore) ); assertEquals( response("some_body"), makeRequest( request().withPath(calculatePath("some_path_three")), headersToIgnore) ); // when String logEntriesActual = mockServerClient.retrieveRecordedRequests(request().withPath(calculatePath("some_path.*")), Format.LOG_ENTRIES); HttpRequest requestOne = request("/some_path_one") .withMethod("GET") .withHeader("host", "localhost:" + this.getServerPort()) .withHeader("accept-encoding", "gzip,deflate") .withHeader("content-length", "0") .withHeader("connection", "keep-alive") .withKeepAlive(true) .withSecure(false); HttpRequest requestTwo = request("/some_path_three") .withMethod("GET") .withHeader("host", "localhost:" + this.getServerPort()) .withHeader("accept-encoding", "gzip,deflate") .withHeader("content-length", "0") .withHeader("connection", "keep-alive") .withKeepAlive(true) .withSecure(false); List<LogEntry> logEntriesExpected = Arrays.asList( new LogEntry() .setType(RECEIVED_REQUEST) .setLogLevel(Level.INFO) .setHttpRequest(requestOne) .setMessageFormat("received request:{}") .setArguments(requestOne), new LogEntry() .setType(RECEIVED_REQUEST) .setLogLevel(Level.INFO) .setHttpRequest(requestTwo) .setMessageFormat("received request:{}") .setArguments(requestTwo) ); // then assertThat(logEntriesActual, is(new LogEntrySerializer(new MockServerLogger()).serialize(logEntriesExpected))); } @Test public void shouldRetrieveActiveExpectationsAsJson() { // when mockServerClient.when(request().withPath(calculatePath("some_path.*")), exactly(4)) .respond(response().withBody("some_body")); mockServerClient.when(request().withPath(calculatePath("some_path.*"))) .respond(response().withBody("some_body")); mockServerClient.when(request().withPath(calculatePath("some_other_path"))) .respond(response().withBody("some_other_body")); mockServerClient.when(request().withPath(calculatePath("some_forward_path"))) .forward(forward()); // then assertThat( mockServerClient.retrieveActiveExpectations(request().withPath(calculatePath("some_path.*")), Format.JSON), is(new ExpectationSerializer(new MockServerLogger()).serialize(Arrays.asList( new Expectation(request().withPath(calculatePath("some_path.*")), exactly(4), TimeToLive.unlimited()) .thenRespond(response().withBody("some_body")), new Expectation(request().withPath(calculatePath("some_path.*"))) .thenRespond(response().withBody("some_body")) ))) ); assertThat( mockServerClient.retrieveActiveExpectations(null, Format.JSON), is(new ExpectationSerializer(new MockServerLogger()).serialize(Arrays.asList( new Expectation(request().withPath(calculatePath("some_path.*")), exactly(4), TimeToLive.unlimited()) .thenRespond(response().withBody("some_body")), new Expectation(request().withPath(calculatePath("some_path.*"))) .thenRespond(response().withBody("some_body")), new Expectation(request().withPath(calculatePath("some_other_path"))) .thenRespond(response().withBody("some_other_body")), new Expectation(request().withPath(calculatePath("some_forward_path"))) .thenForward(forward()) ))) ); assertThat( mockServerClient.retrieveActiveExpectations(request(), Format.JSON), is(new ExpectationSerializer(new MockServerLogger()).serialize(Arrays.asList( new Expectation(request().withPath(calculatePath("some_path.*")), exactly(4), TimeToLive.unlimited()) .thenRespond(response().withBody("some_body")), new Expectation(request().withPath(calculatePath("some_path.*"))) .thenRespond(response().withBody("some_body")), new Expectation(request().withPath(calculatePath("some_other_path"))) .thenRespond(response().withBody("some_other_body")), new Expectation(request().withPath(calculatePath("some_forward_path"))) .thenForward(forward()) ))) ); } @Test public void shouldRetrieveActiveExpectationsAsJava() { // when mockServerClient.when(request().withPath(calculatePath("some_path.*")), exactly(4)) .respond(response().withBody("some_body")); mockServerClient.when(request().withPath(calculatePath("some_path.*"))) .respond(response().withBody("some_body")); mockServerClient.when(request().withPath(calculatePath("some_other_path"))) .respond(response().withBody("some_other_body")); mockServerClient.when(request().withPath(calculatePath("some_forward_path"))) .forward(forward()); // then assertThat( mockServerClient.retrieveActiveExpectations(request().withPath(calculatePath("some_path.*")), Format.JAVA), is(new ExpectationToJavaSerializer().serialize(Arrays.asList( new Expectation(request().withPath(calculatePath("some_path.*")), exactly(4), TimeToLive.unlimited()) .thenRespond(response().withBody("some_body")), new Expectation(request().withPath(calculatePath("some_path.*"))) .thenRespond(response().withBody("some_body")) ))) ); assertThat( mockServerClient.retrieveActiveExpectations(null, Format.JAVA), is(new ExpectationToJavaSerializer().serialize(Arrays.asList( new Expectation(request().withPath(calculatePath("some_path.*")), exactly(4), TimeToLive.unlimited()) .thenRespond(response().withBody("some_body")), new Expectation(request().withPath(calculatePath("some_path.*"))) .thenRespond(response().withBody("some_body")), new Expectation(request().withPath(calculatePath("some_other_path"))) .thenRespond(response().withBody("some_other_body")), new Expectation(request().withPath(calculatePath("some_forward_path"))) .thenForward(forward()) ))) ); assertThat( mockServerClient.retrieveActiveExpectations(request(), Format.JAVA), is(new ExpectationToJavaSerializer().serialize(Arrays.asList( new Expectation(request().withPath(calculatePath("some_path.*")), exactly(4), TimeToLive.unlimited()) .thenRespond(response().withBody("some_body")), new Expectation(request().withPath(calculatePath("some_path.*"))) .thenRespond(response().withBody("some_body")), new Expectation(request().withPath(calculatePath("some_other_path"))) .thenRespond(response().withBody("some_other_body")), new Expectation(request().withPath(calculatePath("some_forward_path"))) .thenForward(forward()) ))) ); } @Test public void shouldRetrieveRecordedExpectationsAsJson() { // when mockServerClient.when(request().withPath(calculatePath("some_path.*")), exactly(4)).forward( forward() .withHost("127.0.0.1") .withPort(insecureEchoServer.getPort()) ); assertEquals( response("some_body_one"), makeRequest( request().withPath(calculatePath("some_path_one")).withBody("some_body_one"), headersToIgnore ) ); assertEquals( response("some_body_three"), makeRequest( request().withPath(calculatePath("some_path_three")).withBody("some_body_three"), headersToIgnore ) ); // then Expectation[] recordedExpectations = new ExpectationSerializer(new MockServerLogger()).deserializeArray( mockServerClient.retrieveRecordedExpectations(request().withPath(calculatePath("some_path_one")), Format.JSON) ); assertThat(recordedExpectations.length, is(1)); verifyRequestsMatches( new HttpRequest[]{ recordedExpectations[0].getHttpRequest() }, request(calculatePath("some_path_one")).withBody("some_body_one") ); assertThat(recordedExpectations[0].getHttpResponse().getBodyAsString(), is("some_body_one")); // and recordedExpectations = new ExpectationSerializer(new MockServerLogger()).deserializeArray( mockServerClient.retrieveRecordedExpectations(request(), Format.JSON) ); assertThat(recordedExpectations.length, is(2)); verifyRequestsMatches( new HttpRequest[]{ recordedExpectations[0].getHttpRequest(), recordedExpectations[1].getHttpRequest() }, request(calculatePath("some_path_one")).withBody("some_body_one"), request(calculatePath("some_path_three")).withBody("some_body_three") ); assertThat(recordedExpectations[0].getHttpResponse().getBodyAsString(), is("some_body_one")); assertThat(recordedExpectations[1].getHttpResponse().getBodyAsString(), is("some_body_three")); // and recordedExpectations = new ExpectationSerializer(new MockServerLogger()).deserializeArray( mockServerClient.retrieveRecordedExpectations(null, Format.JSON) ); assertThat(recordedExpectations.length, is(2)); verifyRequestsMatches( new HttpRequest[]{ recordedExpectations[0].getHttpRequest(), recordedExpectations[1].getHttpRequest() }, request(calculatePath("some_path_one")).withBody("some_body_one"), request(calculatePath("some_path_three")).withBody("some_body_three") ); assertThat(recordedExpectations[0].getHttpResponse().getBodyAsString(), is("some_body_one")); assertThat(recordedExpectations[1].getHttpResponse().getBodyAsString(), is("some_body_three")); } @Test public void shouldClearExpectationsOnly() { // given - some expectations mockServerClient .when( request() .withPath(calculatePath("some_path1")) ) .respond( response() .withBody("some_body1") ); mockServerClient .when( request() .withPath(calculatePath("some_path2")) ) .respond( response() .withBody("some_body2") ); // and - some matching requests assertEquals( response() .withStatusCode(OK_200.code()) .withReasonPhrase(OK_200.reasonPhrase()) .withBody("some_body1"), makeRequest( request() .withPath(calculatePath("some_path1")), headersToIgnore) ); assertEquals( response() .withStatusCode(OK_200.code()) .withReasonPhrase(OK_200.reasonPhrase()) .withBody("some_body2"), makeRequest( request() .withPath(calculatePath("some_path2")), headersToIgnore) ); // when mockServerClient .clear( request() .withPath(calculatePath("some_path1")), ClearType.EXPECTATIONS ); // then - expectations cleared assertThat( mockServerClient.retrieveActiveExpectations(null), arrayContaining( new Expectation(request() .withPath(calculatePath("some_path2"))) .thenRespond( response() .withBody("some_body2") ) ) ); // and then - request log not cleared verifyRequestsMatches( mockServerClient.retrieveRecordedRequests(null), request(calculatePath("some_path1")), request(calculatePath("some_path2")) ); } @Test public void shouldClearLogsOnly() { // given - some expectations mockServerClient .when( request() .withPath(calculatePath("some_path1")) ) .respond( response() .withBody("some_body1") ); mockServerClient .when( request() .withPath(calculatePath("some_path2")) ) .respond( response() .withBody("some_body2") ); // and - some matching requests assertEquals( response() .withStatusCode(OK_200.code()) .withReasonPhrase(OK_200.reasonPhrase()) .withBody("some_body1"), makeRequest( request() .withPath(calculatePath("some_path1")), headersToIgnore) ); assertEquals( response() .withStatusCode(OK_200.code()) .withReasonPhrase(OK_200.reasonPhrase()) .withBody("some_body2"), makeRequest( request() .withPath(calculatePath("some_path2")), headersToIgnore) ); // when mockServerClient .clear( request() .withPath(calculatePath("some_path1")), ClearType.LOG ); // then - expectations cleared assertThat( mockServerClient.retrieveActiveExpectations(null), arrayContaining( new Expectation(request() .withPath(calculatePath("some_path1"))) .thenRespond( response() .withBody("some_body1") ), new Expectation(request() .withPath(calculatePath("some_path2"))) .thenRespond( response() .withBody("some_body2") ) ) ); // and then - request log cleared verifyRequestsMatches( mockServerClient.retrieveRecordedRequests(null), request(calculatePath("some_path2")) ); } @Test public void shouldClearAllExpectationsWithNull() { // given mockServerClient .when( request() .withPath(calculatePath("some_path1")) ) .respond( response() .withBody("some_body1") ); mockServerClient .when( request() .withPath(calculatePath("some_path2")) ) .respond( response() .withBody("some_body2") ); assertEquals( response() .withStatusCode(OK_200.code()) .withReasonPhrase(OK_200.reasonPhrase()) .withBody("some_body2"), makeRequest( request() .withPath(calculatePath("some_path2")), headersToIgnore) ); // when mockServerClient.clear(null); // then assertThat(mockServerClient.retrieveActiveExpectations(null), emptyArray()); assertThat(mockServerClient.retrieveRecordedRequests(null), emptyArray()); } @Test public void shouldClearAllExpectationsWithEmptyRequest() { // given mockServerClient .when( request() .withPath(calculatePath("some_path1")) ) .respond( response() .withBody("some_body1") ); mockServerClient .when( request() .withPath(calculatePath("some_path2")) ) .respond( response() .withBody("some_body2") ); assertEquals( response() .withStatusCode(OK_200.code()) .withReasonPhrase(OK_200.reasonPhrase()) .withBody("some_body2"), makeRequest( request() .withPath(calculatePath("some_path2")), headersToIgnore) ); // when mockServerClient.clear(request()); // then assertThat(mockServerClient.retrieveActiveExpectations(null), emptyArray()); assertThat(mockServerClient.retrieveRecordedRequests(null), emptyArray()); } @Test public void shouldClearExpectationsWithXPathBody() { // given mockServerClient .when( request() .withBody(xpath("/bookstore/book[year=2005]/price")) ) .respond( response() .withBody("some_body1") ); mockServerClient .when( request() .withBody(xpath("/bookstore/book[year=2006]/price")) ) .respond( response() .withBody("some_body2") ); // and StringBody xmlBody = new StringBody("" + "<?xml version=\"1.0\" encoding=\"ISO-8859-1\"?>" + NEW_LINE + "<bookstore>" + NEW_LINE + " <book category=\"COOKING\">" + NEW_LINE + " <title lang=\"en\">Everyday Italian</title>" + NEW_LINE + " <author>Giada De Laurentiis</author>" + NEW_LINE + " <year>2005</year>" + NEW_LINE + " <price>30.00</price>" + NEW_LINE + " </book>" + NEW_LINE + " <book category=\"CHILDREN\">" + NEW_LINE + " <title lang=\"en\">Harry Potter</title>" + NEW_LINE + " <author>J K. Rowling</author>" + NEW_LINE + " <year>2006</year>" + NEW_LINE + " <price>29.99</price>" + NEW_LINE + " </book>" + NEW_LINE + " <book category=\"WEB\">" + NEW_LINE + " <title lang=\"en\">Learning XML</title>" + NEW_LINE + " <author>Erik T. Ray</author>" + NEW_LINE + " <year>2003</year>" + NEW_LINE + " <price>31.95</price>" + NEW_LINE + " </book>" + NEW_LINE + "</bookstore>"); // then assertEquals( response() .withStatusCode(OK_200.code()) .withReasonPhrase(OK_200.reasonPhrase()) .withBody("some_body1"), makeRequest( request() .withBody(xmlBody), headersToIgnore) ); // when mockServerClient .clear( request() .withBody(xpath("/bookstore/book[year=2005]/price")) ); // then assertThat( mockServerClient.retrieveActiveExpectations(null), arrayContaining( new Expectation(request() .withBody(xpath("/bookstore/book[year=2006]/price"))) .thenRespond( response() .withBody("some_body2") ) ) ); // - in http assertEquals( response() .withStatusCode(OK_200.code()) .withReasonPhrase(OK_200.reasonPhrase()) .withBody("some_body2"), makeRequest( request() .withBody(xmlBody), headersToIgnore) ); // - in https assertEquals( response() .withStatusCode(OK_200.code()) .withReasonPhrase(OK_200.reasonPhrase()) .withBody("some_body2"), makeRequest( request() .withSecure(true) .withBody(xmlBody), headersToIgnore) ); } @Test public void shouldClearExpectationsWithJsonSchemaBody() { // given JsonSchemaBody jsonSchemaBodyOne = jsonSchema("{" + NEW_LINE + " \"$schema\": \"http://json-schema.org/draft-04/schema#\"," + NEW_LINE + " \"title\": \"Product\"," + NEW_LINE + " \"description\": \"A product from Acme's catalog\"," + NEW_LINE + " \"type\": \"object\"," + NEW_LINE + " \"properties\": {" + NEW_LINE + " \"id\": {" + NEW_LINE + " \"description\": \"The unique identifier for a product\"," + NEW_LINE + " \"type\": \"integer\"" + NEW_LINE + " }," + NEW_LINE + " \"name\": {" + NEW_LINE + " \"description\": \"Name of the product\"," + NEW_LINE + " \"type\": \"string\"" + NEW_LINE + " }," + NEW_LINE + " \"price\": {" + NEW_LINE + " \"type\": \"number\"," + NEW_LINE + " \"minimum\": 0," + NEW_LINE + " \"exclusiveMinimum\": true" + NEW_LINE + " }," + NEW_LINE + " \"tags\": {" + NEW_LINE + " \"type\": \"array\"," + NEW_LINE + " \"items\": {" + NEW_LINE + " \"type\": \"string\"" + NEW_LINE + " }," + NEW_LINE + " \"minItems\": 1," + NEW_LINE + " \"uniqueItems\": true" + NEW_LINE + " }" + NEW_LINE + " }," + NEW_LINE + " \"required\": [\"id\", \"name\", \"price\"]" + NEW_LINE + "}"); JsonSchemaBody jsonSchemaBodyTwo = jsonSchema("{" + NEW_LINE + " \"$schema\": \"http://json-schema.org/draft-04/schema#\"," + NEW_LINE + " \"title\": \"Product\"," + NEW_LINE + " \"description\": \"A product from Acme's catalog\"," + NEW_LINE + " \"type\": \"object\"," + NEW_LINE + " \"properties\": {" + NEW_LINE + " \"id\": {" + NEW_LINE + " \"description\": \"The unique identifier for a product\"," + NEW_LINE + " \"type\": \"integer\"" + NEW_LINE + " }," + NEW_LINE + " \"name\": {" + NEW_LINE + " \"description\": \"Name of the product\"," + NEW_LINE + " \"type\": \"string\"" + NEW_LINE + " }," + NEW_LINE + " \"price\": {" + NEW_LINE + " \"type\": \"number\"," + NEW_LINE + " \"minimum\": 10," + NEW_LINE + " \"exclusiveMinimum\": true" + NEW_LINE + " }," + NEW_LINE + " \"tags\": {" + NEW_LINE + " \"type\": \"array\"," + NEW_LINE + " \"items\": {" + NEW_LINE + " \"type\": \"string\"" + NEW_LINE + " }," + NEW_LINE + " \"minItems\": 1," + NEW_LINE + " \"uniqueItems\": true" + NEW_LINE + " }" + NEW_LINE + " }," + NEW_LINE + " \"required\": [\"id\", \"name\", \"price\"]" + NEW_LINE + "}"); mockServerClient .when( request() .withBody(jsonSchemaBodyOne) ) .respond( response() .withBody("some_body1") ); mockServerClient .when( request() .withBody(jsonSchemaBodyTwo) ) .respond( response() .withBody("some_body2") ); // then assertEquals( response() .withStatusCode(OK_200.code()) .withReasonPhrase(OK_200.reasonPhrase()) .withBody("some_body1"), makeRequest( request() .withBody("{" + NEW_LINE + " \"id\": 1," + NEW_LINE + " \"name\": \"A green door\"," + NEW_LINE + " \"price\": 12.50," + NEW_LINE + " \"tags\": [\"home\", \"green\"]" + NEW_LINE + "}"), headersToIgnore) ); // when mockServerClient .clear( request() .withBody(jsonSchemaBodyOne) ); // then assertThat( mockServerClient.retrieveActiveExpectations(null), arrayContaining( new Expectation(request() .withBody(jsonSchemaBodyTwo)) .thenRespond( response() .withBody("some_body2") ) ) ); // - in http assertEquals( response() .withStatusCode(OK_200.code()) .withReasonPhrase(OK_200.reasonPhrase()) .withBody("some_body2"), makeRequest( request() .withBody("{" + NEW_LINE + " \"id\": 1," + NEW_LINE + " \"name\": \"A green door\"," + NEW_LINE + " \"price\": 12.50," + NEW_LINE + " \"tags\": [\"home\", \"green\"]" + NEW_LINE + "}"), headersToIgnore) ); // - in https assertEquals( response() .withStatusCode(OK_200.code()) .withReasonPhrase(OK_200.reasonPhrase()) .withBody("some_body2"), makeRequest( request() .withSecure(true) .withBody("{" + NEW_LINE + " \"id\": 1," + NEW_LINE + " \"name\": \"A green door\"," + NEW_LINE + " \"price\": 12.50," + NEW_LINE + " \"tags\": [\"home\", \"green\"]" + NEW_LINE + "}"), headersToIgnore) ); } @Test public void shouldClearExpectationsWithParameterBody() { // given mockServerClient .when( request() .withBody(params(param("bodyParameterNameOne", "bodyParameterValueOne"))) ) .respond( response() .withBody("some_body1") ); mockServerClient .when( request() .withBody(params(param("bodyParameterNameTwo", "bodyParameterValueTwo"))) ) .respond( response() .withBody("some_body2") ); // then assertEquals( response() .withStatusCode(OK_200.code()) .withReasonPhrase(OK_200.reasonPhrase()) .withBody("some_body1"), makeRequest( request() .withBody(params(param("bodyParameterNameOne", "bodyParameterValueOne"))), headersToIgnore) ); // when mockServerClient .clear( request() .withBody(params(param("bodyParameterNameOne", "bodyParameterValueOne"))) ); // then assertThat( mockServerClient.retrieveActiveExpectations(null), arrayContaining( new Expectation(request() .withBody(params(param("bodyParameterNameTwo", "bodyParameterValueTwo")))) .thenRespond( response() .withBody("some_body2") ) ) ); // - in http assertEquals( response() .withStatusCode(OK_200.code()) .withReasonPhrase(OK_200.reasonPhrase()) .withBody("some_body2"), makeRequest( request() .withBody(params(param("bodyParameterNameTwo", "bodyParameterValueTwo"))), headersToIgnore) ); // - in https assertEquals( response() .withStatusCode(NOT_FOUND_404.code()) .withReasonPhrase(NOT_FOUND_404.reasonPhrase()), makeRequest( request() .withBody(params(param("bodyParameterNameOne", "bodyParameterValueOne"))), headersToIgnore) ); } @Test public void shouldEnsureThatInterruptedRequestsAreVerifiable() { mockServerClient .when( request(calculatePath("delayed")) ) .respond( response("delayed data") .withDelay(new Delay(TimeUnit.SECONDS, 3)) ); Future<HttpResponse> delayedFuture = Executors.newSingleThreadExecutor().submit(() -> httpClient.sendRequest( request(addContextToPath(calculatePath("delayed"))) .withHeader(HOST.toString(), "localhost:" + getServerPort()) ).get(10, TimeUnit.SECONDS)); Uninterruptibles.sleepUninterruptibly(1, TimeUnit.SECONDS); // Let request reach server delayedFuture.cancel(true); // Then interrupt requesting thread mockServerClient.verify(request(calculatePath("delayed"))); // We should be able to verify request that reached server even though its later interrupted } @Test public void shouldEnsureThatRequestDelaysDoNotAffectOtherRequests() throws Exception { mockServerClient .when( request("/slow") ) .respond( response("super slow") .withDelay(new Delay(TimeUnit.SECONDS, 5)) ); mockServerClient .when( request("/fast") ) .respond( response("quite fast") ); ExecutorService executorService = Executors.newFixedThreadPool(2); Future<Long> slowFuture = executorService.submit(() -> { long start = System.currentTimeMillis(); makeRequest(request("/slow"), Collections.emptySet()); return System.currentTimeMillis() - start; }); // Let fast request come to the server slightly after slow request Uninterruptibles.sleepUninterruptibly(1, TimeUnit.SECONDS); Future<Long> fastFuture = executorService.submit(() -> { long start = System.currentTimeMillis(); makeRequest(request("/fast"), Collections.emptySet()); return System.currentTimeMillis() - start; }); Long slowRequestElapsedMillis = slowFuture.get(); Long fastRequestElapsedMillis = fastFuture.get(); assertThat("Slow request takes less than expected", slowRequestElapsedMillis, is(greaterThan(4 * 1000L))); assertThat("Fast request takes longer than expected", fastRequestElapsedMillis, is(lessThan(1000L))); } }
rtkmhart/mockserver
mockserver-integration-testing/src/main/java/org/mockserver/integration/server/AbstractExtendedMockingIntegrationTest.java
939
package logic; import java.io.Serializable; /** * * Η κλάση αυτή περιέχει όλες τις πληροφορίες και τις μεθόδους που έχουν σχέση * με την έννοια του παίχτη. * * @author thanasis * @author tasosxak * @since 10/11/16 * @version 1.0 */ public class Player implements Serializable { private final String name; private final transient String keys; private Integer score; private int wins; public Player(String name, String keys) { this.name = name; this.keys = keys; score = null; wins = 0; } /** * * @param points Οι πόντοι που θα προστεθούν στο συνολικό σκορ */ public void addPoints(int points) { if (score == null) { score = 0; } score += points; } public void setScore(int score) { this.score = score; } public Integer getScore() { return score; } public void addWin() { wins++; } public int getWins() { return wins; } public String getName() { return name; } /** * * @param key Συμβολοσειρά με έναν χαρακτήρα που δηλώνει το πλήκτρο το οποίο * θέλουμε να δούμε αν είναι αυτού του παίχτη. * @return Επιστρέφει true αν το key είναι πλήκτρο αυτού του πάιχτη. Αν το * key δεν είναι ένας χαρακτήρας ή δεν είναι πλήκτρο αυτού του παίχτη * επιστρέφει false. */ public boolean isMyKey(String key) { return key.length() == 1 && keys.contains(key); } /** * * @param key Συμβολοσειρά με έναν χαρακτήρα ο οποίος είναι το πλήκτρο του * οποίου η θέση ζητείται. * @return Επιστρέφει το id του key για αυτόν τον παίκτη (πχ αν ο παίκτης * έχει τα πλήκτρα "asdf" τότε το id του 'a' είναι το 0, το id του 's' είναι * το 1 κτλ) αν ο παίκτης έχει τέτοιο πλήκτρο, αλλιώς επιστρέφει -1. */ public int getKeyId(String key) { if (keys.contains(key)) { return keys.indexOf(key); } else { return -1; } } public String getAllKeys() { return this.keys; } @Override public boolean equals(Object obj) { if (this == obj) { return true; } if (!(obj instanceof Player)) { return false; } Player player = (Player) obj; return this.name.equals(player.getName()); } @Override public int hashCode() { int hash = 3; hash = 89 * hash + this.name.hashCode(); return hash; } /** * * @return Επιστρέφει το όνομα και το σκορ του παίχτη στη μορφή "Όνομα: * Σκορ". */ @Override public String toString() { return this.name + ": " + this.score + ", " + this.wins; } }
TeamLS/Buzz
src/logic/Player.java
940
package testbed.review; import java.io.*; import java.nio.file.Path; import java.nio.file.Paths; import java.time.LocalDateTime; import java.util.Arrays; import java.util.Comparator; import java.util.Scanner; /** * Αναπτύξτε μία εφαρμογή που διαβάζει έναν-έναν τους χαρακτήρες ενός αρχείου * και τους εισάγει σε ένα πίνακα 256x2. Κάθε θέση του πίνακα είναι επομένως * ένας πίνακας δύο θέσεων, όπου στη 1η θέση αποθηκεύεται ο χαρακτήρας που έχει * διαβαστεί (αν δεν υπάρχει ήδη στον πίνακα) και στη 2η θέση αποθηκεύεται το πλήθος * των φορών που έχει διαβαστεί (βρεθεί) κάθε χαρακτήρας. Χαρακτήρες θεωρούνται και τα * κενά και οι αλλαγές γραμμής και γενικά οποιοσδήποτε UTF-8 χαρακτήρας. * Στο τέλος η main() παρουσιάζει στατιστικά στοιχεία για κάθε χαρακτήρα όπως η συχνότητα * εμφάνισής του στο κείμενο ταξινομημένα ανά χαρακτήρα και ανά συχνότητα εμφάνισης. */ public class CharReadAndStatisticsApp { final static Path path = Paths.get("C:/tmp/logTextStatistics.txt"); final static int[][] text = new int[256][2]; static int pivot = -1; static int count = 0; final static Scanner in = new Scanner(System.in); public static void main(String[] args) { try { readTextAndSaveService(); printStatisticsService(); } catch (IOException e) { System.out.println("Error in I/O"); } } /** * Reads text from a file using a FileInputStream with 4096 bytes buffering. * Then, each char is saved in the 2D array. * * @throws IOException * if file name is invalid. * @throws IllegalArgumentException * if 2D array is full or any storage error. */ public static void readTextAndSaveService() throws IOException, IllegalArgumentException { int ch; byte[] buf = new byte[4096]; int n = 0; try (FileInputStream fs = new FileInputStream("C:/tmp/inputText.txt");) { while ((n = fs.read(buf)) > 0) { for (int i = 0; i < n; i++) { if (!saveChar(buf[i])) throw new IllegalArgumentException("Error in save"); else { count++; } } } } catch (IOException | IllegalArgumentException e ) { log(e); throw e; } } /** * For each char in the input text, ot prints the count and * the percentage, sorted by char asc and percentage asc. */ public static void printStatisticsService() { int[][] copiedText = Arrays.copyOfRange(text, 0, pivot + 1); Arrays.sort(copiedText, Comparator.comparing(a -> a[0])); System.out.println("Statistics (Char Ascending)"); for (int[] ints : copiedText) { System.out.printf("%c\t%d\t%.4f%%\n", ints[0], ints[1], ints[1] / (double) count); } Arrays.sort(copiedText, Comparator.comparing(a -> a[1])); System.out.println("Statistics (Percentage Ascending)"); for (int[] ints : copiedText) { System.out.printf("%c\t%d\t%.4f%%\n", ints[0], ints[1], ints[1] / (double) count); } } /** * Inserts a char in a 2D array together with its * occurrences' count in the text. * * @param ch the char * @return true, if the char inserted in 2D array, * false, otherwise. */ public static boolean saveChar(int ch) { int charPosition = -1; boolean inserted = false; if (isFull(text)) { return false; } charPosition = getCharPosition(ch); if (charPosition == -1) { pivot++; text[pivot][0] = ch; text[pivot][1] += 1; inserted = true; } else { text[charPosition][1]++; inserted = true; } return inserted; } public static int getCharPosition(int ch) { for (int i = 0; i <= pivot; i++) { if (text[i][0] == ch) { return i; } } return -1; } public static boolean isFull(int[][] text) { return pivot == text.length - 1; } public static void log(Exception e) { try (PrintStream ps = new PrintStream(new FileOutputStream(path.toFile(), true))) { ps.println(LocalDateTime.now() + "\n" + e); } catch (IOException ex) { ex.printStackTrace(); } } }
a8anassis/cf-structured-review
CharReadAndStatisticsApp.java
941
package org.mockserver.integration.server; import com.google.common.base.Charsets; import com.google.common.net.MediaType; import com.google.common.util.concurrent.Uninterruptibles; import org.apache.commons.io.IOUtils; import org.junit.Test; import org.mockserver.client.serialization.ExpectationSerializer; import org.mockserver.client.serialization.HttpRequestSerializer; import org.mockserver.client.serialization.java.ExpectationToJavaSerializer; import org.mockserver.echo.http.EchoServer; import org.mockserver.logging.MockServerLogger; import org.mockserver.matchers.MatchType; import org.mockserver.matchers.TimeToLive; import org.mockserver.mock.Expectation; import org.mockserver.model.*; import org.mockserver.verify.VerificationTimes; import java.io.IOException; import java.util.Arrays; import java.util.Collections; import java.util.concurrent.*; import static io.netty.handler.codec.http.HttpHeaderNames.*; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.*; import static org.hamcrest.core.Is.is; import static org.hamcrest.core.StringStartsWith.startsWith; import static org.hamcrest.number.OrderingComparison.greaterThan; import static org.junit.Assert.assertEquals; import static org.junit.Assert.fail; import static org.mockserver.character.Character.NEW_LINE; import static org.mockserver.matchers.Times.exactly; import static org.mockserver.model.BinaryBody.binary; import static org.mockserver.model.Cookie.cookie; import static org.mockserver.model.Header.header; import static org.mockserver.model.HttpForward.forward; import static org.mockserver.model.HttpRequest.request; import static org.mockserver.model.HttpResponse.notFoundResponse; import static org.mockserver.model.HttpResponse.response; import static org.mockserver.model.HttpStatusCode.NOT_FOUND_404; import static org.mockserver.model.HttpStatusCode.OK_200; import static org.mockserver.model.JsonBody.json; import static org.mockserver.model.JsonSchemaBody.jsonSchema; import static org.mockserver.model.NottableString.not; import static org.mockserver.model.NottableString.string; import static org.mockserver.model.Parameter.param; import static org.mockserver.model.ParameterBody.params; import static org.mockserver.model.RegexBody.regex; import static org.mockserver.model.StringBody.exact; import static org.mockserver.model.StringBody.subString; import static org.mockserver.model.XPathBody.xpath; import static org.mockserver.model.XmlBody.xml; import static org.mockserver.model.XmlSchemaBody.xmlSchema; import static org.mockserver.model.XmlSchemaBody.xmlSchemaFromResource; /** * @author jamesdbloom */ public abstract class AbstractExtendedClientServerIntegrationTest extends AbstractBasicClientServerIntegrationTest { @Test public void shouldReturnResponseForRequestInSsl() { // when mockServerClient.when(request().withSecure(true)).respond(response().withBody("some_body")); // then // - in http assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()) .withReasonPhrase(HttpStatusCode.NOT_FOUND_404.reasonPhrase()), makeRequest( request() .withPath(calculatePath("")), headersToIgnore) ); // - in https assertEquals( response() .withStatusCode(OK_200.code()) .withReasonPhrase(OK_200.reasonPhrase()) .withBody("some_body"), makeRequest( request() .withSecure(true) .withPath(calculatePath("")), headersToIgnore) ); } @Test public void shouldReturnResponseForRequestNotInSsl() { // when mockServerClient.when(request().withSecure(false)).respond(response().withBody("some_body")); // then // - in http assertEquals( response() .withStatusCode(OK_200.code()) .withReasonPhrase(OK_200.reasonPhrase()) .withBody("some_body"), makeRequest( request() .withPath(calculatePath("")), headersToIgnore) ); // - in https assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()) .withReasonPhrase(HttpStatusCode.NOT_FOUND_404.reasonPhrase()), makeRequest( request() .withSecure(true) .withPath(calculatePath("")), headersToIgnore) ); } @Test public void shouldReturnResponseByMatchingPath() { // when mockServerClient .when( request() .withPath(calculatePath("some_path1")) ) .respond( response() .withBody("some_body1") ); mockServerClient .when( request() .withPath(calculatePath("some_path2")) ) .respond( response() .withBody("some_body2") ); // then // - in http assertEquals( response() .withStatusCode(OK_200.code()) .withReasonPhrase(OK_200.reasonPhrase()) .withBody("some_body2"), makeRequest( request() .withPath(calculatePath("some_path2")), headersToIgnore) ); assertEquals( response() .withStatusCode(OK_200.code()) .withReasonPhrase(OK_200.reasonPhrase()) .withBody("some_body1"), makeRequest( request() .withPath(calculatePath("some_path1")), headersToIgnore) ); // - in https assertEquals( response() .withStatusCode(OK_200.code()) .withReasonPhrase(OK_200.reasonPhrase()) .withBody("some_body2"), makeRequest( request() .withSecure(true) .withPath(calculatePath("some_path2")), headersToIgnore) ); assertEquals( response() .withStatusCode(OK_200.code()) .withReasonPhrase(OK_200.reasonPhrase()) .withBody("some_body1"), makeRequest( request() .withSecure(true) .withPath(calculatePath("some_path1")), headersToIgnore) ); } @Test public void shouldReturnResponseByMatchingPathExactTimes() { // when mockServerClient .when( request() .withPath(calculatePath("some_path")), exactly(2) ) .respond( response() .withBody("some_body") ); // then // - in http assertEquals( response() .withStatusCode(OK_200.code()) .withReasonPhrase(OK_200.reasonPhrase()) .withBody("some_body"), makeRequest( request() .withPath(calculatePath("some_path")), headersToIgnore) ); // - in https assertEquals( response() .withStatusCode(OK_200.code()) .withReasonPhrase(OK_200.reasonPhrase()) .withBody("some_body"), makeRequest( request() .withSecure(true) .withPath(calculatePath("some_path")), headersToIgnore) ); // - in http assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()) .withReasonPhrase(HttpStatusCode.NOT_FOUND_404.reasonPhrase()), makeRequest( request() .withPath(calculatePath("some_path")), headersToIgnore) ); // - in https assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()) .withReasonPhrase(HttpStatusCode.NOT_FOUND_404.reasonPhrase()), makeRequest( request() .withSecure(true) .withPath(calculatePath("some_path")), headersToIgnore) ); } @Test public void shouldReturnResponseWhenTimeToLiveHasNotExpired() { // when mockServerClient .when( request().withPath(calculatePath("some_path")), exactly(2), TimeToLive.exactly(TimeUnit.HOURS, 1L) ) .respond( response().withBody("some_body") ); // then // - in http assertEquals( response() .withStatusCode(OK_200.code()) .withReasonPhrase(OK_200.reasonPhrase()) .withBody("some_body"), makeRequest( request() .withPath(calculatePath("some_path")), headersToIgnore) ); // - in https assertEquals( response() .withStatusCode(OK_200.code()) .withReasonPhrase(OK_200.reasonPhrase()) .withBody("some_body"), makeRequest( request() .withSecure(true) .withPath(calculatePath("some_path")), headersToIgnore) ); // - in http assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()) .withReasonPhrase(HttpStatusCode.NOT_FOUND_404.reasonPhrase()), makeRequest( request() .withPath(calculatePath("some_path")), headersToIgnore) ); // - in https assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()) .withReasonPhrase(HttpStatusCode.NOT_FOUND_404.reasonPhrase()), makeRequest( request() .withSecure(true) .withPath(calculatePath("some_path")), headersToIgnore) ); } @Test public void shouldReturnMatchRequestWithBodyInUTF16() { // when String body = "我说中国话"; mockServerClient.when(request().withBody(body, Charsets.UTF_16)).respond(response().withBody(body, Charsets.UTF_8)); // then // - in http assertEquals( response() .withHeader(CONTENT_TYPE.toString(), MediaType.create("text", "plain").withCharset(Charsets.UTF_8).toString()) .withStatusCode(OK_200.code()) .withReasonPhrase(OK_200.reasonPhrase()) .withBody(body), makeRequest( request() .withPath(calculatePath("")) .withBody(body, Charsets.UTF_16), headersToIgnore) ); // - in https assertEquals( response() .withHeader(CONTENT_TYPE.toString(), MediaType.create("text", "plain").withCharset(Charsets.UTF_8).toString()) .withStatusCode(OK_200.code()) .withReasonPhrase(OK_200.reasonPhrase()) .withBody(body), makeRequest( request() .withSecure(true) .withPath(calculatePath("")) .withBody(body, Charsets.UTF_16), headersToIgnore) ); } @Test public void shouldReturnMatchRequestWithBodyInUTF8WithContentTypeHeader() { // when String body = "我说中国话"; mockServerClient .when( request() .withHeader(CONTENT_TYPE.toString(), MediaType.create("text", "plain").withCharset(Charsets.UTF_8).toString()) .withBody(body) ) .respond( response() .withBody(body, Charsets.UTF_8) ); // then // - in http assertEquals( response() .withHeader(CONTENT_TYPE.toString(), MediaType.create("text", "plain").withCharset(Charsets.UTF_8).toString()) .withStatusCode(OK_200.code()) .withReasonPhrase(OK_200.reasonPhrase()) .withBody(body), makeRequest( request() .withHeader(CONTENT_TYPE.toString(), MediaType.create("text", "plain").withCharset(Charsets.UTF_8).toString()) .withPath(calculatePath("")) .withBody(body), headersToIgnore) ); // - in https assertEquals( response() .withHeader(CONTENT_TYPE.toString(), MediaType.create("text", "plain").withCharset(Charsets.UTF_8).toString()) .withStatusCode(OK_200.code()) .withReasonPhrase(OK_200.reasonPhrase()) .withBody(body), makeRequest( request() .withHeader(CONTENT_TYPE.toString(), MediaType.create("text", "plain").withCharset(Charsets.UTF_8).toString()) .withSecure(true) .withPath(calculatePath("")) .withBody(body), headersToIgnore) ); } @Test public void shouldReturnResponseWithBodyInUTF16() { // when String body = "我说中国话"; mockServerClient.when(request()).respond(response().withBody(body, Charsets.UTF_16)); // then // - in http assertEquals( response() .withHeader(CONTENT_TYPE.toString(), MediaType.create("text", "plain").withCharset(Charsets.UTF_16).toString()) .withStatusCode(OK_200.code()) .withReasonPhrase(OK_200.reasonPhrase()) .withBody(body), makeRequest( request() .withPath(calculatePath("")), headersToIgnore) ); // - in https assertEquals( response() .withHeader(CONTENT_TYPE.toString(), MediaType.create("text", "plain").withCharset(Charsets.UTF_16).toString()) .withStatusCode(OK_200.code()) .withReasonPhrase(OK_200.reasonPhrase()) .withBody(body), makeRequest( request() .withSecure(true) .withPath(calculatePath("")), headersToIgnore) ); } @Test public void shouldReturnResponseWithBodyInUTF8WithContentTypeHeader() { // when String body = "我说中国话"; mockServerClient .when( request() ) .respond( response() .withHeader(CONTENT_TYPE.toString(), MediaType.create("text", "plain").withCharset(Charsets.UTF_8).toString()) .withBody(body) ); // then // - in http assertEquals( response() .withHeader(CONTENT_TYPE.toString(), MediaType.create("text", "plain").withCharset(Charsets.UTF_8).toString()) .withStatusCode(OK_200.code()) .withReasonPhrase(OK_200.reasonPhrase()) .withBody(body), makeRequest( request() .withPath(calculatePath("")), headersToIgnore) ); // - in https assertEquals( response() .withHeader(CONTENT_TYPE.toString(), MediaType.create("text", "plain").withCharset(Charsets.UTF_8).toString()) .withStatusCode(OK_200.code()) .withReasonPhrase(OK_200.reasonPhrase()) .withBody(body), makeRequest( request() .withSecure(true) .withPath(calculatePath("")), headersToIgnore) ); } @Test public void shouldReturnResponseByMatchingSubStringBody() { // when mockServerClient .when( request() .withBody( subString("random") ), exactly(2) ) .respond( response() .withBody("some_sub_string_body_response") ); // then // - in http assertEquals( response() .withStatusCode(OK_200.code()) .withReasonPhrase(OK_200.reasonPhrase()) .withBody("some_sub_string_body_response"), makeRequest( request() .withMethod("POST") .withPath(calculatePath("some_path")) .withBody("some_random_body"), headersToIgnore) ); // - in https assertEquals( response() .withStatusCode(OK_200.code()) .withReasonPhrase(OK_200.reasonPhrase()) .withBody("some_sub_string_body_response"), makeRequest( request() .withSecure(true) .withMethod("POST") .withPath(calculatePath("some_path")) .withBody("some_random_body"), headersToIgnore) ); } @Test public void shouldReturnResponseByMatchingBodyWithXPath() { // when mockServerClient.when(request().withBody(xpath("/bookstore/book[price>30]/price")), exactly(2)).respond(response().withBody("some_body")); // then // - in http assertEquals( response() .withStatusCode(OK_200.code()) .withReasonPhrase(OK_200.reasonPhrase()) .withBody("some_body"), makeRequest( request() .withPath(calculatePath("some_path")) .withMethod("POST") .withBody(new StringBody("" + "<?xml version=\"1.0\" encoding=\"ISO-8859-1\"?>" + NEW_LINE + "<bookstore>" + NEW_LINE + " <book category=\"COOKING\">" + NEW_LINE + " <title lang=\"en\">Everyday Italian</title>" + NEW_LINE + " <author>Giada De Laurentiis</author>" + NEW_LINE + " <year>2005</year>" + NEW_LINE + " <price>30.00</price>" + NEW_LINE + " </book>" + NEW_LINE + " <book category=\"CHILDREN\">" + NEW_LINE + " <title lang=\"en\">Harry Potter</title>" + NEW_LINE + " <author>J K. Rowling</author>" + NEW_LINE + " <year>2005</year>" + NEW_LINE + " <price>29.99</price>" + NEW_LINE + " </book>" + NEW_LINE + " <book category=\"WEB\">" + NEW_LINE + " <title lang=\"en\">Learning XML</title>" + NEW_LINE + " <author>Erik T. Ray</author>" + NEW_LINE + " <year>2003</year>" + NEW_LINE + " <price>31.95</price>" + NEW_LINE + " </book>" + NEW_LINE + "</bookstore>")), headersToIgnore) ); // - in https assertEquals( response() .withStatusCode(OK_200.code()) .withReasonPhrase(OK_200.reasonPhrase()) .withBody("some_body"), makeRequest( request() .withSecure(true) .withPath(calculatePath("some_path")) .withMethod("POST") .withBody(new StringBody("" + "<?xml version=\"1.0\" encoding=\"ISO-8859-1\"?>" + NEW_LINE + "<bookstore>" + NEW_LINE + " <book category=\"COOKING\">" + NEW_LINE + " <title lang=\"en\">Everyday Italian</title>" + NEW_LINE + " <author>Giada De Laurentiis</author>" + NEW_LINE + " <year>2005</year>" + NEW_LINE + " <price>30.00</price>" + NEW_LINE + " </book>" + NEW_LINE + " <book category=\"CHILDREN\">" + NEW_LINE + " <title lang=\"en\">Harry Potter</title>" + NEW_LINE + " <author>J K. Rowling</author>" + NEW_LINE + " <year>2005</year>" + NEW_LINE + " <price>29.99</price>" + NEW_LINE + " </book>" + NEW_LINE + " <book category=\"WEB\">" + NEW_LINE + " <title lang=\"en\">Learning XML</title>" + NEW_LINE + " <author>Erik T. Ray</author>" + NEW_LINE + " <year>2003</year>" + NEW_LINE + " <price>31.95</price>" + NEW_LINE + " </book>" + NEW_LINE + "</bookstore>")), headersToIgnore) ); } @Test public void shouldReturnResponseByMatchingBodyWithXml() { // when mockServerClient.when(request().withBody(xml("" + "<bookstore>" + NEW_LINE + " <book nationality=\"ITALIAN\" category=\"COOKING\"><title lang=\"en\">Everyday Italian</title><author>Giada De Laurentiis</author><year>2005</year><price>30.00</price></book>" + NEW_LINE + "</bookstore>")), exactly(2)).respond(response().withBody("some_body")); // then // - in http assertEquals( response() .withStatusCode(OK_200.code()) .withReasonPhrase(OK_200.reasonPhrase()) .withBody("some_body"), makeRequest( request() .withPath(calculatePath("some_path")) .withMethod("POST") .withBody(new StringBody("" + "<?xml version=\"1.0\" encoding=\"ISO-8859-1\"?>" + NEW_LINE + "<bookstore>" + NEW_LINE + " <book category=\"COOKING\" nationality=\"ITALIAN\">" + NEW_LINE + " <title lang=\"en\">Everyday Italian</title>" + NEW_LINE + " <author>Giada De Laurentiis</author>" + NEW_LINE + " <year>2005</year>" + NEW_LINE + " <price>30.00</price>" + NEW_LINE + " </book>" + NEW_LINE + "</bookstore>")), headersToIgnore) ); // - in https assertEquals( response() .withStatusCode(OK_200.code()) .withReasonPhrase(OK_200.reasonPhrase()) .withBody("some_body"), makeRequest( request() .withSecure(true) .withPath(calculatePath("some_path")) .withMethod("POST") .withBody(new StringBody("" + "<?xml version=\"1.0\" encoding=\"ISO-8859-1\"?>" + NEW_LINE + "<bookstore>" + NEW_LINE + " <book category=\"COOKING\" nationality=\"ITALIAN\">" + NEW_LINE + " <title lang=\"en\">Everyday Italian</title>" + NEW_LINE + " <author>Giada De Laurentiis</author>" + NEW_LINE + " <year>2005</year>" + NEW_LINE + " <price>30.00</price>" + NEW_LINE + " </book>" + NEW_LINE + "</bookstore>")), headersToIgnore) ); } @Test public void shouldReturnResponseByMatchingBodyWithJson() { // when mockServerClient .when( request() .withBody(json("{" + NEW_LINE + " \"id\": 1," + NEW_LINE + " \"name\": \"A green door\"," + NEW_LINE + " \"price\": 12.50," + NEW_LINE + " \"tags\": [\"home\", \"green\"]" + NEW_LINE + "}")), exactly(2) ) .respond( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withReasonPhrase(HttpStatusCode.ACCEPTED_202.reasonPhrase()) .withBody("some_body") ); // then // - in http assertEquals( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withReasonPhrase(HttpStatusCode.ACCEPTED_202.reasonPhrase()) .withBody("some_body"), makeRequest( request() .withPath(calculatePath("some_path")) .withMethod("POST") .withBody("{" + NEW_LINE + " \"id\": 1," + NEW_LINE + " \"extra ignored field\": \"some value\"," + NEW_LINE + " \"name\": \"A green door\"," + NEW_LINE + " \"price\": 12.50," + NEW_LINE + " \"tags\": [\"home\", \"green\"]" + NEW_LINE + "}"), headersToIgnore) ); // - in https assertEquals( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withReasonPhrase(HttpStatusCode.ACCEPTED_202.reasonPhrase()) .withBody("some_body"), makeRequest( request() .withSecure(true) .withPath(calculatePath("some_path")) .withMethod("POST") .withBody("{" + NEW_LINE + " \"id\": 1," + NEW_LINE + " \"extra ignored array\": [\"one\", \"two\"]," + NEW_LINE + " \"name\": \"A green door\"," + NEW_LINE + " \"price\": 12.50," + NEW_LINE + " \"tags\": [\"home\", \"green\"]" + NEW_LINE + "}"), headersToIgnore) ); } @Test public void shouldReturnResponseByMatchingBodyWithJsonWithCharsetUTF8() { // when mockServerClient .when( request() .withBody(json("{" + NEW_LINE + " \"ταυτότητα\": 1," + NEW_LINE + " \"όνομα\": \"μια πράσινη πόρτα\"," + NEW_LINE + " \"τιμή\": 12.50," + NEW_LINE + " \"ετικέτες\": [\"σπίτι\", \"πράσινος\"]" + NEW_LINE + "}", Charsets.UTF_16, MatchType.ONLY_MATCHING_FIELDS)), exactly(2) ) .respond( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withReasonPhrase(HttpStatusCode.ACCEPTED_202.reasonPhrase()) .withBody("some_body") ); // then // - in http assertEquals( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withReasonPhrase(HttpStatusCode.ACCEPTED_202.reasonPhrase()) .withBody("some_body"), makeRequest( request() .withPath(calculatePath("some_path")) .withMethod("POST") .withBody(json("{" + NEW_LINE + " \"ταυτότητα\": 1," + NEW_LINE + " \"επιπλέον αγνοούνται τομέα\": \"κάποια αξία\"," + NEW_LINE + " \"όνομα\": \"μια πράσινη πόρτα\"," + NEW_LINE + " \"τιμή\": 12.50," + NEW_LINE + " \"ετικέτες\": [\"σπίτι\", \"πράσινος\"]" + NEW_LINE + "}", Charsets.UTF_16, MatchType.ONLY_MATCHING_FIELDS)), headersToIgnore) ); // - in https assertEquals( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withReasonPhrase(HttpStatusCode.ACCEPTED_202.reasonPhrase()) .withBody("some_body"), makeRequest( request() .withSecure(true) .withPath(calculatePath("some_path")) .withMethod("POST") .withBody(json("{" + NEW_LINE + " \"ταυτότητα\": 1," + NEW_LINE + " \"επιπλέον αγνοούνται σειρά\": [\"ένας\", \"δυο\"]," + NEW_LINE + " \"όνομα\": \"μια πράσινη πόρτα\"," + NEW_LINE + " \"τιμή\": 12.50," + NEW_LINE + " \"ετικέτες\": [\"σπίτι\", \"πράσινος\"]" + NEW_LINE + "}", Charsets.UTF_16, MatchType.ONLY_MATCHING_FIELDS)), headersToIgnore) ); } @Test public void shouldReturnResponseByMatchingBodyWithJsonWithContentTypeHeader() { // when mockServerClient .when( request() .withBody(json("{" + NEW_LINE + " \"ταυτότητα\": 1," + NEW_LINE + " \"όνομα\": \"μια πράσινη πόρτα\"," + NEW_LINE + " \"τιμή\": 12.50," + NEW_LINE + " \"ετικέτες\": [\"σπίτι\", \"πράσινος\"]" + NEW_LINE + "}", Charsets.UTF_16, MatchType.ONLY_MATCHING_FIELDS)), exactly(2) ) .respond( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withReasonPhrase(HttpStatusCode.ACCEPTED_202.reasonPhrase()) .withBody("some_body") ); // then // - in http assertEquals( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withReasonPhrase(HttpStatusCode.ACCEPTED_202.reasonPhrase()) .withBody("some_body"), makeRequest( request() .withHeader(CONTENT_TYPE.toString(), MediaType.create("text", "plain").withCharset(Charsets.UTF_16).toString()) .withPath(calculatePath("some_path")) .withMethod("POST") .withBody(json("{" + NEW_LINE + " \"ταυτότητα\": 1," + NEW_LINE + " \"επιπλέον αγνοούνται τομέα\": \"κάποια αξία\"," + NEW_LINE + " \"όνομα\": \"μια πράσινη πόρτα\"," + NEW_LINE + " \"τιμή\": 12.50," + NEW_LINE + " \"ετικέτες\": [\"σπίτι\", \"πράσινος\"]" + NEW_LINE + "}")), headersToIgnore) ); // - in https assertEquals( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withReasonPhrase(HttpStatusCode.ACCEPTED_202.reasonPhrase()) .withBody("some_body"), makeRequest( request() .withSecure(true) .withHeader(CONTENT_TYPE.toString(), MediaType.create("text", "plain").withCharset(Charsets.UTF_16).toString()) .withPath(calculatePath("some_path")) .withMethod("POST") .withBody(json("{" + NEW_LINE + " \"ταυτότητα\": 1," + NEW_LINE + " \"επιπλέον αγνοούνται σειρά\": [\"ένας\", \"δυο\"]," + NEW_LINE + " \"όνομα\": \"μια πράσινη πόρτα\"," + NEW_LINE + " \"τιμή\": 12.50," + NEW_LINE + " \"ετικέτες\": [\"σπίτι\", \"πράσινος\"]" + NEW_LINE + "}")), headersToIgnore) ); } @Test public void shouldReturnResponseByMatchingBodyWithJsonWithMatchType() { // when mockServerClient .when( request() .withBody(json("{" + NEW_LINE + " \"id\": 1," + NEW_LINE + " \"name\": \"A green door\"," + NEW_LINE + " \"price\": 12.50," + NEW_LINE + " \"tags\": [\"home\", \"green\"]" + NEW_LINE + "}", MatchType.ONLY_MATCHING_FIELDS)), exactly(2) ) .respond( response() .withBody("some_body") ); // then // - in http assertEquals( response("some_body"), makeRequest( request() .withPath(calculatePath("some_path")) .withMethod("POST") .withBody("{" + NEW_LINE + " \"id\": 1," + NEW_LINE + " \"extra field\": \"some value\"," + NEW_LINE + " \"name\": \"A green door\"," + NEW_LINE + " \"price\": 12.50," + NEW_LINE + " \"tags\": [\"home\", \"green\"]" + NEW_LINE + "}"), headersToIgnore) ); // - in https assertEquals( response("some_body"), makeRequest( request() .withSecure(true) .withPath(calculatePath("some_path")) .withMethod("POST") .withBody("{" + NEW_LINE + " \"id\": 1," + NEW_LINE + " \"extra field\": \"some value\"," + NEW_LINE + " \"name\": \"A green door\"," + NEW_LINE + " \"price\": 12.50," + NEW_LINE + " \"tags\": [\"home\", \"green\"]" + NEW_LINE + "}"), headersToIgnore) ); } @Test public void shouldReturnResponseByMatchingBodyWithJsonSchema() { // when mockServerClient.when(request().withBody(jsonSchema("{" + NEW_LINE + " \"$schema\": \"http://json-schema.org/draft-04/schema#\"," + NEW_LINE + " \"title\": \"Product\"," + NEW_LINE + " \"description\": \"A product from Acme's catalog\"," + NEW_LINE + " \"type\": \"object\"," + NEW_LINE + " \"properties\": {" + NEW_LINE + " \"id\": {" + NEW_LINE + " \"description\": \"The unique identifier for a product\"," + NEW_LINE + " \"type\": \"integer\"" + NEW_LINE + " }," + NEW_LINE + " \"name\": {" + NEW_LINE + " \"description\": \"Name of the product\"," + NEW_LINE + " \"type\": \"string\"" + NEW_LINE + " }," + NEW_LINE + " \"price\": {" + NEW_LINE + " \"type\": \"number\"," + NEW_LINE + " \"minimum\": 0," + NEW_LINE + " \"exclusiveMinimum\": true" + NEW_LINE + " }," + NEW_LINE + " \"tags\": {" + NEW_LINE + " \"type\": \"array\"," + NEW_LINE + " \"items\": {" + NEW_LINE + " \"type\": \"string\"" + NEW_LINE + " }," + NEW_LINE + " \"minItems\": 1," + NEW_LINE + " \"uniqueItems\": true" + NEW_LINE + " }" + NEW_LINE + " }," + NEW_LINE + " \"required\": [\"id\", \"name\", \"price\"]" + NEW_LINE + "}")), exactly(2)).respond(response().withBody("some_body")); // then // - in http assertEquals( response() .withStatusCode(OK_200.code()) .withReasonPhrase(OK_200.reasonPhrase()) .withBody("some_body"), makeRequest( request() .withPath(calculatePath("some_path")) .withMethod("POST") .withBody("{" + NEW_LINE + " \"id\": 1," + NEW_LINE + " \"name\": \"A green door\"," + NEW_LINE + " \"price\": 12.50," + NEW_LINE + " \"tags\": [\"home\", \"green\"]" + NEW_LINE + "}"), headersToIgnore) ); // - in https assertEquals( response() .withStatusCode(OK_200.code()) .withReasonPhrase(OK_200.reasonPhrase()) .withBody("some_body"), makeRequest( request() .withSecure(true) .withPath(calculatePath("some_path")) .withMethod("POST") .withBody("{" + NEW_LINE + " \"id\": 1," + NEW_LINE + " \"name\": \"A green door\"," + NEW_LINE + " \"price\": 12.50," + NEW_LINE + " \"tags\": [\"home\", \"green\"]" + NEW_LINE + "}"), headersToIgnore) ); } @Test public void shouldReturnResponseByMatchingBodyWithXmlSchema() { // when mockServerClient.when(request() .withBody( xmlSchema("<?xml version=\"1.0\" encoding=\"UTF-8\"?>" + NEW_LINE + "<xs:schema xmlns:xs=\"http://www.w3.org/2001/XMLSchema\" elementFormDefault=\"qualified\" attributeFormDefault=\"unqualified\">" + NEW_LINE + " <!-- XML Schema Generated from XML Document on Wed Jun 28 2017 21:52:45 GMT+0100 (BST) -->" + NEW_LINE + " <!-- with XmlGrid.net Free Online Service http://xmlgrid.net -->" + NEW_LINE + " <xs:element name=\"notes\">" + NEW_LINE + " <xs:complexType>" + NEW_LINE + " <xs:sequence>" + NEW_LINE + " <xs:element name=\"note\" maxOccurs=\"unbounded\">" + NEW_LINE + " <xs:complexType>" + NEW_LINE + " <xs:sequence>" + NEW_LINE + " <xs:element name=\"to\" minOccurs=\"1\" maxOccurs=\"1\" type=\"xs:string\"></xs:element>" + NEW_LINE + " <xs:element name=\"from\" minOccurs=\"1\" maxOccurs=\"1\" type=\"xs:string\"></xs:element>" + NEW_LINE + " <xs:element name=\"heading\" minOccurs=\"1\" maxOccurs=\"1\" type=\"xs:string\"></xs:element>" + NEW_LINE + " <xs:element name=\"body\" minOccurs=\"1\" maxOccurs=\"1\" type=\"xs:string\"></xs:element>" + NEW_LINE + " </xs:sequence>" + NEW_LINE + " </xs:complexType>" + NEW_LINE + " </xs:element>" + NEW_LINE + " </xs:sequence>" + NEW_LINE + " </xs:complexType>" + NEW_LINE + " </xs:element>" + NEW_LINE + "</xs:schema>")), exactly(2) ) .respond( response() .withBody("some_body") ); // then // - in http assertEquals( response() .withStatusCode(NOT_FOUND_404.code()) .withReasonPhrase(NOT_FOUND_404.reasonPhrase()), makeRequest( request() .withMethod("POST") .withBody("<?xml version=\"1.0\" encoding=\"utf-8\"?>" + NEW_LINE + "<notes>" + NEW_LINE + " <note>" + NEW_LINE + " <to>Bob</to>" + NEW_LINE + " <heading>Reminder</heading>" + NEW_LINE + " <body>Buy Bread</body>" + NEW_LINE + " </note>" + NEW_LINE + " <note>" + NEW_LINE + " <to>Jack</to>" + NEW_LINE + " <from>Jill</from>" + NEW_LINE + " <heading>Reminder</heading>" + NEW_LINE + " <body>Wash Shirts</body>" + NEW_LINE + " </note>" + NEW_LINE + "</notes>"), headersToIgnore) ); assertEquals( response() .withStatusCode(OK_200.code()) .withReasonPhrase(OK_200.reasonPhrase()) .withBody("some_body"), makeRequest( request() .withPath(calculatePath("some_path")) .withMethod("POST") .withBody("<?xml version=\"1.0\" encoding=\"utf-8\"?>" + NEW_LINE + "<notes>" + NEW_LINE + " <note>" + NEW_LINE + " <to>Bob</to>" + NEW_LINE + " <from>Bill</from>" + NEW_LINE + " <heading>Reminder</heading>" + NEW_LINE + " <body>Buy Bread</body>" + NEW_LINE + " </note>" + NEW_LINE + " <note>" + NEW_LINE + " <to>Jack</to>" + NEW_LINE + " <from>Jill</from>" + NEW_LINE + " <heading>Reminder</heading>" + NEW_LINE + " <body>Wash Shirts</body>" + NEW_LINE + " </note>" + NEW_LINE + "</notes>"), headersToIgnore) ); // - in https assertEquals( response() .withStatusCode(OK_200.code()) .withReasonPhrase(OK_200.reasonPhrase()) .withBody("some_body"), makeRequest( request() .withSecure(true) .withPath(calculatePath("some_path")) .withMethod("POST") .withBody("<?xml version=\"1.0\" encoding=\"utf-8\"?>" + NEW_LINE + "<notes>" + NEW_LINE + " <note>" + NEW_LINE + " <to>Bob</to>" + NEW_LINE + " <from>Bill</from>" + NEW_LINE + " <heading>Reminder</heading>" + NEW_LINE + " <body>Buy Bread</body>" + NEW_LINE + " </note>" + NEW_LINE + " <note>" + NEW_LINE + " <to>Jack</to>" + NEW_LINE + " <from>Jill</from>" + NEW_LINE + " <heading>Reminder</heading>" + NEW_LINE + " <body>Wash Shirts</body>" + NEW_LINE + " </note>" + NEW_LINE + "</notes>"), headersToIgnore) ); } @Test public void shouldReturnResponseByMatchingBodyWithXmlSchemaByClasspath() { // when mockServerClient.when(request() .withBody( xmlSchemaFromResource("org/mockserver/model/testXmlSchema.xsd")), exactly(2) ) .respond( response() .withBody("some_body") ); // then // - in http assertEquals( response() .withStatusCode(NOT_FOUND_404.code()) .withReasonPhrase(NOT_FOUND_404.reasonPhrase()), makeRequest( request() .withMethod("POST") .withBody("<?xml version=\"1.0\" encoding=\"utf-8\"?>" + NEW_LINE + "<notes>" + NEW_LINE + " <note>" + NEW_LINE + " <to>Bob</to>" + NEW_LINE + " <heading>Reminder</heading>" + NEW_LINE + " <body>Buy Bread</body>" + NEW_LINE + " </note>" + NEW_LINE + " <note>" + NEW_LINE + " <to>Jack</to>" + NEW_LINE + " <from>Jill</from>" + NEW_LINE + " <heading>Reminder</heading>" + NEW_LINE + " <body>Wash Shirts</body>" + NEW_LINE + " </note>" + NEW_LINE + "</notes>"), headersToIgnore) ); assertEquals( response() .withStatusCode(OK_200.code()) .withReasonPhrase(OK_200.reasonPhrase()) .withBody("some_body"), makeRequest( request() .withPath(calculatePath("some_path")) .withMethod("POST") .withBody("<?xml version=\"1.0\" encoding=\"utf-8\"?>" + NEW_LINE + "<notes>" + NEW_LINE + " <note>" + NEW_LINE + " <to>Bob</to>" + NEW_LINE + " <from>Bill</from>" + NEW_LINE + " <heading>Reminder</heading>" + NEW_LINE + " <body>Buy Bread</body>" + NEW_LINE + " </note>" + NEW_LINE + " <note>" + NEW_LINE + " <to>Jack</to>" + NEW_LINE + " <from>Jill</from>" + NEW_LINE + " <heading>Reminder</heading>" + NEW_LINE + " <body>Wash Shirts</body>" + NEW_LINE + " </note>" + NEW_LINE + "</notes>"), headersToIgnore) ); // - in https assertEquals( response() .withStatusCode(OK_200.code()) .withReasonPhrase(OK_200.reasonPhrase()) .withBody("some_body"), makeRequest( request() .withSecure(true) .withPath(calculatePath("some_path")) .withMethod("POST") .withBody("<?xml version=\"1.0\" encoding=\"utf-8\"?>" + NEW_LINE + "<notes>" + NEW_LINE + " <note>" + NEW_LINE + " <to>Bob</to>" + NEW_LINE + " <from>Bill</from>" + NEW_LINE + " <heading>Reminder</heading>" + NEW_LINE + " <body>Buy Bread</body>" + NEW_LINE + " </note>" + NEW_LINE + " <note>" + NEW_LINE + " <to>Jack</to>" + NEW_LINE + " <from>Jill</from>" + NEW_LINE + " <heading>Reminder</heading>" + NEW_LINE + " <body>Wash Shirts</body>" + NEW_LINE + " </note>" + NEW_LINE + "</notes>"), headersToIgnore) ); } @Test public void shouldReturnPDFResponseByMatchingPath() throws IOException { // when byte[] pdfBytes = IOUtils.toByteArray(getClass().getClassLoader().getResourceAsStream("test.pdf")); mockServerClient .when( request() .withPath(calculatePath("ws/rest/user/[0-9]+/document/[0-9]+\\.pdf")) ) .respond( response() .withStatusCode(OK_200.code()) .withReasonPhrase(OK_200.reasonPhrase()) .withHeaders( header(CONTENT_TYPE.toString(), MediaType.PDF.toString()), header(CONTENT_DISPOSITION.toString(), "form-data; name=\"test.pdf\"; filename=\"test.pdf\""), header(CACHE_CONTROL.toString(), "must-revalidate, post-check=0, pre-check=0") ) .withBody(binary(pdfBytes)) ); // then // - in http assertEquals( response() .withStatusCode(OK_200.code()) .withReasonPhrase(OK_200.reasonPhrase()) .withHeaders( header(CONTENT_DISPOSITION.toString(), "form-data; name=\"test.pdf\"; filename=\"test.pdf\""), header(CACHE_CONTROL.toString(), "must-revalidate, post-check=0, pre-check=0"), header(CONTENT_TYPE.toString(), MediaType.PDF.toString()) ) .withBody(binary(pdfBytes)), makeRequest( request() .withPath(calculatePath("ws/rest/user/1/document/2.pdf")) .withMethod("GET"), headersToIgnore) ); // - in https assertEquals( response() .withStatusCode(OK_200.code()) .withReasonPhrase(OK_200.reasonPhrase()) .withHeaders( header(CONTENT_DISPOSITION.toString(), "form-data; name=\"test.pdf\"; filename=\"test.pdf\""), header(CACHE_CONTROL.toString(), "must-revalidate, post-check=0, pre-check=0"), header(CONTENT_TYPE.toString(), MediaType.PDF.toString()) ) .withBody(binary(pdfBytes)), makeRequest( request() .withSecure(true) .withPath(calculatePath("ws/rest/user/1/document/2.pdf")) .withMethod("GET"), headersToIgnore) ); } @Test public void shouldReturnPNGResponseByMatchingPath() throws IOException { // when byte[] pngBytes = IOUtils.toByteArray(getClass().getClassLoader().getResourceAsStream("test.png")); mockServerClient .when( request() .withPath(calculatePath("ws/rest/user/[0-9]+/icon/[0-9]+\\.png")) ) .respond( response() .withStatusCode(OK_200.code()) .withReasonPhrase(OK_200.reasonPhrase()) .withHeaders( header(CONTENT_TYPE.toString(), MediaType.PNG.toString()), header(CONTENT_DISPOSITION.toString(), "form-data; name=\"test.png\"; filename=\"test.png\"") ) .withBody(binary(pngBytes)) ); // then // - in http assertEquals( response() .withStatusCode(OK_200.code()) .withReasonPhrase(OK_200.reasonPhrase()) .withHeaders( header(CONTENT_DISPOSITION.toString(), "form-data; name=\"test.png\"; filename=\"test.png\""), header(CONTENT_TYPE.toString(), MediaType.PNG.toString()) ) .withBody(binary(pngBytes)), makeRequest( request() .withPath(calculatePath("ws/rest/user/1/icon/1.png")) .withMethod("GET"), headersToIgnore) ); // - in https assertEquals( response() .withStatusCode(OK_200.code()) .withReasonPhrase(OK_200.reasonPhrase()) .withHeaders( header(CONTENT_DISPOSITION.toString(), "form-data; name=\"test.png\"; filename=\"test.png\""), header(CONTENT_TYPE.toString(), MediaType.PNG.toString()) ) .withBody(binary(pngBytes)), makeRequest( request() .withSecure(true) .withPath(calculatePath("ws/rest/user/1/icon/1.png")) .withMethod("GET"), headersToIgnore) ); } @Test public void shouldReturnPDFResponseByMatchingBinaryPDFBody() throws IOException { // when byte[] pdfBytes = IOUtils.toByteArray(getClass().getClassLoader().getResourceAsStream("test.pdf")); mockServerClient .when( request().withBody(binary(pdfBytes)) ) .respond( response() .withStatusCode(OK_200.code()) .withReasonPhrase(OK_200.reasonPhrase()) .withHeaders( header(CONTENT_TYPE.toString(), MediaType.PDF.toString()), header(CONTENT_DISPOSITION.toString(), "form-data; name=\"test.pdf\"; filename=\"test.pdf\""), header(CACHE_CONTROL.toString(), "must-revalidate, post-check=0, pre-check=0") ) .withBody(binary(pdfBytes)) ); // then // - in http assertEquals( response() .withStatusCode(OK_200.code()) .withReasonPhrase(OK_200.reasonPhrase()) .withHeaders( header(CONTENT_DISPOSITION.toString(), "form-data; name=\"test.pdf\"; filename=\"test.pdf\""), header(CACHE_CONTROL.toString(), "must-revalidate, post-check=0, pre-check=0"), header(CONTENT_TYPE.toString(), MediaType.PDF.toString()) ) .withBody(binary(pdfBytes)), makeRequest( request() .withPath(calculatePath("ws/rest/user/1/document/2.pdf")) .withBody(binary(pdfBytes)) .withMethod("POST"), headersToIgnore) ); // - in https assertEquals( response() .withStatusCode(OK_200.code()) .withReasonPhrase(OK_200.reasonPhrase()) .withHeaders( header(CONTENT_DISPOSITION.toString(), "form-data; name=\"test.pdf\"; filename=\"test.pdf\""), header(CACHE_CONTROL.toString(), "must-revalidate, post-check=0, pre-check=0"), header(CONTENT_TYPE.toString(), MediaType.PDF.toString()) ) .withBody(binary(pdfBytes)), makeRequest( request() .withSecure(true) .withPath(calculatePath("ws/rest/user/1/document/2.pdf")) .withBody(binary(pdfBytes)) .withMethod("POST"), headersToIgnore) ); } @Test public void shouldReturnPNGResponseByMatchingBinaryPNGBody() throws IOException { // when byte[] pngBytes = IOUtils.toByteArray(getClass().getClassLoader().getResourceAsStream("test.png")); mockServerClient .when( request().withBody(binary(pngBytes)) ) .respond( response() .withStatusCode(OK_200.code()) .withReasonPhrase(OK_200.reasonPhrase()) .withHeaders( header(CONTENT_TYPE.toString(), MediaType.PNG.toString()), header(CONTENT_DISPOSITION.toString(), "form-data; name=\"test.png\"; filename=\"test.png\"") ) .withBody(binary(pngBytes)) ); // then // - in http assertEquals( response() .withStatusCode(OK_200.code()) .withReasonPhrase(OK_200.reasonPhrase()) .withHeaders( header(CONTENT_DISPOSITION.toString(), "form-data; name=\"test.png\"; filename=\"test.png\""), header(CONTENT_TYPE.toString(), MediaType.PNG.toString()) ) .withBody(binary(pngBytes)), makeRequest( request() .withPath(calculatePath("ws/rest/user/1/icon/1.png")) .withBody(binary(pngBytes)) .withMethod("POST"), headersToIgnore) ); // - in https assertEquals( response() .withStatusCode(OK_200.code()) .withReasonPhrase(OK_200.reasonPhrase()) .withHeaders( header(CONTENT_DISPOSITION.toString(), "form-data; name=\"test.png\"; filename=\"test.png\""), header(CONTENT_TYPE.toString(), MediaType.PNG.toString()) ) .withBody(binary(pngBytes)), makeRequest( request() .withSecure(true) .withPath(calculatePath("ws/rest/user/1/icon/1.png")) .withBody(binary(pngBytes)) .withMethod("POST"), headersToIgnore) ); } @Test public void shouldReturnResponseByNotMatchingPathWithNotOperator() { // when mockServerClient .when( request() .withPath(not(calculatePath("some_path"))) ) .respond( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withReasonPhrase(HttpStatusCode.ACCEPTED_202.reasonPhrase()) .withBody("some_body_response") ); // then // - in http assertEquals( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withReasonPhrase(HttpStatusCode.ACCEPTED_202.reasonPhrase()) .withBody("some_body_response"), makeRequest( request() .withPath(calculatePath("some_other_path")), headersToIgnore) ); // - in https assertEquals( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withReasonPhrase(HttpStatusCode.ACCEPTED_202.reasonPhrase()) .withBody("some_body_response"), makeRequest( request() .withPath(calculatePath("some_other_path")), headersToIgnore) ); } @Test public void shouldReturnResponseByNotMatchingMethodWithNotOperator() { // when mockServerClient .when( request() .withMethod(not("GET")) ) .respond( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withReasonPhrase(HttpStatusCode.ACCEPTED_202.reasonPhrase()) .withBody("some_body_response") ); // then // - in http assertEquals( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withReasonPhrase(HttpStatusCode.ACCEPTED_202.reasonPhrase()) .withBody("some_body_response"), makeRequest( request() .withMethod("POST"), headersToIgnore) ); // - in https assertEquals( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withReasonPhrase(HttpStatusCode.ACCEPTED_202.reasonPhrase()) .withBody("some_body_response"), makeRequest( request() .withMethod("POST"), headersToIgnore) ); } @Test public void shouldReturnResponseByMatchingPathAndMethodAndBody() { // when mockServerClient .when( request() .withMethod("POST") .withPath(calculatePath("some_pathRequest")) .withBody("some_bodyRequest") ) .respond( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withReasonPhrase(HttpStatusCode.ACCEPTED_202.reasonPhrase()) .withBody("some_body_response") .withHeaders(header("headerNameResponse", "headerValueResponse")) ); // then // - in http assertEquals( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withReasonPhrase(HttpStatusCode.ACCEPTED_202.reasonPhrase()) .withBody("some_body_response") .withHeaders( header("headerNameResponse", "headerValueResponse") ), makeRequest( request() .withMethod("POST") .withPath(calculatePath("some_pathRequest")) .withQueryStringParameters( param("queryStringParameterOneName", "queryStringParameterOneValue"), param("queryStringParameterTwoName", "queryStringParameterTwoValue") ) .withBody("some_bodyRequest") .withHeaders(header("headerNameRequest", "headerValueRequest")) .withCookies(cookie("cookieNameRequest", "cookieValueRequest")), headersToIgnore) ); // - in https assertEquals( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withReasonPhrase(HttpStatusCode.ACCEPTED_202.reasonPhrase()) .withBody("some_body_response") .withHeaders( header("headerNameResponse", "headerValueResponse") ), makeRequest( request() .withMethod("POST") .withSecure(true) .withPath(calculatePath("some_pathRequest")) .withQueryStringParameters( param("queryStringParameterOneName", "queryStringParameterOneValue"), param("queryStringParameterTwoName", "queryStringParameterTwoValue") ) .withBody("some_bodyRequest") .withHeaders(header("headerNameRequest", "headerValueRequest")) .withCookies(cookie("cookieNameRequest", "cookieValueRequest")), headersToIgnore) ); } @Test public void shouldReturnResponseByMatchingPathAndMethodAndQueryStringParameters() { // when mockServerClient .when( request() .withMethod("GET") .withPath(calculatePath("some_pathRequest")) .withQueryStringParameters( param("queryStringParameterOneName", "queryStringParameterOneValue"), param("queryStringParameterTwoName", "queryStringParameterTwoValue") ) ) .respond( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withReasonPhrase(HttpStatusCode.ACCEPTED_202.reasonPhrase()) .withBody("some_body_response") .withCookies(cookie("cookieNameResponse", "cookieValueResponse")) ); // then // - in http assertEquals( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withReasonPhrase(HttpStatusCode.ACCEPTED_202.reasonPhrase()) .withBody("some_body_response") .withCookies(cookie("cookieNameResponse", "cookieValueResponse")) .withHeaders( header(SET_COOKIE.toString(), "cookieNameResponse=cookieValueResponse") ), makeRequest( request() .withMethod("GET") .withPath(calculatePath("some_pathRequest")) .withQueryStringParameters( param("queryStringParameterOneName", "queryStringParameterOneValue"), param("queryStringParameterTwoName", "queryStringParameterTwoValue") ) .withHeaders(header("headerNameRequest", "headerValueRequest")) .withCookies(cookie("cookieNameRequest", "cookieValueRequest")), headersToIgnore) ); // - in https assertEquals( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withReasonPhrase(HttpStatusCode.ACCEPTED_202.reasonPhrase()) .withBody("some_body_response") .withCookies(cookie("cookieNameResponse", "cookieValueResponse")) .withHeaders( header(SET_COOKIE.toString(), "cookieNameResponse=cookieValueResponse") ), makeRequest( request() .withMethod("GET") .withSecure(true) .withPath(calculatePath("some_pathRequest")) .withQueryStringParameters( param("queryStringParameterOneName", "queryStringParameterOneValue"), param("queryStringParameterTwoName", "queryStringParameterTwoValue") ) .withHeaders(header("headerNameRequest", "headerValueRequest")) .withCookies(cookie("cookieNameRequest", "cookieValueRequest")), headersToIgnore) ); } @Test public void shouldReturnResponseByMatchingPathAndMethodAndHeaders() { // when mockServerClient .when( request() .withMethod("GET") .withPath(calculatePath("some_pathRequest")) .withHeaders( header("requestHeaderNameOne", "requestHeaderValueOne_One", "requestHeaderValueOne_Two"), header("requestHeaderNameTwo", "requestHeaderValueTwo") ) ) .respond( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withReasonPhrase(HttpStatusCode.ACCEPTED_202.reasonPhrase()) .withBody("some_body_response") .withCookies(cookie("cookieNameResponse", "cookieValueResponse")) ); // then // - in http assertEquals( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withReasonPhrase(HttpStatusCode.ACCEPTED_202.reasonPhrase()) .withBody("some_body_response") .withCookies(cookie("cookieNameResponse", "cookieValueResponse")) .withHeaders( header(SET_COOKIE.toString(), "cookieNameResponse=cookieValueResponse") ), makeRequest( request() .withMethod("GET") .withPath(calculatePath("some_pathRequest")) .withHeaders( header("requestHeaderNameOne", "requestHeaderValueOne_One", "requestHeaderValueOne_Two"), header("requestHeaderNameTwo", "requestHeaderValueTwo") ) .withCookies(cookie("cookieNameRequest", "cookieValueRequest")), headersToIgnore) ); // - in https assertEquals( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withReasonPhrase(HttpStatusCode.ACCEPTED_202.reasonPhrase()) .withBody("some_body_response") .withCookies(cookie("cookieNameResponse", "cookieValueResponse")) .withHeaders( header(SET_COOKIE.toString(), "cookieNameResponse=cookieValueResponse") ), makeRequest( request() .withMethod("GET") .withSecure(true) .withPath(calculatePath("some_pathRequest")) .withHeaders( header("requestHeaderNameOne", "requestHeaderValueOne_One", "requestHeaderValueOne_Two"), header("requestHeaderNameTwo", "requestHeaderValueTwo") ) .withCookies(cookie("cookieNameRequest", "cookieValueRequest")), headersToIgnore) ); } @Test public void shouldReturnResponseByMatchingPathAndMethodAndCookies() { // when mockServerClient .when( request() .withMethod("GET") .withPath(calculatePath("some_pathRequest")) .withCookies( cookie("requestCookieNameOne", "requestCookieValueOne"), cookie("requestCookieNameTwo", "requestCookieValueTwo") ) ) .respond( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withReasonPhrase(HttpStatusCode.ACCEPTED_202.reasonPhrase()) .withBody("some_body_response") .withCookies( cookie("responseCookieNameOne", "responseCookieValueOne"), cookie("responseCookieNameTwo", "responseCookieValueTwo") ) ); // then // - in http - cookie objects assertEquals( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withReasonPhrase(HttpStatusCode.ACCEPTED_202.reasonPhrase()) .withBody("some_body_response") .withCookies( cookie("responseCookieNameOne", "responseCookieValueOne"), cookie("responseCookieNameTwo", "responseCookieValueTwo") ) .withHeaders( header(SET_COOKIE.toString(), "responseCookieNameOne=responseCookieValueOne", "responseCookieNameTwo=responseCookieValueTwo") ), makeRequest( request() .withMethod("GET") .withPath(calculatePath("some_pathRequest")) .withHeaders( header("headerNameRequest", "headerValueRequest"), header(CONTENT_TYPE.toString(), MediaType.create("text", "plain").toString()) ) .withCookies( cookie("requestCookieNameOne", "requestCookieValueOne"), cookie("requestCookieNameTwo", "requestCookieValueTwo") ), headersToIgnore) ); // - in http - cookie header assertEquals( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withReasonPhrase(HttpStatusCode.ACCEPTED_202.reasonPhrase()) .withBody("some_body_response") .withCookies( cookie("responseCookieNameOne", "responseCookieValueOne"), cookie("responseCookieNameTwo", "responseCookieValueTwo") ) .withHeaders( header(SET_COOKIE.toString(), "responseCookieNameOne=responseCookieValueOne", "responseCookieNameTwo=responseCookieValueTwo") ), makeRequest( request() .withMethod("GET") .withPath(calculatePath("some_pathRequest")) .withHeaders( header("headerNameRequest", "headerValueRequest"), header("Cookie", "requestCookieNameOne=requestCookieValueOne; requestCookieNameTwo=requestCookieValueTwo") ), headersToIgnore) ); // - in https - cookie objects assertEquals( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withReasonPhrase(HttpStatusCode.ACCEPTED_202.reasonPhrase()) .withBody("some_body_response") .withCookies( cookie("responseCookieNameOne", "responseCookieValueOne"), cookie("responseCookieNameTwo", "responseCookieValueTwo") ) .withHeaders( header(SET_COOKIE.toString(), "responseCookieNameOne=responseCookieValueOne", "responseCookieNameTwo=responseCookieValueTwo") ), makeRequest( request() .withMethod("GET") .withSecure(true) .withPath(calculatePath("some_pathRequest")) .withHeaders( header("headerNameRequest", "headerValueRequest") ) .withCookies( cookie("requestCookieNameOne", "requestCookieValueOne"), cookie("requestCookieNameTwo", "requestCookieValueTwo") ), headersToIgnore) ); // - in https - cookie header assertEquals( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withReasonPhrase(HttpStatusCode.ACCEPTED_202.reasonPhrase()) .withBody("some_body_response") .withCookies( cookie("responseCookieNameOne", "responseCookieValueOne"), cookie("responseCookieNameTwo", "responseCookieValueTwo") ) .withHeaders( header(SET_COOKIE.toString(), "responseCookieNameOne=responseCookieValueOne", "responseCookieNameTwo=responseCookieValueTwo") ), makeRequest( request() .withMethod("GET") .withSecure(true) .withPath(calculatePath("some_pathRequest")) .withHeaders( header("headerNameRequest", "headerValueRequest"), header("Cookie", "requestCookieNameOne=requestCookieValueOne; requestCookieNameTwo=requestCookieValueTwo") ), headersToIgnore) ); } @Test public void shouldReturnResponseByMatchingPathAndMethodAndQueryStringParametersAndBodyParameters() { // when mockServerClient .when( request() .withMethod("POST") .withPath(calculatePath("some_pathRequest")) .withQueryStringParameters( param("queryStringParameterOneName", "queryStringParameterOneValueOne", "queryStringParameterOneValueTwo"), param("queryStringParameterTwoName", "queryStringParameterTwoValue") ) .withBody(params(param("bodyParameterName", "bodyParameterValue"))) ) .respond( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withReasonPhrase(HttpStatusCode.ACCEPTED_202.reasonPhrase()) .withBody("some_body") ); // then // - in http - url query string assertEquals( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withReasonPhrase(HttpStatusCode.ACCEPTED_202.reasonPhrase()) .withBody("some_body"), makeRequest( request() .withMethod("POST") .withPath(calculatePath("some_pathRequest")) .withQueryStringParameters( param("queryStringParameterOneName", "queryStringParameterOneValueOne", "queryStringParameterOneValueTwo"), param("queryStringParameterTwoName", "queryStringParameterTwoValue") ) .withBody(params(param("bodyParameterName", "bodyParameterValue"))), headersToIgnore) ); // - in https - query string parameter objects assertEquals( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withReasonPhrase(HttpStatusCode.ACCEPTED_202.reasonPhrase()) .withBody("some_body"), makeRequest( request() .withSecure(true) .withMethod("POST") .withPath(calculatePath("some_pathRequest")) .withQueryStringParameters( param("queryStringParameterOneName", "queryStringParameterOneValueOne", "queryStringParameterOneValueTwo"), param("queryStringParameterTwoName", "queryStringParameterTwoValue") ) .withBody(params(param("bodyParameterName", "bodyParameterValue"))), headersToIgnore) ); } @Test public void shouldReturnResponseByMatchingPathAndMethodAndQueryStringParametersAndBody() { // when mockServerClient .when( request() .withMethod("POST") .withPath(calculatePath("some_pathRequest")) .withQueryStringParameters( param("queryStringParameterOneName", "queryStringParameterOneValueOne", "queryStringParameterOneValueTwo"), param("queryStringParameterTwoName", "queryStringParameterTwoValue") ) .withBody("some_bodyRequest") ) .respond( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withReasonPhrase(HttpStatusCode.ACCEPTED_202.reasonPhrase()) .withBody("some_body_response") .withHeaders(header("headerNameResponse", "headerValueResponse")) .withCookies(cookie("cookieNameResponse", "cookieValueResponse")) ); // then // - in http - url query string assertEquals( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withReasonPhrase(HttpStatusCode.ACCEPTED_202.reasonPhrase()) .withBody("some_body_response") .withCookies(cookie("cookieNameResponse", "cookieValueResponse")) .withHeaders( header("headerNameResponse", "headerValueResponse"), header(SET_COOKIE.toString(), "cookieNameResponse=cookieValueResponse") ), makeRequest( request() .withMethod("POST") .withPath(calculatePath("some_pathRequest")) .withQueryStringParameters( param("queryStringParameterOneName", "queryStringParameterOneValueOne", "queryStringParameterOneValueTwo"), param("queryStringParameterTwoName", "queryStringParameterTwoValue") ) .withBody("some_bodyRequest") .withHeaders(header("headerNameRequest", "headerValueRequest")) .withCookies(cookie("cookieNameRequest", "cookieValueRequest")), headersToIgnore) ); // - in http - query string parameter objects assertEquals( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withReasonPhrase(HttpStatusCode.ACCEPTED_202.reasonPhrase()) .withBody("some_body_response") .withCookies(cookie("cookieNameResponse", "cookieValueResponse")) .withHeaders( header("headerNameResponse", "headerValueResponse"), header(SET_COOKIE.toString(), "cookieNameResponse=cookieValueResponse") ), makeRequest( request() .withMethod("POST") .withPath(calculatePath("some_pathRequest")) .withQueryStringParameters( param("queryStringParameterOneName", "queryStringParameterOneValueOne", "queryStringParameterOneValueTwo"), param("queryStringParameterTwoName", "queryStringParameterTwoValue") ) .withBody("some_bodyRequest") .withHeaders(header("headerNameRequest", "headerValueRequest")) .withCookies(cookie("cookieNameRequest", "cookieValueRequest")), headersToIgnore) ); // - in https - url string and query string parameter objects assertEquals( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withReasonPhrase(HttpStatusCode.ACCEPTED_202.reasonPhrase()) .withBody("some_body_response") .withCookies(cookie("cookieNameResponse", "cookieValueResponse")) .withHeaders( header("headerNameResponse", "headerValueResponse"), header(SET_COOKIE.toString(), "cookieNameResponse=cookieValueResponse") ), makeRequest( request() .withMethod("POST") .withPath(calculatePath("some_pathRequest")) .withQueryStringParameters( param("queryStringParameterOneName", "queryStringParameterOneValueOne", "queryStringParameterOneValueTwo"), param("queryStringParameterTwoName", "queryStringParameterTwoValue") ) .withBody("some_bodyRequest") .withHeaders(header("headerNameRequest", "headerValueRequest")) .withCookies(cookie("cookieNameRequest", "cookieValueRequest")), headersToIgnore) ); } @Test public void shouldReturnResponseByMatchingPathAndMethodAndBodyParameters() { // when mockServerClient .when( request() .withMethod("POST") .withPath(calculatePath("some_pathRequest")) .withBody(params( param("bodyParameterOneName", "Parameter One Value One", "Parameter One Value Two"), param("bodyParameterTwoName", "Parameter Two") )) ) .respond( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withReasonPhrase(HttpStatusCode.ACCEPTED_202.reasonPhrase()) .withBody("some_body_response") .withHeaders(header("headerNameResponse", "headerValueResponse")) .withCookies(cookie("cookieNameResponse", "cookieValueResponse")) ); // then // - in http - body string assertEquals( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withReasonPhrase(HttpStatusCode.ACCEPTED_202.reasonPhrase()) .withBody("some_body_response") .withCookies(cookie("cookieNameResponse", "cookieValueResponse")) .withHeaders( header("headerNameResponse", "headerValueResponse"), header(SET_COOKIE.toString(), "cookieNameResponse=cookieValueResponse") ), makeRequest( request() .withMethod("POST") .withPath(calculatePath("some_pathRequest")) .withBody(new StringBody("bodyParameterOneName=Parameter+One+Value+One" + "&bodyParameterOneName=Parameter+One+Value+Two" + "&bodyParameterTwoName=Parameter+Two")) .withHeaders(header("headerNameRequest", "headerValueRequest")) .withCookies(cookie("cookieNameRequest", "cookieValueRequest")), headersToIgnore) ); // - in http - body parameter objects assertEquals( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withReasonPhrase(HttpStatusCode.ACCEPTED_202.reasonPhrase()) .withBody("some_body_response") .withCookies(cookie("cookieNameResponse", "cookieValueResponse")) .withHeaders( header("headerNameResponse", "headerValueResponse"), header(SET_COOKIE.toString(), "cookieNameResponse=cookieValueResponse") ), makeRequest( request() .withMethod("POST") .withPath(calculatePath("some_pathRequest")) .withBody(params( param("bodyParameterOneName", "Parameter One Value One", "Parameter One Value Two"), param("bodyParameterTwoName", "Parameter Two") )) .withHeaders(header("headerNameRequest", "headerValueRequest")) .withCookies(cookie("cookieNameRequest", "cookieValueRequest")), headersToIgnore) ); // - in https - url string and query string parameter objects assertEquals( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withReasonPhrase(HttpStatusCode.ACCEPTED_202.reasonPhrase()) .withBody("some_body_response") .withCookies(cookie("cookieNameResponse", "cookieValueResponse")) .withHeaders( header("headerNameResponse", "headerValueResponse"), header(SET_COOKIE.toString(), "cookieNameResponse=cookieValueResponse") ), makeRequest( request() .withMethod("POST") .withPath(calculatePath("some_pathRequest")) .withBody(params( param("bodyParameterOneName", "Parameter One Value One", "Parameter One Value Two"), param("bodyParameterTwoName", "Parameter Two") )) .withHeaders(header("headerNameRequest", "headerValueRequest")) .withCookies(cookie("cookieNameRequest", "cookieValueRequest")), headersToIgnore) ); } @Test public void shouldReturnResponseByMatchingPathAndMethodAndParametersAndHeadersAndCookies() { // when mockServerClient .when( request() .withMethod("PUT") .withPath(calculatePath("some_pathRequest")) .withBody(new StringBody("bodyParameterOneName=Parameter+One+Value+One" + "&bodyParameterOneName=Parameter+One+Value+Two" + "&bodyParameterTwoName=Parameter+Two")) .withHeaders(header("headerNameRequest", "headerValueRequest")) .withCookies(cookie("cookieNameRequest", "cookieValueRequest")) ) .respond( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withReasonPhrase(HttpStatusCode.ACCEPTED_202.reasonPhrase()) .withBody("some_body_response") .withHeaders(header("headerNameResponse", "headerValueResponse")) .withCookies(cookie("cookieNameResponse", "cookieValueResponse")) ); // then // - in http - body string assertEquals( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withReasonPhrase(HttpStatusCode.ACCEPTED_202.reasonPhrase()) .withBody("some_body_response") .withCookies(cookie("cookieNameResponse", "cookieValueResponse")) .withHeaders( header("headerNameResponse", "headerValueResponse"), header(SET_COOKIE.toString(), "cookieNameResponse=cookieValueResponse") ), makeRequest( request() .withMethod("PUT") .withPath(calculatePath("some_pathRequest")) .withBody(new StringBody("bodyParameterOneName=Parameter+One+Value+One" + "&bodyParameterOneName=Parameter+One+Value+Two" + "&bodyParameterTwoName=Parameter+Two")) .withHeaders( header("headerNameRequest", "headerValueRequest"), header("Cookie", "cookieNameRequest=cookieValueRequest") ), headersToIgnore) ); // - in http - body parameter objects assertEquals( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withReasonPhrase(HttpStatusCode.ACCEPTED_202.reasonPhrase()) .withBody("some_body_response") .withCookies(cookie("cookieNameResponse", "cookieValueResponse")) .withHeaders( header("headerNameResponse", "headerValueResponse"), header(SET_COOKIE.toString(), "cookieNameResponse=cookieValueResponse") ), makeRequest( request() .withMethod("PUT") .withPath(calculatePath("some_pathRequest")) .withBody(params( param("bodyParameterOneName", "Parameter One Value One", "Parameter One Value Two"), param("bodyParameterTwoName", "Parameter Two") )) .withHeaders(header("headerNameRequest", "headerValueRequest")) .withCookies(cookie("cookieNameRequest", "cookieValueRequest")), headersToIgnore) ); } @Test public void shouldReturnResponseByNotMatchingBodyParameterWithNotOperatorForNameAndValue() { // when mockServerClient .when( request() .withMethod("POST") .withPath(calculatePath("some_pathRequest")) .withBody(params( param(not("bodyParameterOneName"), not("Parameter One Value One"), not("Parameter One Value Two")), param("bodyParameterTwoName", "Parameter Two") )) ) .respond( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withReasonPhrase(HttpStatusCode.ACCEPTED_202.reasonPhrase()) .withBody("some_body_response") ); // then // wrong query string parameter name assertEquals( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withReasonPhrase(HttpStatusCode.ACCEPTED_202.reasonPhrase()) .withBody("some_body_response"), makeRequest( request() .withMethod("POST") .withPath(calculatePath("some_pathRequest")) .withBody(params( param("OTHERBodyParameterOneName", "Parameter One Value One", "Parameter One Value Two"), param("bodyParameterTwoName", "Parameter Two") )) .withHeaders(header("headerNameRequest", "headerValueRequest")) .withCookies(cookie("cookieNameRequest", "cookieValueRequest")), headersToIgnore) ); // wrong query string parameter name assertEquals( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withReasonPhrase(HttpStatusCode.ACCEPTED_202.reasonPhrase()) .withBody("some_body_response"), makeRequest( request() .withMethod("POST") .withPath(calculatePath("some_pathRequest")) .withBody(new StringBody("OTHERBodyParameterOneName=Parameter+One+Value+One" + "&OTHERBodyParameterOneName=Parameter+One+Value+Two" + "&bodyParameterTwoName=Parameter+Two")) .withHeaders(header("headerNameRequest", "headerValueRequest")) .withCookies(cookie("cookieNameRequest", "cookieValueRequest")), headersToIgnore) ); // wrong query string parameter value assertEquals( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withReasonPhrase(HttpStatusCode.ACCEPTED_202.reasonPhrase()) .withBody("some_body_response"), makeRequest( request() .withMethod("POST") .withPath(calculatePath("some_pathRequest")) .withBody(params( param("bodyParameterOneName", "OTHER Parameter One Value One", "OTHER Parameter One Value Two"), param("bodyParameterTwoName", "Parameter Two") )) .withHeaders(header("headerNameRequest", "headerValueRequest")) .withCookies(cookie("cookieNameRequest", "cookieValueRequest")), headersToIgnore) ); // wrong query string parameter value assertEquals( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withReasonPhrase(HttpStatusCode.ACCEPTED_202.reasonPhrase()) .withBody("some_body_response"), makeRequest( request() .withMethod("POST") .withPath(calculatePath("some_pathRequest")) .withBody(new StringBody("bodyParameterOneName=OTHER Parameter+One+Value+One" + "&bodyParameterOneName=OTHER Parameter+One+Value+Two" + "&bodyParameterTwoName=Parameter+Two")) .withHeaders(header("headerNameRequest", "headerValueRequest")) .withCookies(cookie("cookieNameRequest", "cookieValueRequest")), headersToIgnore) ); } @Test public void shouldReturnResponseByNotMatchingBodyParameterWithNotOperatorForName() { // when mockServerClient .when( request() .withMethod("POST") .withPath(calculatePath("some_pathRequest")) .withBody(params( param(not("bodyParameterOneName"), string("Parameter One Value One"), string("Parameter One Value Two")), param("bodyParameterTwoName", "Parameter Two") )) ) .respond( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withReasonPhrase(HttpStatusCode.ACCEPTED_202.reasonPhrase()) .withBody("some_body_response") ); // then // wrong query string parameter name assertEquals( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withReasonPhrase(HttpStatusCode.ACCEPTED_202.reasonPhrase()) .withBody("some_body_response"), makeRequest( request() .withMethod("POST") .withPath(calculatePath("some_pathRequest")) .withBody(params( param("OTHERBodyParameterOneName", "Parameter One Value One", "Parameter One Value Two"), param("bodyParameterTwoName", "Parameter Two") )) .withHeaders(header("headerNameRequest", "headerValueRequest")) .withCookies(cookie("cookieNameRequest", "cookieValueRequest")), headersToIgnore) ); // wrong query string parameter name assertEquals( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withReasonPhrase(HttpStatusCode.ACCEPTED_202.reasonPhrase()) .withBody("some_body_response"), makeRequest( request() .withMethod("POST") .withPath(calculatePath("some_pathRequest")) .withBody(new StringBody("OTHERBodyParameterOneName=Parameter+One+Value+One" + "&OTHERBodyParameterOneName=Parameter+One+Value+Two" + "&bodyParameterTwoName=Parameter+Two")) .withHeaders(header("headerNameRequest", "headerValueRequest")) .withCookies(cookie("cookieNameRequest", "cookieValueRequest")), headersToIgnore) ); } @Test public void shouldReturnResponseByNotMatchingBodyParameterWithNotOperatorForValue() { // when mockServerClient .when( request() .withMethod("POST") .withPath(calculatePath("some_pathRequest")) .withBody(params( param(string("bodyParameterOneName"), not("Parameter One Value One"), not("Parameter One Value Two")), param("bodyParameterTwoName", "Parameter Two") )) ) .respond( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withReasonPhrase(HttpStatusCode.ACCEPTED_202.reasonPhrase()) .withBody("some_body_response") ); // then // wrong query string parameter value assertEquals( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withReasonPhrase(HttpStatusCode.ACCEPTED_202.reasonPhrase()) .withBody("some_body_response"), makeRequest( request() .withMethod("POST") .withPath(calculatePath("some_pathRequest")) .withBody(params( param("bodyParameterOneName", "OTHER Parameter One Value One", "OTHER Parameter One Value Two"), param("bodyParameterTwoName", "Parameter Two") )) .withHeaders(header("headerNameRequest", "headerValueRequest")) .withCookies(cookie("cookieNameRequest", "cookieValueRequest")), headersToIgnore) ); // wrong query string parameter value assertEquals( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withReasonPhrase(HttpStatusCode.ACCEPTED_202.reasonPhrase()) .withBody("some_body_response"), makeRequest( request() .withMethod("POST") .withPath(calculatePath("some_pathRequest")) .withBody(new StringBody("bodyParameterOneName=OTHER Parameter+One+Value+One" + "&bodyParameterOneName=OTHER Parameter+One+Value+Two" + "&bodyParameterTwoName=Parameter+Two")) .withHeaders(header("headerNameRequest", "headerValueRequest")) .withCookies(cookie("cookieNameRequest", "cookieValueRequest")), headersToIgnore) ); } @Test public void shouldReturnResponseByNotMatchingQueryStringParameterWithNotOperatorForNameAndValue() { // when mockServerClient .when( request() .withMethod("POST") .withPath(calculatePath("some_pathRequest")) .withQueryStringParameters( param(not("queryStringParameterOneName"), not("Parameter One Value One"), not("Parameter One Value Two")), param("queryStringParameterTwoName", "Parameter Two") ) ) .respond( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withReasonPhrase(HttpStatusCode.ACCEPTED_202.reasonPhrase()) .withBody("some_body_response") ); // then // wrong query string parameter name assertEquals( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withReasonPhrase(HttpStatusCode.ACCEPTED_202.reasonPhrase()) .withBody("some_body_response"), makeRequest( request() .withMethod("POST") .withPath(calculatePath("some_pathRequest")) .withQueryStringParameters( param("OTHERQueryStringParameterOneName", "Parameter One Value One", "Parameter One Value Two"), param("queryStringParameterTwoName", "Parameter Two") ), headersToIgnore) ); // wrong query string parameter value assertEquals( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withReasonPhrase(HttpStatusCode.ACCEPTED_202.reasonPhrase()) .withBody("some_body_response"), makeRequest( request() .withMethod("POST") .withPath(calculatePath("some_pathRequest")) .withQueryStringParameters( param("queryStringParameterOneName", "OTHER Parameter One Value One", "OTHER Parameter One Value Two"), param("queryStringParameterTwoName", "Parameter Two") ), headersToIgnore) ); } @Test public void shouldReturnResponseByNotMatchingQueryStringParameterWithNotOperatorForName() { // when mockServerClient .when( request() .withMethod("POST") .withPath(calculatePath("some_pathRequest")) .withQueryStringParameters( param(not("queryStringParameterOneName"), string("Parameter One Value One"), string("Parameter One Value Two")), param("queryStringParameterTwoName", "Parameter Two") ) ) .respond( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withReasonPhrase(HttpStatusCode.ACCEPTED_202.reasonPhrase()) .withBody("some_body_response") ); // then // wrong query string parameter name assertEquals( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withReasonPhrase(HttpStatusCode.ACCEPTED_202.reasonPhrase()) .withBody("some_body_response"), makeRequest( request() .withMethod("POST") .withPath(calculatePath("some_pathRequest")) .withQueryStringParameters( param("OTHERQueryStringParameterOneName", "Parameter One Value One", "Parameter One Value Two"), param("queryStringParameterTwoName", "Parameter Two") ), headersToIgnore) ); } @Test public void shouldReturnResponseByNotMatchingQueryStringParameterWithNotOperatorForValue() { // when mockServerClient .when( request() .withMethod("POST") .withPath(calculatePath("some_pathRequest")) .withQueryStringParameters( param(string("queryStringParameterOneName"), not("Parameter One Value One"), not("Parameter One Value Two")), param("queryStringParameterTwoName", "Parameter Two") ) ) .respond( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withReasonPhrase(HttpStatusCode.ACCEPTED_202.reasonPhrase()) .withBody("some_body_response") ); // then // wrong query string parameter value assertEquals( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withReasonPhrase(HttpStatusCode.ACCEPTED_202.reasonPhrase()) .withBody("some_body_response"), makeRequest( request() .withMethod("POST") .withPath(calculatePath("some_pathRequest")) .withQueryStringParameters( param("queryStringParameterOneName", "OTHER Parameter One Value One", "OTHER Parameter One Value Two"), param("queryStringParameterTwoName", "Parameter Two") ), headersToIgnore) ); } @Test public void shouldReturnResponseByNotMatchingCookieWithNotOperatorForNameAndValue() { // when mockServerClient .when( request() .withMethod("GET") .withPath(calculatePath("some_pathRequest")) .withCookies( cookie(not("requestCookieNameOne"), not("requestCookieValueOne")), cookie("requestCookieNameTwo", "requestCookieValueTwo") ) ) .respond( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withReasonPhrase(HttpStatusCode.ACCEPTED_202.reasonPhrase()) .withBody("some_body_response") ); // then // wrong query string cookie name assertEquals( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withReasonPhrase(HttpStatusCode.ACCEPTED_202.reasonPhrase()) .withBody("some_body_response"), makeRequest( request() .withMethod("GET") .withPath(calculatePath("some_pathRequest")) .withCookies( cookie("OTHERrequestCookieNameOne", "requestCookieValueOne"), cookie("requestCookieNameTwo", "requestCookieValueTwo") ), headersToIgnore) ); // wrong query string cookie value assertEquals( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withReasonPhrase(HttpStatusCode.ACCEPTED_202.reasonPhrase()) .withBody("some_body_response"), makeRequest( request() .withMethod("GET") .withPath(calculatePath("some_pathRequest")) .withCookies( cookie("requestCookieNameOne", "OTHERrequestCookieValueOne"), cookie("requestCookieNameTwo", "requestCookieValueTwo") ), headersToIgnore) ); } @Test public void shouldReturnResponseByNotMatchingCookieWithNotOperatorForName() { // when mockServerClient .when( request() .withMethod("GET") .withPath(calculatePath("some_pathRequest")) .withCookies( cookie(not("requestCookieNameOne"), string("requestCookieValueOne")), cookie("requestCookieNameTwo", "requestCookieValueTwo") ) ) .respond( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withReasonPhrase(HttpStatusCode.ACCEPTED_202.reasonPhrase()) .withBody("some_body_response") ); // then // wrong query string cookie name assertEquals( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withReasonPhrase(HttpStatusCode.ACCEPTED_202.reasonPhrase()) .withBody("some_body_response"), makeRequest( request() .withMethod("GET") .withPath(calculatePath("some_pathRequest")) .withCookies( cookie("OTHERrequestCookieNameOne", "requestCookieValueOne"), cookie("requestCookieNameTwo", "requestCookieValueTwo") ), headersToIgnore) ); } @Test public void shouldReturnResponseByNotMatchingCookieWithNotOperatorForValue() { // when mockServerClient .when( request() .withMethod("GET") .withPath(calculatePath("some_pathRequest")) .withCookies( cookie(string("requestCookieNameOne"), not("requestCookieValueOne")), cookie("requestCookieNameTwo", "requestCookieValueTwo") ) ) .respond( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withReasonPhrase(HttpStatusCode.ACCEPTED_202.reasonPhrase()) .withBody("some_body_response") ); // then // wrong query string cookie value assertEquals( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withReasonPhrase(HttpStatusCode.ACCEPTED_202.reasonPhrase()) .withBody("some_body_response"), makeRequest( request() .withMethod("GET") .withPath(calculatePath("some_pathRequest")) .withCookies( cookie("requestCookieNameOne", "OTHERrequestCookieValueOne"), cookie("requestCookieNameTwo", "requestCookieValueTwo") ), headersToIgnore) ); } @Test public void shouldReturnResponseByNotMatchingHeaderWithNotOperatorForNameAndValue() { // when mockServerClient .when( request() .withMethod("GET") .withPath(calculatePath("some_pathRequest")) .withHeaders( header(not("requestHeaderNameOne"), not("requestHeaderValueOne")), header("requestHeaderNameTwo", "requestHeaderValueTwo") ) ) .respond( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withReasonPhrase(HttpStatusCode.ACCEPTED_202.reasonPhrase()) .withBody("some_body_response") ); // then // wrong query string header name assertEquals( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withReasonPhrase(HttpStatusCode.ACCEPTED_202.reasonPhrase()) .withBody("some_body_response"), makeRequest( request() .withMethod("GET") .withPath(calculatePath("some_pathRequest")) .withHeaders( header("OTHERrequestHeaderNameOne", "requestHeaderValueOne"), header("requestHeaderNameTwo", "requestHeaderValueTwo") ), headersToIgnore) ); // wrong query string header value assertEquals( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withReasonPhrase(HttpStatusCode.ACCEPTED_202.reasonPhrase()) .withBody("some_body_response"), makeRequest( request() .withMethod("GET") .withPath(calculatePath("some_pathRequest")) .withHeaders( header("requestHeaderNameOne", "OTHERrequestHeaderValueOne"), header("requestHeaderNameTwo", "requestHeaderValueTwo") ), headersToIgnore) ); } @Test public void shouldReturnResponseByNotMatchingHeaderWithNotOperatorForName() { // when mockServerClient .when( request() .withMethod("GET") .withPath(calculatePath("some_pathRequest")) .withHeaders( header(not("requestHeaderNameOne"), string("requestHeaderValueOne")), header("requestHeaderNameTwo", "requestHeaderValueTwo") ) ) .respond( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withReasonPhrase(HttpStatusCode.ACCEPTED_202.reasonPhrase()) .withBody("some_body_response") ); // then // wrong query string header name assertEquals( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withReasonPhrase(HttpStatusCode.ACCEPTED_202.reasonPhrase()) .withBody("some_body_response"), makeRequest( request() .withMethod("GET") .withPath(calculatePath("some_pathRequest")) .withHeaders( header("OTHERrequestHeaderNameOne", "requestHeaderValueOne"), header("requestHeaderNameTwo", "requestHeaderValueTwo") ), headersToIgnore) ); } @Test public void shouldReturnResponseByNotMatchingHeaderWithNotOperatorForValue() { // when mockServerClient .when( request() .withMethod("GET") .withPath(calculatePath("some_pathRequest")) .withHeaders( header(string("requestHeaderNameOne"), not("requestHeaderValueOne")), header("requestHeaderNameTwo", "requestHeaderValueTwo") ) ) .respond( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withReasonPhrase(HttpStatusCode.ACCEPTED_202.reasonPhrase()) .withBody("some_body_response") ); // then // wrong query string header value assertEquals( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withReasonPhrase(HttpStatusCode.ACCEPTED_202.reasonPhrase()) .withBody("some_body_response"), makeRequest( request() .withMethod("GET") .withPath(calculatePath("some_pathRequest")) .withHeaders( header("requestHeaderNameOne", "OTHERrequestHeaderValueOne"), header("requestHeaderNameTwo", "requestHeaderValueTwo") ), headersToIgnore) ); } @Test public void shouldNotReturnResponseForWhenTimeToLiveExpired() { // when mockServerClient .when( request().withPath(calculatePath("some_path")), exactly(2), TimeToLive.exactly(TimeUnit.SECONDS, 3L) ) .respond( response().withBody("some_body").withDelay(TimeUnit.SECONDS, 3L) ); // then assertEquals( response() .withStatusCode(OK_200.code()) .withReasonPhrase(OK_200.reasonPhrase()) .withBody("some_body"), makeRequest( request() .withPath(calculatePath("some_path")), headersToIgnore) ); // - in http assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()) .withReasonPhrase(HttpStatusCode.NOT_FOUND_404.reasonPhrase()), makeRequest( request() .withPath(calculatePath("some_path")), headersToIgnore) ); // - in https assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()) .withReasonPhrase(HttpStatusCode.NOT_FOUND_404.reasonPhrase()), makeRequest( request() .withSecure(true) .withPath(calculatePath("some_path")), headersToIgnore) ); } @Test public void shouldNotReturnResponseForMatchingBodyWithNotOperator() { // when mockServerClient .when( request() .withBody(Not.not(json("{" + NEW_LINE + " \"id\": 1," + NEW_LINE + " \"name\": \"A green door\"," + NEW_LINE + " \"price\": 12.50," + NEW_LINE + " \"tags\": [\"home\", \"green\"]" + NEW_LINE + "}"))), exactly(2) ) .respond( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withReasonPhrase(HttpStatusCode.ACCEPTED_202.reasonPhrase()) .withBody("some_body") ); // then // - in http assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()) .withReasonPhrase(HttpStatusCode.NOT_FOUND_404.reasonPhrase()), makeRequest( request() .withPath(calculatePath("some_path")) .withMethod("POST") .withBody("{" + NEW_LINE + " \"id\": 1," + NEW_LINE + " \"extra_ignored_field\": \"some value\"," + NEW_LINE + " \"name\": \"A green door\"," + NEW_LINE + " \"price\": 12.50," + NEW_LINE + " \"tags\": [\"home\", \"green\"]" + NEW_LINE + "}"), headersToIgnore) ); // - in https assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()) .withReasonPhrase(HttpStatusCode.NOT_FOUND_404.reasonPhrase()), makeRequest( request() .withSecure(true) .withPath(calculatePath("some_path")) .withMethod("POST") .withBody("{" + NEW_LINE + " \"id\": 1," + NEW_LINE + " \"extra_ignored_array\": [\"one\", \"two\"]," + NEW_LINE + " \"name\": \"A green door\"," + NEW_LINE + " \"price\": 12.50," + NEW_LINE + " \"tags\": [\"home\", \"green\"]" + NEW_LINE + "}"), headersToIgnore) ); } @Test public void shouldNotReturnResponseForNonMatchingXPathBody() { // when mockServerClient.when(request().withBody(new XPathBody("/bookstore/book[price>35]/price")), exactly(2)).respond(response().withBody("some_body")); // then // - in http assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()) .withReasonPhrase(HttpStatusCode.NOT_FOUND_404.reasonPhrase()), makeRequest( request() .withSecure(true) .withPath(calculatePath("some_path")) .withMethod("POST") .withBody(new StringBody("" + "<?xml version=\"1.0\" encoding=\"ISO-8859-1\"?>" + NEW_LINE + "<bookstore>" + NEW_LINE + " <book category=\"COOKING\">" + NEW_LINE + " <title lang=\"en\">Everyday Italian</title>" + NEW_LINE + " <author>Giada De Laurentiis</author>" + NEW_LINE + " <year>2005</year>" + NEW_LINE + " <price>30.00</price>" + NEW_LINE + " </book>" + NEW_LINE + " <book category=\"CHILDREN\">" + NEW_LINE + " <title lang=\"en\">Harry Potter</title>" + NEW_LINE + " <author>J K. Rowling</author>" + NEW_LINE + " <year>2005</year>" + NEW_LINE + " <price>29.99</price>" + NEW_LINE + " </book>" + NEW_LINE + " <book category=\"WEB\">" + NEW_LINE + " <title lang=\"en\">Learning XML</title>" + NEW_LINE + " <author>Erik T. Ray</author>" + NEW_LINE + " <year>2003</year>" + NEW_LINE + " <price>31.95</price>" + NEW_LINE + " </book>" + NEW_LINE + "</bookstore>")), headersToIgnore) ); // - in https assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()) .withReasonPhrase(HttpStatusCode.NOT_FOUND_404.reasonPhrase()), makeRequest( request() .withSecure(true) .withPath(calculatePath("some_path")) .withMethod("POST") .withBody(new StringBody("" + "<?xml version=\"1.0\" encoding=\"ISO-8859-1\"?>" + NEW_LINE + "<bookstore>" + NEW_LINE + " <book category=\"COOKING\">" + NEW_LINE + " <title lang=\"en\">Everyday Italian</title>" + NEW_LINE + " <author>Giada De Laurentiis</author>" + NEW_LINE + " <year>2005</year>" + NEW_LINE + " <price>30.00</price>" + NEW_LINE + " </book>" + NEW_LINE + " <book category=\"CHILDREN\">" + NEW_LINE + " <title lang=\"en\">Harry Potter</title>" + NEW_LINE + " <author>J K. Rowling</author>" + NEW_LINE + " <year>2005</year>" + NEW_LINE + " <price>29.99</price>" + NEW_LINE + " </book>" + NEW_LINE + " <book category=\"WEB\">" + NEW_LINE + " <title lang=\"en\">Learning XML</title>" + NEW_LINE + " <author>Erik T. Ray</author>" + NEW_LINE + " <year>2003</year>" + NEW_LINE + " <price>31.95</price>" + NEW_LINE + " </book>" + NEW_LINE + "</bookstore>")), headersToIgnore) ); } @Test public void shouldNotReturnResponseForNonMatchingXmlBody() { // when mockServerClient.when(request().withBody(xml("" + "<?xml version=\"1.0\" encoding=\"ISO-8859-1\"?>" + NEW_LINE + "<bookstore>" + NEW_LINE + " <book category=\"COOKING\" nationality=\"ITALIAN\">" + NEW_LINE + " <title lang=\"en\">Everyday Italian</title>" + NEW_LINE + " <author>Giada De Laurentiis</author>" + NEW_LINE + " <year>2005</year>" + NEW_LINE + " <price>30.00</price>" + NEW_LINE + " </book>" + NEW_LINE + "</bookstore>")), exactly(2)).respond(response().withBody("some_body")); // then // - in http assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()) .withReasonPhrase(HttpStatusCode.NOT_FOUND_404.reasonPhrase()), makeRequest( request() .withSecure(true) .withPath(calculatePath("some_path")) .withMethod("POST") .withBody(new StringBody("" + "<?xml version=\"1.0\" encoding=\"ISO-8859-1\"?>" + NEW_LINE + "<bookstore>" + NEW_LINE + " <book category=\"COOKING\">" + NEW_LINE + " <title lang=\"en\">Everyday Italian</title>" + NEW_LINE + " <author>Giada De Laurentiis</author>" + NEW_LINE + " <year>2005</year>" + NEW_LINE + " <price>30.00</price>" + NEW_LINE + " </book>" + NEW_LINE + "</bookstore>")), headersToIgnore) ); // - in https assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()) .withReasonPhrase(HttpStatusCode.NOT_FOUND_404.reasonPhrase()), makeRequest( request() .withSecure(true) .withPath(calculatePath("some_path")) .withMethod("POST") .withBody(new StringBody("" + "<?xml version=\"1.0\" encoding=\"ISO-8859-1\"?>" + NEW_LINE + "<bookstore>" + NEW_LINE + " <book category=\"COOKING\">" + NEW_LINE + " <title lang=\"en\">Everyday Italian</title>" + NEW_LINE + " <author>Giada De Laurentiis</author>" + NEW_LINE + " <year>2005</year>" + NEW_LINE + " <price>30.00</price>" + NEW_LINE + " </book>" + NEW_LINE + "</bookstore>")), headersToIgnore) ); } @Test public void shouldNotReturnResponseForNonMatchingJsonBody() { // when mockServerClient.when(request().withBody(json("{" + NEW_LINE + " \"id\": 1," + NEW_LINE + " \"name\": \"A green door\"," + NEW_LINE + " \"price\": 12.50," + NEW_LINE + " \"tags\": [\"home\", \"green\"]" + NEW_LINE + "}")), exactly(2)).respond(response().withBody("some_body")); // then // - in http assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()) .withReasonPhrase(HttpStatusCode.NOT_FOUND_404.reasonPhrase()), makeRequest( request() .withPath(calculatePath("some_path")) .withMethod("POST") .withBody("{" + NEW_LINE + " \"id\": 1," + NEW_LINE + " \"name\": \"---- XXXX WRONG VALUE XXXX ----\"," + NEW_LINE + " \"price\": 12.50," + NEW_LINE + " \"tags\": [\"home\", \"green\"]" + NEW_LINE + "}"), headersToIgnore) ); // - in https assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()) .withReasonPhrase(HttpStatusCode.NOT_FOUND_404.reasonPhrase()), makeRequest( request() .withSecure(true) .withPath(calculatePath("some_path")) .withMethod("POST") .withBody("{" + NEW_LINE + " \"id\": 1," + NEW_LINE + " \"name\": \"---- XXXX WRONG VALUE XXXX ----\"," + NEW_LINE + " \"price\": 12.50," + NEW_LINE + " \"tags\": [\"home\", \"green\"]" + NEW_LINE + "}"), headersToIgnore) ); } @Test public void shouldNotReturnResponseForNonMatchingJsonBodyWithMatchType() { // when mockServerClient .when( request() .withBody(json("{" + NEW_LINE + " \"id\": 1," + NEW_LINE + " \"name\": \"A green door\"," + NEW_LINE + " \"price\": 12.50," + NEW_LINE + " \"tags\": [\"home\", \"green\"]" + NEW_LINE + "}", MatchType.STRICT)), exactly(2)) .respond( response() .withBody("some_body") ); // then // - in http assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()) .withReasonPhrase(HttpStatusCode.NOT_FOUND_404.reasonPhrase()), makeRequest( request() .withPath(calculatePath("some_path")) .withMethod("POST") .withBody("{" + NEW_LINE + " \"id\": 1," + NEW_LINE + " \"extra field\": \"some value\"," + NEW_LINE + " \"name\": \"A green door\"," + NEW_LINE + " \"price\": 12.50," + NEW_LINE + " \"tags\": [\"home\", \"green\"]" + NEW_LINE + "}"), headersToIgnore) ); // - in https assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()) .withReasonPhrase(HttpStatusCode.NOT_FOUND_404.reasonPhrase()), makeRequest( request() .withSecure(true) .withPath(calculatePath("some_path")) .withMethod("POST") .withBody("{" + NEW_LINE + " \"id\": 1," + NEW_LINE + " \"extra field\": \"some value\"," + NEW_LINE + " \"name\": \"A green door\"," + NEW_LINE + " \"price\": 12.50," + NEW_LINE + " \"tags\": [\"home\", \"green\"]" + NEW_LINE + "}"), headersToIgnore) ); } @Test public void shouldNotReturnResponseForNonMatchingJsonSchema() { // when mockServerClient.when(request().withBody(jsonSchema("{" + NEW_LINE + " \"$schema\": \"http://json-schema.org/draft-04/schema#\"," + NEW_LINE + " \"title\": \"Product\"," + NEW_LINE + " \"description\": \"A product from Acme's catalog\"," + NEW_LINE + " \"type\": \"object\"," + NEW_LINE + " \"properties\": {" + NEW_LINE + " \"id\": {" + NEW_LINE + " \"description\": \"The unique identifier for a product\"," + NEW_LINE + " \"type\": \"integer\"" + NEW_LINE + " }," + NEW_LINE + " \"name\": {" + NEW_LINE + " \"description\": \"Name of the product\"," + NEW_LINE + " \"type\": \"string\"" + NEW_LINE + " }," + NEW_LINE + " \"price\": {" + NEW_LINE + " \"type\": \"number\"," + NEW_LINE + " \"minimum\": 0," + NEW_LINE + " \"exclusiveMinimum\": true" + NEW_LINE + " }," + NEW_LINE + " \"tags\": {" + NEW_LINE + " \"type\": \"array\"," + NEW_LINE + " \"items\": {" + NEW_LINE + " \"type\": \"string\"" + NEW_LINE + " }," + NEW_LINE + " \"minItems\": 1," + NEW_LINE + " \"uniqueItems\": true" + NEW_LINE + " }" + NEW_LINE + " }," + NEW_LINE + " \"required\": [\"id\", \"name\", \"price\"]" + NEW_LINE + "}")), exactly(2)).respond(response().withBody("some_body")); // then // - in http assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()) .withReasonPhrase(HttpStatusCode.NOT_FOUND_404.reasonPhrase()), makeRequest( request() .withPath(calculatePath("some_path")) .withMethod("POST") .withBody("{" + NEW_LINE + " \"id\": 1," + NEW_LINE + " \"wrong field name\": \"A green door\"," + NEW_LINE + " \"price\": 12.50," + NEW_LINE + " \"tags\": [\"home\", \"green\"]" + NEW_LINE + "}"), headersToIgnore) ); // - in https assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()) .withReasonPhrase(HttpStatusCode.NOT_FOUND_404.reasonPhrase()), makeRequest( request() .withSecure(true) .withPath(calculatePath("some_path")) .withMethod("POST") .withBody("{" + NEW_LINE + " \"id\": 1," + NEW_LINE + " \"name\": \"A green door\"," + NEW_LINE + " \"wrong field name\": 12.50," + NEW_LINE + " \"tags\": [\"home\", \"green\"]" + NEW_LINE + "}"), headersToIgnore) ); } @Test public void shouldNotReturnResponseForMatchingPathWithNotOperator() { // when mockServerClient .when( request() .withPath(not(calculatePath("some_path"))) ) .respond( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withReasonPhrase(HttpStatusCode.ACCEPTED_202.reasonPhrase()) .withBody("some_body_response") ); // then // - in http assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()) .withReasonPhrase(HttpStatusCode.NOT_FOUND_404.reasonPhrase()), makeRequest( request() .withPath(calculatePath("some_path")), headersToIgnore) ); // - in https assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()) .withReasonPhrase(HttpStatusCode.NOT_FOUND_404.reasonPhrase()), makeRequest( request() .withPath(calculatePath("some_path")), headersToIgnore) ); } @Test public void shouldNotReturnResponseForMatchingMethodWithNotOperator() { // when mockServerClient .when( request() .withMethod(not("GET")) ) .respond( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withReasonPhrase(HttpStatusCode.ACCEPTED_202.reasonPhrase()) .withBody("some_body_response") ); // then // - in http assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()) .withReasonPhrase(HttpStatusCode.NOT_FOUND_404.reasonPhrase()), makeRequest( request() .withMethod("GET"), headersToIgnore) ); // - in https assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()) .withReasonPhrase(HttpStatusCode.NOT_FOUND_404.reasonPhrase()), makeRequest( request() .withMethod("GET"), headersToIgnore) ); } @Test public void shouldNotReturnResponseForNonMatchingBodyParameterName() { // when mockServerClient .when( request() .withMethod("POST") .withPath(calculatePath("some_pathRequest")) .withBody(params( param("bodyParameterOneName", "Parameter One Value One", "Parameter One Value Two"), param("bodyParameterTwoName", "Parameter Two") )) ) .respond( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withReasonPhrase(HttpStatusCode.ACCEPTED_202.reasonPhrase()) .withBody("some_body_response") .withHeaders(header("headerNameResponse", "headerValueResponse")) .withCookies(cookie("cookieNameResponse", "cookieValueResponse")) ); // then // wrong query string parameter name assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()) .withReasonPhrase(HttpStatusCode.NOT_FOUND_404.reasonPhrase()), makeRequest( request() .withMethod("POST") .withPath(calculatePath("some_pathRequest")) .withBody(params( param("OTHERBodyParameterOneName", "Parameter One Value One", "Parameter One Value Two"), param("bodyParameterTwoName", "Parameter Two") )) .withHeaders(header("headerNameRequest", "headerValueRequest")) .withCookies(cookie("cookieNameRequest", "cookieValueRequest")), headersToIgnore) ); // wrong query string parameter name assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()) .withReasonPhrase(HttpStatusCode.NOT_FOUND_404.reasonPhrase()), makeRequest( request() .withMethod("POST") .withPath(calculatePath("some_pathRequest")) .withBody(new StringBody("OTHERBodyParameterOneName=Parameter+One+Value+One" + "&bodyParameterOneName=Parameter+One+Value+Two" + "&bodyParameterTwoName=Parameter+Two")) .withHeaders(header("headerNameRequest", "headerValueRequest")) .withCookies(cookie("cookieNameRequest", "cookieValueRequest")), headersToIgnore) ); } @Test public void shouldNotReturnResponseForMatchingBodyParameterWithNotOperator() { // when mockServerClient .when( request() .withMethod("POST") .withPath(calculatePath("some_pathRequest")) .withBody(params( param(not("bodyParameterOneName"), not("Parameter One Value One"), not("Parameter One Value Two")), param("bodyParameterTwoName", "Parameter Two") )) ) .respond( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withReasonPhrase(HttpStatusCode.ACCEPTED_202.reasonPhrase()) .withBody("some_body_response") ); // then // wrong query string parameter name assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()) .withReasonPhrase(HttpStatusCode.NOT_FOUND_404.reasonPhrase()), makeRequest( request() .withMethod("POST") .withPath(calculatePath("some_pathRequest")) .withBody(params( param("bodyParameterOneName", "Parameter One Value One", "Parameter One Value Two"), param("bodyParameterTwoName", "Parameter Two") )) .withHeaders(header("headerNameRequest", "headerValueRequest")) .withCookies(cookie("cookieNameRequest", "cookieValueRequest")), headersToIgnore) ); // wrong query string parameter name assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()) .withReasonPhrase(HttpStatusCode.NOT_FOUND_404.reasonPhrase()), makeRequest( request() .withMethod("POST") .withPath(calculatePath("some_pathRequest")) .withBody(new StringBody("bodyParameterOneName=Other Parameter+One+Value+One" + "&bodyParameterOneName=Parameter+One+Value+Two" + "&bodyParameterTwoName=Parameter+Two")) .withHeaders(header("headerNameRequest", "headerValueRequest")) .withCookies(cookie("cookieNameRequest", "cookieValueRequest")), headersToIgnore) ); } @Test public void shouldNotReturnResponseForNonMatchingBodyParameterValue() { // when mockServerClient .when( request() .withMethod("POST") .withPath(calculatePath("some_pathRequest")) .withBody(params( param("bodyParameterOneName", "Parameter One Value One", "Parameter One Value Two"), param("bodyParameterTwoName", "Parameter Two") )) ) .respond( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withReasonPhrase(HttpStatusCode.ACCEPTED_202.reasonPhrase()) .withBody("some_body_response") .withHeaders(header("headerNameResponse", "headerValueResponse")) .withCookies(cookie("cookieNameResponse", "cookieValueResponse")) ); // then // wrong body parameter value assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()) .withReasonPhrase(HttpStatusCode.NOT_FOUND_404.reasonPhrase()), makeRequest( request() .withMethod("POST") .withPath(calculatePath("some_pathRequest")) .withBody(params( param("bodyParameterOneName", "Other Parameter One Value One", "Parameter One Value Two"), param("bodyParameterTwoName", "Parameter Two") )) .withHeaders(header("headerNameRequest", "headerValueRequest")) .withCookies(cookie("cookieNameRequest", "cookieValueRequest")), headersToIgnore) ); // wrong body parameter value assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()) .withReasonPhrase(HttpStatusCode.NOT_FOUND_404.reasonPhrase()), makeRequest( request() .withMethod("POST") .withPath(calculatePath("some_pathRequest")) .withBody(new StringBody("bodyParameterOneName=Other Parameter+One+Value+One" + "&bodyParameterOneName=Parameter+One+Value+Two" + "&bodyParameterTwoName=Parameter+Two")) .withHeaders(header("headerNameRequest", "headerValueRequest")) .withCookies(cookie("cookieNameRequest", "cookieValueRequest")), headersToIgnore) ); } @Test public void shouldNotReturnResponseForNonMatchingQueryStringParameterName() { // when mockServerClient .when( request() .withMethod("POST") .withPath(calculatePath("some_pathRequest")) .withQueryStringParameters( param("queryStringParameterOneName", "queryStringParameterOneValueOne", "queryStringParameterOneValueTwo"), param("queryStringParameterTwoName", "queryStringParameterTwoValue") ) .withBody("some_bodyRequest") ) .respond( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withReasonPhrase(HttpStatusCode.ACCEPTED_202.reasonPhrase()) .withBody("some_body_response") .withHeaders(header("headerNameResponse", "headerValueResponse")) .withCookies(cookie("cookieNameResponse", "cookieValueResponse")) ); // then // wrong query string parameter name assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()) .withReasonPhrase(HttpStatusCode.NOT_FOUND_404.reasonPhrase()), makeRequest( request() .withMethod("POST") .withPath(calculatePath("some_pathRequest")) .withQueryStringParameters( param("OTHERQueryStringParameterOneName", "queryStringParameterOneValueOne", "queryStringParameterOneValueTwo"), param("queryStringParameterTwoName", "queryStringParameterTwoValue") ) .withBody("some_bodyRequest") .withHeaders( header("headerNameRequest", "headerValueRequest") ) .withCookies(cookie("cookieNameRequest", "cookieValueRequest")), headersToIgnore) ); } @Test public void shouldNotReturnResponseForNonMatchingQueryStringParameterValue() { // when mockServerClient .when( request() .withMethod("POST") .withPath(calculatePath("some_pathRequest")) .withQueryStringParameters( param("queryStringParameterOneName", "queryStringParameterOneValueOne", "queryStringParameterOneValueTwo"), param("queryStringParameterTwoName", "queryStringParameterTwoValue") ) .withBody("some_bodyRequest") ) .respond( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withReasonPhrase(HttpStatusCode.ACCEPTED_202.reasonPhrase()) .withBody("some_body_response") .withHeaders(header("headerNameResponse", "headerValueResponse")) .withCookies(cookie("cookieNameResponse", "cookieValueResponse")) ); // then // wrong query string parameter value assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()) .withReasonPhrase(HttpStatusCode.NOT_FOUND_404.reasonPhrase()), makeRequest( request() .withMethod("POST") .withPath(calculatePath("some_pathRequest")) .withQueryStringParameters( param("queryStringParameterOneName", "OTHERqueryStringParameterOneValueOne", "queryStringParameterOneValueTwo"), param("queryStringParameterTwoName", "queryStringParameterTwoValue") ) .withBody("some_bodyRequest") .withHeaders(header("headerNameRequest", "headerValueRequest")) .withCookies(cookie("cookieNameRequest", "cookieValueRequest")), headersToIgnore) ); } @Test public void shouldNotReturnResponseForMatchingQueryStringParameterWithNotOperator() { // when mockServerClient .when( request() .withMethod("POST") .withPath(calculatePath("some_pathRequest")) .withQueryStringParameters( param(not("queryStringParameterOneName"), not("Parameter One Value One"), not("Parameter One Value Two")), param("queryStringParameterTwoName", "Parameter Two") ) ) .respond( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withReasonPhrase(HttpStatusCode.ACCEPTED_202.reasonPhrase()) .withBody("some_body_response") ); // then // wrong query string parameter name assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()) .withReasonPhrase(HttpStatusCode.NOT_FOUND_404.reasonPhrase()), makeRequest( request() .withMethod("POST") .withPath(calculatePath("some_pathRequest")) .withQueryStringParameters( param("queryStringParameterOneName", "Parameter One Value One", "Parameter One Value Two"), param("queryStringParameterTwoName", "Parameter Two") ), headersToIgnore) ); // wrong query string parameter name assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()) .withReasonPhrase(HttpStatusCode.NOT_FOUND_404.reasonPhrase()), makeRequest( request() .withMethod("POST") .withPath(calculatePath("some_pathRequest")) .withQueryStringParameters( param("queryStringParameterOneName", "Parameter One Value One", "Parameter One Value Two"), param("queryStringParameterTwoName", "Parameter Two") ), headersToIgnore) ); } @Test public void shouldNotReturnResponseForNonMatchingCookieName() { // when mockServerClient .when( request() .withMethod("GET") .withPath(calculatePath("some_path")) .withQueryStringParameters( param("queryStringParameterOneName", "queryStringParameterOneValue"), param("queryStringParameterTwoName", "queryStringParameterTwoValue") ) .withBody(exact("some_body")) .withHeaders(header("headerName", "headerValue")) .withCookies(cookie("cookieName", "cookieValue")) ) .respond( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withReasonPhrase(HttpStatusCode.ACCEPTED_202.reasonPhrase()) .withBody("some_body") .withHeaders(header("headerName", "headerValue")) .withCookies(cookie("cookieName", "cookieValue")) ); // then // - in http assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()) .withReasonPhrase(HttpStatusCode.NOT_FOUND_404.reasonPhrase()), makeRequest( request() .withMethod("GET") .withPath(calculatePath("some_path")) .withQueryStringParameters( param("queryStringParameterOneName", "queryStringParameterOneValue"), param("queryStringParameterTwoName", "queryStringParameterTwoValue") ) .withBody(exact("some_body")) .withHeaders(header("headerName", "headerValue")) .withCookies(cookie("cookieOtherName", "cookieValue")), headersToIgnore) ); // - in https assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()) .withReasonPhrase(HttpStatusCode.NOT_FOUND_404.reasonPhrase()), makeRequest( request() .withMethod("GET") .withSecure(true) .withPath(calculatePath("some_path")) .withQueryStringParameters( param("queryStringParameterOneName", "queryStringParameterOneValue"), param("queryStringParameterTwoName", "queryStringParameterTwoValue") ) .withBody(exact("some_body")) .withHeaders(header("headerName", "headerValue")) .withCookies(cookie("cookieOtherName", "cookieValue")), headersToIgnore) ); } @Test public void shouldNotReturnResponseForNonMatchingCookieValue() { // when mockServerClient .when( request() .withMethod("GET") .withPath(calculatePath("some_path")) .withQueryStringParameters( param("queryStringParameterOneName", "queryStringParameterOneValue"), param("queryStringParameterTwoName", "queryStringParameterTwoValue") ) .withBody(exact("some_body")) .withHeaders(header("headerName", "headerValue")) .withCookies(cookie("cookieName", "cookieValue")) ) .respond( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withReasonPhrase(HttpStatusCode.ACCEPTED_202.reasonPhrase()) .withBody("some_body") .withHeaders(header("headerName", "headerValue")) .withCookies(cookie("cookieName", "cookieValue")) ); // then // - in http assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()) .withReasonPhrase(HttpStatusCode.NOT_FOUND_404.reasonPhrase()), makeRequest( request() .withMethod("GET") .withPath(calculatePath("some_path")) .withQueryStringParameters( param("queryStringParameterOneName", "queryStringParameterOneValue"), param("queryStringParameterTwoName", "queryStringParameterTwoValue") ) .withBody(exact("some_body")) .withHeaders(header("headerName", "headerValue")) .withCookies(cookie("cookieName", "cookieOtherValue")), headersToIgnore) ); // - in https assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()) .withReasonPhrase(HttpStatusCode.NOT_FOUND_404.reasonPhrase()), makeRequest( request() .withMethod("GET") .withSecure(true) .withPath(calculatePath("some_path")) .withQueryStringParameters( param("queryStringParameterOneName", "queryStringParameterOneValue"), param("queryStringParameterTwoName", "queryStringParameterTwoValue") ) .withBody(exact("some_body")) .withHeaders(header("headerName", "headerValue")) .withCookies(cookie("cookieName", "cookieOtherValue")), headersToIgnore) ); } @Test public void shouldNotReturnResponseForMatchingCookieWithNotOperator() { // when mockServerClient .when( request() .withMethod("GET") .withPath(calculatePath("some_pathRequest")) .withCookies( cookie(not("requestCookieNameOne"), not("requestCookieValueOne")), cookie("requestCookieNameTwo", "requestCookieValueTwo") ) ) .respond( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withReasonPhrase(HttpStatusCode.ACCEPTED_202.reasonPhrase()) .withBody("some_body_response") ); // then // wrong query string parameter name assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()) .withReasonPhrase(HttpStatusCode.NOT_FOUND_404.reasonPhrase()), makeRequest( request() .withMethod("GET") .withPath(calculatePath("some_pathRequest")) .withCookies( cookie("requestCookieNameOne", "requestCookieValueOne"), cookie("requestCookieNameTwo", "requestCookieValueTwo") ), headersToIgnore) ); // wrong query string parameter name assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()) .withReasonPhrase(HttpStatusCode.NOT_FOUND_404.reasonPhrase()), makeRequest( request() .withMethod("GET") .withPath(calculatePath("some_pathRequest")) .withCookies( cookie("requestCookieNameOne", "requestCookieValueOne"), cookie("requestCookieNameTwo", "requestCookieValueTwo") ), headersToIgnore) ); } @Test public void shouldNotReturnResponseForNonMatchingHeaderName() { // when mockServerClient .when( request() .withMethod("GET") .withPath(calculatePath("some_path")) .withQueryStringParameters( param("queryStringParameterOneName", "queryStringParameterOneValue"), param("queryStringParameterTwoName", "queryStringParameterTwoValue") ) .withBody(exact("some_body")) .withHeaders(header("headerName", "headerValue")) .withCookies(cookie("cookieName", "cookieValue")) ) .respond( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withReasonPhrase(HttpStatusCode.ACCEPTED_202.reasonPhrase()) .withBody("some_body") .withHeaders(header("headerName", "headerValue")) .withCookies(cookie("cookieName", "cookieValue")) ); // then // - in http assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()) .withReasonPhrase(HttpStatusCode.NOT_FOUND_404.reasonPhrase()), makeRequest( request() .withMethod("GET") .withPath(calculatePath("some_path")) .withQueryStringParameters( param("queryStringParameterOneName", "queryStringParameterOneValue"), param("queryStringParameterTwoName", "queryStringParameterTwoValue") ) .withBody(exact("some_body")) .withHeaders(header("headerOtherName", "headerValue")) .withCookies(cookie("cookieName", "cookieValue")), headersToIgnore) ); // - in https assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()) .withReasonPhrase(HttpStatusCode.NOT_FOUND_404.reasonPhrase()), makeRequest( request() .withMethod("GET") .withSecure(true) .withPath(calculatePath("some_path")) .withQueryStringParameters( param("queryStringParameterOneName", "queryStringParameterOneValue"), param("queryStringParameterTwoName", "queryStringParameterTwoValue") ) .withBody(exact("some_body")) .withHeaders(header("headerOtherName", "headerValue")) .withCookies(cookie("cookieName", "cookieValue")), headersToIgnore) ); } @Test public void shouldNotReturnResponseForNonMatchingHeaderValue() { // when mockServerClient .when( request() .withMethod("GET") .withPath(calculatePath("some_path")) .withQueryStringParameters( param("queryStringParameterOneName", "queryStringParameterOneValue"), param("queryStringParameterTwoName", "queryStringParameterTwoValue") ) .withBody(exact("some_body")) .withHeaders(header("headerName", "headerValue")) .withCookies(cookie("cookieName", "cookieValue")) ) .respond( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withReasonPhrase(HttpStatusCode.ACCEPTED_202.reasonPhrase()) .withBody("some_body") .withHeaders(header("headerName", "headerValue")) .withCookies(cookie("cookieName", "cookieValue")) ); // then // - in http assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()) .withReasonPhrase(HttpStatusCode.NOT_FOUND_404.reasonPhrase()), makeRequest( request() .withMethod("GET") .withPath(calculatePath("some_path")) .withQueryStringParameters( param("queryStringParameterOneName", "queryStringParameterOneValue"), param("queryStringParameterTwoName", "queryStringParameterTwoValue") ) .withBody(exact("some_body")) .withHeaders(header("headerName", "headerOtherValue")) .withCookies(cookie("cookieName", "cookieValue")), headersToIgnore) ); // - in https assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()) .withReasonPhrase(HttpStatusCode.NOT_FOUND_404.reasonPhrase()), makeRequest( request() .withMethod("GET") .withSecure(true) .withPath(calculatePath("some_path")) .withQueryStringParameters( param("queryStringParameterOneName", "queryStringParameterOneValue"), param("queryStringParameterTwoName", "queryStringParameterTwoValue") ) .withBody(exact("some_body")) .withHeaders(header("headerName", "headerOtherValue")) .withCookies(cookie("cookieName", "cookieValue")), headersToIgnore) ); } @Test public void shouldNotReturnResponseForMatchingHeaderWithNotOperator() { // when mockServerClient .when( request() .withMethod("GET") .withPath(calculatePath("some_pathRequest")) .withHeaders( header(not("requestHeaderNameOne"), not("requestHeaderValueOne")), header("requestHeaderNameTwo", "requestHeaderValueTwo") ) ) .respond( response() .withStatusCode(HttpStatusCode.ACCEPTED_202.code()) .withReasonPhrase(HttpStatusCode.ACCEPTED_202.reasonPhrase()) .withBody("some_body_response") ); // then // wrong query string parameter name assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()) .withReasonPhrase(HttpStatusCode.NOT_FOUND_404.reasonPhrase()), makeRequest( request() .withMethod("GET") .withPath(calculatePath("some_pathRequest")) .withHeaders( header("requestHeaderNameOne", "requestHeaderValueOne"), header("requestHeaderNameTwo", "requestHeaderValueTwo") ), headersToIgnore) ); // wrong query string parameter name assertEquals( response() .withStatusCode(HttpStatusCode.NOT_FOUND_404.code()) .withReasonPhrase(HttpStatusCode.NOT_FOUND_404.reasonPhrase()), makeRequest( request() .withMethod("GET") .withPath(calculatePath("some_pathRequest")) .withHeaders( header("requestHeaderNameOne", "requestHeaderValueOne"), header("requestHeaderNameTwo", "requestHeaderValueTwo") ), headersToIgnore) ); } @Test public void shouldVerifyReceivedRequestInSsl() { // when mockServerClient .when( request() .withPath(calculatePath("some.*path")), exactly(2) ) .respond( response() .withBody("some_body") ); // then // - in http assertEquals( response() .withStatusCode(OK_200.code()) .withReasonPhrase(OK_200.reasonPhrase()) .withBody("some_body"), makeRequest( request() .withPath(calculatePath("some_path")), headersToIgnore) ); mockServerClient.verify(request() .withPath(calculatePath("some_path")) .withSecure(false)); mockServerClient.verify(request() .withPath(calculatePath("some_path")) .withSecure(false), VerificationTimes.exactly(1)); // - in https assertEquals( response() .withStatusCode(OK_200.code()) .withReasonPhrase(OK_200.reasonPhrase()) .withBody("some_body"), makeRequest( request() .withPath(calculatePath("some_secure_path")) .withSecure(true), headersToIgnore) ); mockServerClient.verify(request() .withPath(calculatePath("some_secure_path")) .withSecure(true)); mockServerClient.verify(request() .withPath(calculatePath("some_secure_path")) .withSecure(true), VerificationTimes.exactly(1)); } @Test public void shouldVerifyReceivedRequestsWithRegexBody() { // when mockServerClient .when( request() .withMethod("POST") .withPath(calculatePath("some_path")) .withBody("{type: 'some_random_type', value: 'some_random_value'}"), exactly(2) ) .respond( response() .withBody("some_response") ); // then // - in http assertEquals( response() .withStatusCode(OK_200.code()) .withReasonPhrase(OK_200.reasonPhrase()) .withBody("some_response"), makeRequest( request() .withMethod("POST") .withPath(calculatePath("some_path")) .withBody("{type: 'some_random_type', value: 'some_random_value'}"), headersToIgnore) ); mockServerClient.verify( request() .withBody(regex("\\{type\\: \\'some_random_type\\'\\, value\\: \\'some_random_value\\'\\}")) ); mockServerClient.verify( request() .withBody(regex("\\{type\\: \\'some_random_type\\'\\, value\\: \\'some_random_value\\'\\}")), VerificationTimes.exactly(1) ); // - in https assertEquals( response() .withStatusCode(OK_200.code()) .withReasonPhrase(OK_200.reasonPhrase()) .withBody("some_response"), makeRequest( request() .withSecure(true) .withMethod("POST") .withPath(calculatePath("some_path")) .withBody("{type: 'some_random_type', value: 'some_random_value'}"), headersToIgnore) ); mockServerClient.verify( request() .withSecure(true) .withBody(regex("\\{type\\: \\'some_random_type\\'\\, value\\: \\'some_random_value\\'\\}")) ); mockServerClient.verify( request() .withSecure(true) .withBody(regex("\\{type\\: \\'some_random_type\\'\\, value\\: \\'some_random_value\\'\\}")), VerificationTimes.atLeast(1) ); } @Test public void shouldVerifyReceivedRequestsWithNoBody() { // when mockServerClient.when(request().withPath(calculatePath("some_path")), exactly(2)).respond(response()); // then // - in http assertEquals( response() .withStatusCode(OK_200.code()) .withReasonPhrase(OK_200.reasonPhrase()), makeRequest( request() .withPath(calculatePath("some_path")), headersToIgnore) ); mockServerClient.verify(request() .withPath(calculatePath("some_path"))); mockServerClient.verify(request() .withPath(calculatePath("some_path")), VerificationTimes.exactly(1)); } @Test public void shouldVerifyTooManyRequestsReceived() { // when mockServerClient.when(request().withPath(calculatePath("some_path")), exactly(2)).respond(response().withBody("some_body")); // then assertEquals( response() .withStatusCode(OK_200.code()) .withReasonPhrase(OK_200.reasonPhrase()) .withBody("some_body"), makeRequest( request() .withPath(calculatePath("some_path")), headersToIgnore) ); try { mockServerClient.verify(request() .withPath(calculatePath("some_path")), VerificationTimes.exactly(0)); fail(); } catch (AssertionError ae) { assertThat(ae.getMessage(), startsWith("Request not found exactly 0 times, expected:<{" + NEW_LINE + " \"path\" : \"" + calculatePath("some_path") + "\"" + NEW_LINE + "}> but was:<{" + NEW_LINE + " \"method\" : \"GET\"," + NEW_LINE + " \"path\" : \"" + calculatePath("some_path") + "\"," + NEW_LINE)); } } @Test public void shouldVerifyNoMatchingRequestsReceived() { // when mockServerClient.when(request().withPath(calculatePath("some_path")), exactly(2)).respond(response().withBody("some_body")); // then assertEquals( response() .withStatusCode(OK_200.code()) .withReasonPhrase(OK_200.reasonPhrase()) .withBody("some_body"), makeRequest( request() .withPath(calculatePath("some_path")), headersToIgnore) ); try { mockServerClient.verify(request() .withPath(calculatePath("some_other_path")), VerificationTimes.exactly(2)); fail(); } catch (AssertionError ae) { assertThat(ae.getMessage(), startsWith("Request not found exactly 2 times, expected:<{" + NEW_LINE + " \"path\" : \"" + calculatePath("some_other_path") + "\"" + NEW_LINE + "}> but was:<{" + NEW_LINE + " \"method\" : \"GET\"," + NEW_LINE + " \"path\" : \"" + calculatePath("some_path") + "\"," + NEW_LINE)); } } @Test public void shouldNotVerifyNoRequestsReceived() { // when mockServerClient.when(request().withPath(calculatePath("some_path")), exactly(2)).respond(response().withBody("some_body")); // then assertEquals( response() .withStatusCode(OK_200.code()) .withReasonPhrase(OK_200.reasonPhrase()) .withBody("some_body"), makeRequest( request() .withPath(calculatePath("some_path")), headersToIgnore) ); try { mockServerClient.verifyZeroInteractions(); fail(); } catch (AssertionError ae) { assertThat(ae.getMessage(), startsWith("Request not found exactly 0 times, expected:<{ }> but was:<{" + NEW_LINE + " \"method\" : \"GET\"," + NEW_LINE + " \"path\" : \"" + calculatePath("some_path") + "\"," + NEW_LINE)); } } @Test public void shouldVerifyNoMatchingRequestsReceivedInSsl() { // when mockServerClient.when(request().withPath(calculatePath("some.*path")), exactly(2)).respond(response().withBody("some_body")); // then // - in http assertEquals( response() .withStatusCode(OK_200.code()) .withReasonPhrase(OK_200.reasonPhrase()) .withBody("some_body"), makeRequest( request() .withPath(calculatePath("some_path")), headersToIgnore) ); try { mockServerClient.verify( request() .withPath(calculatePath("some_path")) .withSecure(true), VerificationTimes.atLeast(1) ); fail(); } catch (AssertionError ae) { assertThat(ae.getMessage(), startsWith("Request not found at least once, expected:<{" + NEW_LINE + " \"path\" : \"" + calculatePath("some_path") + "\"," + NEW_LINE + " \"secure\" : true" + NEW_LINE + "}> but was:<{" + NEW_LINE + " \"method\" : \"GET\"," + NEW_LINE + " \"path\" : \"" + calculatePath("some_path") + "\"," + NEW_LINE)); } // - in https assertEquals( response() .withStatusCode(OK_200.code()) .withReasonPhrase(OK_200.reasonPhrase()) .withBody("some_body"), makeRequest( request() .withPath(calculatePath("some_secure_path")) .withSecure(true), headersToIgnore) ); try { mockServerClient.verify( request() .withPath(calculatePath("some_secure_path")) .withSecure(false), VerificationTimes.atLeast(1) ); fail(); } catch (AssertionError ae) { assertThat(ae.getMessage(), startsWith("Request not found at least once, expected:<{" + NEW_LINE + " \"path\" : \"" + calculatePath("some_secure_path") + "\"," + NEW_LINE + " \"secure\" : false" + NEW_LINE + "}> but was:<[ {" + NEW_LINE + " \"method\" : \"GET\"," + NEW_LINE + " \"path\" : \"" + calculatePath("some_path") + "\"," + NEW_LINE)); } } @Test public void shouldVerifySequenceOfRequestsReceivedIncludingThoseNotMatchingAnException() { // when mockServerClient.when(request().withPath(calculatePath("some_path.*")), exactly(4)).respond(response().withBody("some_body")); // then assertEquals( response("some_body"), makeRequest( request().withPath(calculatePath("some_path_one")), headersToIgnore) ); assertEquals( notFoundResponse(), makeRequest( request().withPath(calculatePath("not_found")), headersToIgnore) ); assertEquals( response("some_body"), makeRequest( request().withPath(calculatePath("some_path_three")), headersToIgnore) ); mockServerClient.verify(request(calculatePath("some_path_one")), request(calculatePath("some_path_three"))); mockServerClient.verify(request(calculatePath("some_path_one")), request(calculatePath("not_found"))); mockServerClient.verify(request(calculatePath("some_path_one")), request(calculatePath("not_found")), request(calculatePath("some_path_three"))); mockServerClient.verify(request(calculatePath("some_path_one")), request(calculatePath("not_found")), request(calculatePath("some_path_three"))); } @Test public void shouldVerifySequenceOfRequestsNotReceived() { // when mockServerClient.when(request().withPath(calculatePath("some_path.*")), exactly(6)).respond(response().withBody("some_body")); // then assertEquals( response("some_body"), makeRequest( request().withPath(calculatePath("some_path_one")), headersToIgnore) ); assertEquals( response("some_body"), makeRequest( request().withPath(calculatePath("some_path_two")), headersToIgnore) ); assertEquals( response("some_body"), makeRequest( request().withPath(calculatePath("some_path_three")), headersToIgnore) ); try { mockServerClient.verify(request(calculatePath("some_path_two")), request(calculatePath("some_path_one"))); fail(); } catch (AssertionError ae) { assertThat(ae.getMessage(), startsWith("Request sequence not found, expected:<[ {" + NEW_LINE + " \"path\" : \"" + calculatePath("some_path_two") + "\"" + NEW_LINE + "}, {" + NEW_LINE + " \"path\" : \"" + calculatePath("some_path_one") + "\"" + NEW_LINE + "} ]> but was:<[ {" + NEW_LINE + " \"method\" : \"GET\"," + NEW_LINE + " \"path\" : \"" + calculatePath("some_path_one") + "\"," + NEW_LINE)); } try { mockServerClient.verify(request(calculatePath("some_path_three")), request(calculatePath("some_path_two"))); fail(); } catch (AssertionError ae) { assertThat(ae.getMessage(), startsWith("Request sequence not found, expected:<[ {" + NEW_LINE + " \"path\" : \"" + calculatePath("some_path_three") + "\"" + NEW_LINE + "}, {" + NEW_LINE + " \"path\" : \"" + calculatePath("some_path_two") + "\"" + NEW_LINE + "} ]> but was:<[ {" + NEW_LINE + " \"method\" : \"GET\"," + NEW_LINE + " \"path\" : \"" + calculatePath("some_path_one") + "\"," + NEW_LINE)); } try { mockServerClient.verify(request(calculatePath("some_path_four"))); fail(); } catch (AssertionError ae) { assertThat(ae.getMessage(), startsWith("Request sequence not found, expected:<[ {" + NEW_LINE + " \"path\" : \"" + calculatePath("some_path_four") + "\"" + NEW_LINE + "} ]> but was:<[ {" + NEW_LINE + " \"method\" : \"GET\"," + NEW_LINE + " \"path\" : \"" + calculatePath("some_path_one") + "\"," + NEW_LINE)); } } @Test public void shouldRetrieveRecordedRequestsAsJson() { // when mockServerClient.when(request().withPath(calculatePath("some_path.*")), exactly(4)).respond(response().withBody("some_body")); assertEquals( response("some_body"), makeRequest( request().withPath(calculatePath("some_path_one")), headersToIgnore) ); assertEquals( notFoundResponse(), makeRequest( request().withPath(calculatePath("not_found")), headersToIgnore) ); assertEquals( response("some_body"), makeRequest( request().withPath(calculatePath("some_path_three")), headersToIgnore) ); // then verifyRequestsMatches( new HttpRequestSerializer(new MockServerLogger()).deserializeArray(mockServerClient.retrieveRecordedRequests(request().withPath(calculatePath("some_path.*")), Format.JSON)), request(calculatePath("some_path_one")), request(calculatePath("some_path_three")) ); verifyRequestsMatches( new HttpRequestSerializer(new MockServerLogger()).deserializeArray(mockServerClient.retrieveRecordedRequests(request(), Format.JSON)), request(calculatePath("some_path_one")), request(calculatePath("not_found")), request(calculatePath("some_path_three")) ); verifyRequestsMatches( new HttpRequestSerializer(new MockServerLogger()).deserializeArray(mockServerClient.retrieveRecordedRequests(null, Format.JSON)), request(calculatePath("some_path_one")), request(calculatePath("not_found")), request(calculatePath("some_path_three")) ); } @Test public void shouldRetrieveActiveExpectationsAsJson() { // when mockServerClient.when(request().withPath(calculatePath("some_path.*")), exactly(4)) .respond(response().withBody("some_body")); mockServerClient.when(request().withPath(calculatePath("some_path.*"))) .respond(response().withBody("some_body")); mockServerClient.when(request().withPath(calculatePath("some_other_path"))) .respond(response().withBody("some_other_body")); mockServerClient.when(request().withPath(calculatePath("some_forward_path"))) .forward(forward()); // then assertThat( mockServerClient.retrieveActiveExpectations(request().withPath(calculatePath("some_path.*")), Format.JSON), is(new ExpectationSerializer(new MockServerLogger()).serialize(Arrays.asList( new Expectation(request().withPath(calculatePath("some_path.*")), exactly(4), TimeToLive.unlimited()) .thenRespond(response().withBody("some_body")), new Expectation(request().withPath(calculatePath("some_path.*"))) .thenRespond(response().withBody("some_body")) ))) ); assertThat( mockServerClient.retrieveActiveExpectations(null, Format.JSON), is(new ExpectationSerializer(new MockServerLogger()).serialize(Arrays.asList( new Expectation(request().withPath(calculatePath("some_path.*")), exactly(4), TimeToLive.unlimited()) .thenRespond(response().withBody("some_body")), new Expectation(request().withPath(calculatePath("some_path.*"))) .thenRespond(response().withBody("some_body")), new Expectation(request().withPath(calculatePath("some_other_path"))) .thenRespond(response().withBody("some_other_body")), new Expectation(request().withPath(calculatePath("some_forward_path"))) .thenForward(forward()) ))) ); assertThat( mockServerClient.retrieveActiveExpectations(request(), Format.JSON), is(new ExpectationSerializer(new MockServerLogger()).serialize(Arrays.asList( new Expectation(request().withPath(calculatePath("some_path.*")), exactly(4), TimeToLive.unlimited()) .thenRespond(response().withBody("some_body")), new Expectation(request().withPath(calculatePath("some_path.*"))) .thenRespond(response().withBody("some_body")), new Expectation(request().withPath(calculatePath("some_other_path"))) .thenRespond(response().withBody("some_other_body")), new Expectation(request().withPath(calculatePath("some_forward_path"))) .thenForward(forward()) ))) ); } @Test public void shouldRetrieveActiveExpectationsAsJava() { // when mockServerClient.when(request().withPath(calculatePath("some_path.*")), exactly(4)) .respond(response().withBody("some_body")); mockServerClient.when(request().withPath(calculatePath("some_path.*"))) .respond(response().withBody("some_body")); mockServerClient.when(request().withPath(calculatePath("some_other_path"))) .respond(response().withBody("some_other_body")); mockServerClient.when(request().withPath(calculatePath("some_forward_path"))) .forward(forward()); // then assertThat( mockServerClient.retrieveActiveExpectations(request().withPath(calculatePath("some_path.*")), Format.JAVA), is(new ExpectationToJavaSerializer().serialize(Arrays.asList( new Expectation(request().withPath(calculatePath("some_path.*")), exactly(4), TimeToLive.unlimited()) .thenRespond(response().withBody("some_body")), new Expectation(request().withPath(calculatePath("some_path.*"))) .thenRespond(response().withBody("some_body")) ))) ); assertThat( mockServerClient.retrieveActiveExpectations(null, Format.JAVA), is(new ExpectationToJavaSerializer().serialize(Arrays.asList( new Expectation(request().withPath(calculatePath("some_path.*")), exactly(4), TimeToLive.unlimited()) .thenRespond(response().withBody("some_body")), new Expectation(request().withPath(calculatePath("some_path.*"))) .thenRespond(response().withBody("some_body")), new Expectation(request().withPath(calculatePath("some_other_path"))) .thenRespond(response().withBody("some_other_body")), new Expectation(request().withPath(calculatePath("some_forward_path"))) .thenForward(forward()) ))) ); assertThat( mockServerClient.retrieveActiveExpectations(request(), Format.JAVA), is(new ExpectationToJavaSerializer().serialize(Arrays.asList( new Expectation(request().withPath(calculatePath("some_path.*")), exactly(4), TimeToLive.unlimited()) .thenRespond(response().withBody("some_body")), new Expectation(request().withPath(calculatePath("some_path.*"))) .thenRespond(response().withBody("some_body")), new Expectation(request().withPath(calculatePath("some_other_path"))) .thenRespond(response().withBody("some_other_body")), new Expectation(request().withPath(calculatePath("some_forward_path"))) .thenForward(forward()) ))) ); } @Test public void shouldRetrieveRecordedExpectationsAsJson() { // when EchoServer secureEchoServer = new EchoServer(false); try { mockServerClient.when(request().withPath(calculatePath("some_path.*")), exactly(4)).forward( forward() .withHost("127.0.0.1") .withPort(secureEchoServer.getPort()) ); assertEquals( response("some_body_one"), makeRequest( request().withPath(calculatePath("some_path_one")).withBody("some_body_one"), headersToIgnore ) ); assertEquals( response("some_body_three"), makeRequest( request().withPath(calculatePath("some_path_three")).withBody("some_body_three"), headersToIgnore ) ); // then Expectation[] recordedExpectations = new ExpectationSerializer(new MockServerLogger()).deserializeArray( mockServerClient.retrieveRecordedExpectations(request().withPath(calculatePath("some_path_one")), Format.JSON) ); assertThat(recordedExpectations.length, is(1)); verifyRequestsMatches( new HttpRequest[]{ recordedExpectations[0].getHttpRequest() }, request(calculatePath("some_path_one")).withBody("some_body_one") ); assertThat(recordedExpectations[0].getHttpResponse().getBodyAsString(), is("some_body_one")); // and recordedExpectations = new ExpectationSerializer(new MockServerLogger()).deserializeArray( mockServerClient.retrieveRecordedExpectations(request(), Format.JSON) ); assertThat(recordedExpectations.length, is(2)); verifyRequestsMatches( new HttpRequest[]{ recordedExpectations[0].getHttpRequest(), recordedExpectations[1].getHttpRequest() }, request(calculatePath("some_path_one")).withBody("some_body_one"), request(calculatePath("some_path_three")).withBody("some_body_three") ); assertThat(recordedExpectations[0].getHttpResponse().getBodyAsString(), is("some_body_one")); assertThat(recordedExpectations[1].getHttpResponse().getBodyAsString(), is("some_body_three")); // and recordedExpectations = new ExpectationSerializer(new MockServerLogger()).deserializeArray( mockServerClient.retrieveRecordedExpectations(null, Format.JSON) ); assertThat(recordedExpectations.length, is(2)); verifyRequestsMatches( new HttpRequest[]{ recordedExpectations[0].getHttpRequest(), recordedExpectations[1].getHttpRequest() }, request(calculatePath("some_path_one")).withBody("some_body_one"), request(calculatePath("some_path_three")).withBody("some_body_three") ); assertThat(recordedExpectations[0].getHttpResponse().getBodyAsString(), is("some_body_one")); assertThat(recordedExpectations[1].getHttpResponse().getBodyAsString(), is("some_body_three")); } finally { secureEchoServer.stop(); } } @Test public void shouldClearExpectationsOnly() { // given - some expectations mockServerClient .when( request() .withPath(calculatePath("some_path1")) ) .respond( response() .withBody("some_body1") ); mockServerClient .when( request() .withPath(calculatePath("some_path2")) ) .respond( response() .withBody("some_body2") ); // and - some matching requests assertEquals( response() .withStatusCode(OK_200.code()) .withReasonPhrase(OK_200.reasonPhrase()) .withBody("some_body1"), makeRequest( request() .withPath(calculatePath("some_path1")), headersToIgnore) ); assertEquals( response() .withStatusCode(OK_200.code()) .withReasonPhrase(OK_200.reasonPhrase()) .withBody("some_body2"), makeRequest( request() .withPath(calculatePath("some_path2")), headersToIgnore) ); // when mockServerClient .clear( request() .withPath(calculatePath("some_path1")), ClearType.EXPECTATIONS ); // then - expectations cleared assertThat( mockServerClient.retrieveActiveExpectations(null), arrayContaining( new Expectation(request() .withPath(calculatePath("some_path2"))) .thenRespond( response() .withBody("some_body2") ) ) ); // and then - request log not cleared verifyRequestsMatches( mockServerClient.retrieveRecordedRequests(null), request(calculatePath("some_path1")), request(calculatePath("some_path2")) ); } @Test public void shouldClearLogsOnly() { // given - some expectations mockServerClient .when( request() .withPath(calculatePath("some_path1")) ) .respond( response() .withBody("some_body1") ); mockServerClient .when( request() .withPath(calculatePath("some_path2")) ) .respond( response() .withBody("some_body2") ); // and - some matching requests assertEquals( response() .withStatusCode(OK_200.code()) .withReasonPhrase(OK_200.reasonPhrase()) .withBody("some_body1"), makeRequest( request() .withPath(calculatePath("some_path1")), headersToIgnore) ); assertEquals( response() .withStatusCode(OK_200.code()) .withReasonPhrase(OK_200.reasonPhrase()) .withBody("some_body2"), makeRequest( request() .withPath(calculatePath("some_path2")), headersToIgnore) ); // when mockServerClient .clear( request() .withPath(calculatePath("some_path1")), ClearType.LOG ); // then - expectations cleared assertThat( mockServerClient.retrieveActiveExpectations(null), arrayContaining( new Expectation(request() .withPath(calculatePath("some_path1"))) .thenRespond( response() .withBody("some_body1") ), new Expectation(request() .withPath(calculatePath("some_path2"))) .thenRespond( response() .withBody("some_body2") ) ) ); // and then - request log cleared verifyRequestsMatches( mockServerClient.retrieveRecordedRequests(null), request(calculatePath("some_path2")) ); } @Test public void shouldClearAllExpectationsWithNull() { // given mockServerClient .when( request() .withPath(calculatePath("some_path1")) ) .respond( response() .withBody("some_body1") ); mockServerClient .when( request() .withPath(calculatePath("some_path2")) ) .respond( response() .withBody("some_body2") ); assertEquals( response() .withStatusCode(OK_200.code()) .withReasonPhrase(OK_200.reasonPhrase()) .withBody("some_body2"), makeRequest( request() .withPath(calculatePath("some_path2")), headersToIgnore) ); // when mockServerClient.clear(null); // then assertThat(mockServerClient.retrieveActiveExpectations(null), emptyArray()); assertThat(mockServerClient.retrieveRecordedRequests(null), emptyArray()); } @Test public void shouldClearAllExpectationsWithEmptyRequest() { // given mockServerClient .when( request() .withPath(calculatePath("some_path1")) ) .respond( response() .withBody("some_body1") ); mockServerClient .when( request() .withPath(calculatePath("some_path2")) ) .respond( response() .withBody("some_body2") ); assertEquals( response() .withStatusCode(OK_200.code()) .withReasonPhrase(OK_200.reasonPhrase()) .withBody("some_body2"), makeRequest( request() .withPath(calculatePath("some_path2")), headersToIgnore) ); // when mockServerClient.clear(request()); // then assertThat(mockServerClient.retrieveActiveExpectations(null), emptyArray()); assertThat(mockServerClient.retrieveRecordedRequests(null), emptyArray()); } @Test public void shouldClearExpectationsWithXPathBody() { // given mockServerClient .when( request() .withBody(xpath("/bookstore/book[year=2005]/price")) ) .respond( response() .withBody("some_body1") ); mockServerClient .when( request() .withBody(xpath("/bookstore/book[year=2006]/price")) ) .respond( response() .withBody("some_body2") ); // and StringBody xmlBody = new StringBody("" + "<?xml version=\"1.0\" encoding=\"ISO-8859-1\"?>" + NEW_LINE + "<bookstore>" + NEW_LINE + " <book category=\"COOKING\">" + NEW_LINE + " <title lang=\"en\">Everyday Italian</title>" + NEW_LINE + " <author>Giada De Laurentiis</author>" + NEW_LINE + " <year>2005</year>" + NEW_LINE + " <price>30.00</price>" + NEW_LINE + " </book>" + NEW_LINE + " <book category=\"CHILDREN\">" + NEW_LINE + " <title lang=\"en\">Harry Potter</title>" + NEW_LINE + " <author>J K. Rowling</author>" + NEW_LINE + " <year>2006</year>" + NEW_LINE + " <price>29.99</price>" + NEW_LINE + " </book>" + NEW_LINE + " <book category=\"WEB\">" + NEW_LINE + " <title lang=\"en\">Learning XML</title>" + NEW_LINE + " <author>Erik T. Ray</author>" + NEW_LINE + " <year>2003</year>" + NEW_LINE + " <price>31.95</price>" + NEW_LINE + " </book>" + NEW_LINE + "</bookstore>"); // then assertEquals( response() .withStatusCode(OK_200.code()) .withReasonPhrase(OK_200.reasonPhrase()) .withBody("some_body1"), makeRequest( request() .withBody(xmlBody), headersToIgnore) ); // when mockServerClient .clear( request() .withBody(xpath("/bookstore/book[year=2005]/price")) ); // then assertThat( mockServerClient.retrieveActiveExpectations(null), arrayContaining( new Expectation(request() .withBody(xpath("/bookstore/book[year=2006]/price"))) .thenRespond( response() .withBody("some_body2") ) ) ); // - in http assertEquals( response() .withStatusCode(OK_200.code()) .withReasonPhrase(OK_200.reasonPhrase()) .withBody("some_body2"), makeRequest( request() .withBody(xmlBody), headersToIgnore) ); // - in https assertEquals( response() .withStatusCode(OK_200.code()) .withReasonPhrase(OK_200.reasonPhrase()) .withBody("some_body2"), makeRequest( request() .withSecure(true) .withBody(xmlBody), headersToIgnore) ); } @Test public void shouldClearExpectationsWithJsonSchemaBody() { // given JsonSchemaBody jsonSchemaBodyOne = jsonSchema("{" + NEW_LINE + " \"$schema\": \"http://json-schema.org/draft-04/schema#\"," + NEW_LINE + " \"title\": \"Product\"," + NEW_LINE + " \"description\": \"A product from Acme's catalog\"," + NEW_LINE + " \"type\": \"object\"," + NEW_LINE + " \"properties\": {" + NEW_LINE + " \"id\": {" + NEW_LINE + " \"description\": \"The unique identifier for a product\"," + NEW_LINE + " \"type\": \"integer\"" + NEW_LINE + " }," + NEW_LINE + " \"name\": {" + NEW_LINE + " \"description\": \"Name of the product\"," + NEW_LINE + " \"type\": \"string\"" + NEW_LINE + " }," + NEW_LINE + " \"price\": {" + NEW_LINE + " \"type\": \"number\"," + NEW_LINE + " \"minimum\": 0," + NEW_LINE + " \"exclusiveMinimum\": true" + NEW_LINE + " }," + NEW_LINE + " \"tags\": {" + NEW_LINE + " \"type\": \"array\"," + NEW_LINE + " \"items\": {" + NEW_LINE + " \"type\": \"string\"" + NEW_LINE + " }," + NEW_LINE + " \"minItems\": 1," + NEW_LINE + " \"uniqueItems\": true" + NEW_LINE + " }" + NEW_LINE + " }," + NEW_LINE + " \"required\": [\"id\", \"name\", \"price\"]" + NEW_LINE + "}"); JsonSchemaBody jsonSchemaBodyTwo = jsonSchema("{" + NEW_LINE + " \"$schema\": \"http://json-schema.org/draft-04/schema#\"," + NEW_LINE + " \"title\": \"Product\"," + NEW_LINE + " \"description\": \"A product from Acme's catalog\"," + NEW_LINE + " \"type\": \"object\"," + NEW_LINE + " \"properties\": {" + NEW_LINE + " \"id\": {" + NEW_LINE + " \"description\": \"The unique identifier for a product\"," + NEW_LINE + " \"type\": \"integer\"" + NEW_LINE + " }," + NEW_LINE + " \"name\": {" + NEW_LINE + " \"description\": \"Name of the product\"," + NEW_LINE + " \"type\": \"string\"" + NEW_LINE + " }," + NEW_LINE + " \"price\": {" + NEW_LINE + " \"type\": \"number\"," + NEW_LINE + " \"minimum\": 10," + NEW_LINE + " \"exclusiveMinimum\": true" + NEW_LINE + " }," + NEW_LINE + " \"tags\": {" + NEW_LINE + " \"type\": \"array\"," + NEW_LINE + " \"items\": {" + NEW_LINE + " \"type\": \"string\"" + NEW_LINE + " }," + NEW_LINE + " \"minItems\": 1," + NEW_LINE + " \"uniqueItems\": true" + NEW_LINE + " }" + NEW_LINE + " }," + NEW_LINE + " \"required\": [\"id\", \"name\", \"price\"]" + NEW_LINE + "}"); mockServerClient .when( request() .withBody(jsonSchemaBodyOne) ) .respond( response() .withBody("some_body1") ); mockServerClient .when( request() .withBody(jsonSchemaBodyTwo) ) .respond( response() .withBody("some_body2") ); // then assertEquals( response() .withStatusCode(OK_200.code()) .withReasonPhrase(OK_200.reasonPhrase()) .withBody("some_body1"), makeRequest( request() .withBody("{" + NEW_LINE + " \"id\": 1," + NEW_LINE + " \"name\": \"A green door\"," + NEW_LINE + " \"price\": 12.50," + NEW_LINE + " \"tags\": [\"home\", \"green\"]" + NEW_LINE + "}"), headersToIgnore) ); // when mockServerClient .clear( request() .withBody(jsonSchemaBodyOne) ); // then assertThat( mockServerClient.retrieveActiveExpectations(null), arrayContaining( new Expectation(request() .withBody(jsonSchemaBodyTwo)) .thenRespond( response() .withBody("some_body2") ) ) ); // - in http assertEquals( response() .withStatusCode(OK_200.code()) .withReasonPhrase(OK_200.reasonPhrase()) .withBody("some_body2"), makeRequest( request() .withBody("{" + NEW_LINE + " \"id\": 1," + NEW_LINE + " \"name\": \"A green door\"," + NEW_LINE + " \"price\": 12.50," + NEW_LINE + " \"tags\": [\"home\", \"green\"]" + NEW_LINE + "}"), headersToIgnore) ); // - in https assertEquals( response() .withStatusCode(OK_200.code()) .withReasonPhrase(OK_200.reasonPhrase()) .withBody("some_body2"), makeRequest( request() .withSecure(true) .withBody("{" + NEW_LINE + " \"id\": 1," + NEW_LINE + " \"name\": \"A green door\"," + NEW_LINE + " \"price\": 12.50," + NEW_LINE + " \"tags\": [\"home\", \"green\"]" + NEW_LINE + "}"), headersToIgnore) ); } @Test public void shouldClearExpectationsWithParameterBody() { // given mockServerClient .when( request() .withBody(params(param("bodyParameterNameOne", "bodyParameterValueOne"))) ) .respond( response() .withBody("some_body1") ); mockServerClient .when( request() .withBody(params(param("bodyParameterNameTwo", "bodyParameterValueTwo"))) ) .respond( response() .withBody("some_body2") ); // then assertEquals( response() .withStatusCode(OK_200.code()) .withReasonPhrase(OK_200.reasonPhrase()) .withBody("some_body1"), makeRequest( request() .withBody(params(param("bodyParameterName.*", "bodyParameterValue.*"))), headersToIgnore) ); // when mockServerClient .clear( request() .withBody(params(param("bodyParameterNameOne", "bodyParameterValueOne"))) ); // then assertThat( mockServerClient.retrieveActiveExpectations(null), arrayContaining( new Expectation(request() .withBody(params(param("bodyParameterNameTwo", "bodyParameterValueTwo")))) .thenRespond( response() .withBody("some_body2") ) ) ); // - in http assertEquals( response() .withStatusCode(OK_200.code()) .withReasonPhrase(OK_200.reasonPhrase()) .withBody("some_body2"), makeRequest( request() .withBody(params(param("bodyParameterName.*", "bodyParameterValue.*"))), headersToIgnore) ); // - in https assertEquals( response() .withStatusCode(OK_200.code()) .withReasonPhrase(OK_200.reasonPhrase()) .withBody("some_body2"), makeRequest( request() .withSecure(true) .withBody(params(param("bodyParameterName.*", "bodyParameterValue.*"))), headersToIgnore) ); } @Test public void shouldEnsureThatInterruptedRequestsAreVerifiable() throws Exception { mockServerClient .when( request(calculatePath("delayed")) ) .respond( response("delayed data") .withDelay(new Delay(TimeUnit.SECONDS, 3)) ); Future<HttpResponse> delayedFuture = Executors.newSingleThreadExecutor().submit(new Callable<HttpResponse>() { @Override public HttpResponse call() throws Exception { return httpClient.sendRequest( request(addContextToPath(calculatePath("delayed"))) .withHeader(HOST.toString(), "localhost:" + getMockServerPort()) ).get(10, TimeUnit.SECONDS); } }); Uninterruptibles.sleepUninterruptibly(1, TimeUnit.SECONDS); // Let request reach server delayedFuture.cancel(true); // Then interrupt requesting thread mockServerClient.verify(request(calculatePath("delayed"))); // We should be able to verify request that reached server even though its later interrupted } @Test public void shouldEnsureThatRequestDelaysDoNotAffectOtherRequests() throws Exception { mockServerClient .when( request("/slow") ) .respond( response("super slow") .withDelay(new Delay(TimeUnit.SECONDS, 5)) ); mockServerClient .when( request("/fast") ) .respond( response("quite fast") ); ExecutorService executorService = Executors.newFixedThreadPool(2); Future<Long> slowFuture = executorService.submit(new Callable<Long>() { @Override public Long call() throws Exception { long start = System.currentTimeMillis(); makeRequest(request("/slow"), Collections.<String>emptySet()); return System.currentTimeMillis() - start; } }); // Let fast request come to the server slightly after slow request Uninterruptibles.sleepUninterruptibly(1, TimeUnit.SECONDS); Future<Long> fastFuture = executorService.submit(new Callable<Long>() { @Override public Long call() throws Exception { long start = System.currentTimeMillis(); makeRequest(request("/fast"), Collections.<String>emptySet()); return System.currentTimeMillis() - start; } }); Long slowRequestElapsedMillis = slowFuture.get(); Long fastRequestElapsedMillis = fastFuture.get(); assertThat("Slow request takes less than expected", slowRequestElapsedMillis, is(greaterThan(5 * 1000L))); assertThat("Fast request takes longer than expected", fastRequestElapsedMillis, is(lessThan(5 * 1000L))); } }
brcolow/mockserver
mockserver-integration-testing/src/main/java/org/mockserver/integration/server/AbstractExtendedClientServerIntegrationTest.java
943
/****************************************************************************** * Τεκμηρίωση HelloWord προγράμματος * Αρχείο πηγαίου κώδικα HelloWorld.java * * Πρώτο πρόγραμμα σε Java. Εμφανίζει το κείμενο Hello, World στο τερματικό. * * Compilation: javac HelloWorld.java * Execution: java HelloWorld * ******************************************************************************/ public class HelloWorld { public static void main(String[] args) { // Prints "Hello, World" to the terminal window. System.out.println("Hello, World"); } }
riggas-ionio/java
lab-java-01/HelloWorld.java
945
package gr.aueb.cf.ch2; /** * Εμφανίζει τους τύπους δεδομένων ακεραίων (int, short, byte, long) * το μέγεθός τους (size σε bits), και το εύρος τιμών. * * @author a8ana */ public class IntApp { public static void main(String[] args) { System.out.printf("Type: %s, Size: %d bits, Min: %,d, Max: %,d\n", Integer.TYPE, Integer.SIZE, Integer.MIN_VALUE, Integer.MAX_VALUE); System.out.printf("Type: %s, Size: %d bits, Min: %d, Max: %d\n", Byte.TYPE, Byte.SIZE, Byte.MIN_VALUE, Byte.MAX_VALUE); System.out.printf("Type: %s, Size: %d bits, Min: %d, Max: %d\n", Short.TYPE, Short.SIZE, Short.MIN_VALUE, Short.MAX_VALUE); System.out.printf("Type: %s, Size: %d bits, Min: %,d, Max: %,d\n", Long.TYPE, Long.SIZE, Long.MIN_VALUE, Long.MAX_VALUE); } }
a8anassis/cf6-java
src/gr/aueb/cf/ch2/IntApp.java
946
package logic; import java.util.Set; import java.util.HashSet; /** * * Κλάση Question , η οποία επιτρέπει τη δημιουργία αντικειμένων ερωτήσεων. Στο * αντικείμενο αποθηκεύεται η ερώτηση, η σωστή και οι λανθασμένες απαντήσεις * καθώς και η κατηγορία στην οποία ανήκει. Ως default κατηγορίες ερωτήσεων * έχουν οριστεί πέντε. * * +++ Οι κλάσεις VideoQuestion , SoundQuestion και ImageQuestion κληρονομούν * από την Question +++ * * * @author tasosxak * @author Thanasis * @since 8/11/2016 * @version 1.0 * */ public class Question { private static final String[] CATEGORIES = {"SPORT", "SCIENCE", "HISTORY", "TECHNOLOGY", "OTHERS"}; public static final int ANSWERS = 4; private String question; private String correctAnswer; private String[] wrongs; private String category; private Question(String question) { this.wrongs = new String[Question.ANSWERS - 1]; this.question = question; } private Question(String question, String correct) { this(question); this.correctAnswer = correct; } private Question(String question, String category, String correct) { this(question, correct); if (Question.belongs(category)) { this.category = category.toUpperCase(); } else { this.category = "OTHERS"; //Σε περίπτωση που δεν ανήκει σε καμιά από τις υποστηριζόμενες κατηγορίες , κατάσσεται στην κατηγορία "others" } } public Question(Question question) { this(question.getQuestion(), question.getCategory(), question.getCorrect(), question.getAllWrongs()); } /** * Public Construtor * * @param question Η ερώτηση του αντικειμένου * @param category Η κατηγορία στην οποία ανήκει η ερώτηση * @param correct Η σωστή απάντηση της ερώτησης * @param wrongs Πίνακας συμβολοσειρών που περιέχει τις λανθασμένες * απαντήσεις */ public Question(String question, String category, String correct, String[] wrongs) { this(question, category, correct); /* Αντιγραφή του πίνακα των λανθασμένων απαντήσεων wrongs στον this.wrongs (πίνακα λανθασμένων απαντήσεων μιας ερώτησης)*/ System.arraycopy(wrongs, 0, this.wrongs, 0, Question.ANSWERS - 1); } /** * Ελέγχει αν η απάντηση που δίνεται ως παράμετρος είναι η σωστή απάντηση * που αντιστοιχεί στην ερώτηση * * * @param answer Αντιστοιχεί στην απάντηση που δίνει ο χρήστης * @return Επιστρέφει true αν η απάντηση είναι σωστή και false αν είναι * λάθος */ public boolean isCorrect(String answer) { return this.correctAnswer.equals(answer); } /** * Θέτει την σωστή απάντηση της ερώτησης, η σωστή απάντηση πρέπει να έχει * μήκος μεγαλύτερο του μηδενός * * @param correctAnswer Η απάντηση που θα τεθεί ως η σωστή απάντηση της * ερώτησης * @return true αν η προσθήκη έγινε επιτυχώς (όταν το μήπως της παραμέτρου * είναι μεγαλύτερο του μηδενός), διαφορετικά false */ public boolean setCorrectAnswer(String correctAnswer) { if (correctAnswer.length() != 0) { this.correctAnswer = correctAnswer; return true; } return false; } /** * * @return Επιστρέφει την ερώτηση */ public String getQuestion() { return this.question; } /** * * @return Επιστρέφει την κατηγορία που ανήκει η ερώτηση */ public String getCategory() { return this.category; } /** * * @return Επιστρέφει την σωστή απάντηση της ερώτησης */ public String getCorrect() { return this.correctAnswer; } /** * * @param index Θέση μιας λανθασμένης απάντησης στον πίνακα wrongs * @return Επιστρέφει την λανθασμένη απάντηση στη θέση index του πίνακα * wrongs */ public String getWrong(int index) { if (index < Question.ANSWERS - 1) { return this.wrongs[index]; } else { return null; } } /** * * @return Επιστρέφει έναν νέο πίνακα συμβολοσειρών με τις λανθασμένες * ερωτήσεις */ public String[] getAllWrongs() { return this.wrongs.clone(); } /** * * @return Επιστρέφει όλες τις πιθανές επιλογές (απαντήσεις) της ερώτησης σε * πίνακα συμβολοσειρών */ public String[] getAllAnswers() { String[] allAnswers = new String[Question.ANSWERS]; allAnswers[0] = this.getCorrect(); for (int i = 1; i < Question.ANSWERS; i++) { allAnswers[i] = this.getWrong(i - 1); } return allAnswers; } /** * Ελέγχει εαν μια κατηγορία που δίνεται ως παράμετρος πράγματι υπάρχει στον * πινακα CATEGORIES της Question * * @param category Η κατηγορία μιας ερώτησης * @return Επιστρέφει true αν η κατηγορία είναι έγκυρη ενώ false σε άλλη * περίπτωση */ public static boolean belongs(String category) { for (String cat : Question.CATEGORIES) { if (cat.equals(category.toUpperCase())) { return true; } } return false; } @Override public boolean equals(Object object2) { if (this == object2) { return true; } if (!(object2 instanceof Question)) { return false; } Question question2 = (Question) object2; if (this.getQuestion().equals(question2.getQuestion())) { if (this.getCategory().equals(question2.getCategory())) { if (this.getCorrect().equals(question2.getCorrect())) { Set<String> wrongs1 = new HashSet<>(); Set<String> wrongs2 = new HashSet<>(); wrongs1.add(this.getAllWrongs()[0]); wrongs1.add(this.getAllWrongs()[1]); wrongs1.add(this.getAllWrongs()[2]); wrongs2.add(question2.getAllWrongs()[0]); wrongs2.add(question2.getAllWrongs()[1]); wrongs2.add(question2.getAllWrongs()[2]); return wrongs1.equals(wrongs2); } } } return false; } @Override public int hashCode() { int hash = 5; hash = 31 * hash + this.getQuestion().hashCode(); hash = 17 * hash + this.getCorrect().hashCode(); hash = 65 * hash + this.getCategory().hashCode(); hash = 78 * hash + this.getAllWrongs()[0].hashCode() + this.getAllWrongs()[1].hashCode() + this.getAllWrongs()[2].hashCode(); return hash; } /** * * @return Επιστρέφει την κατηγορία της ερωτήσης, την ερώτηση, και * απαριθμημένες τις απαντήσεις, με την πρώτη να είναι η σωστή και οι * υπόλοιπες λανθασμένες */ @Override public String toString() { return "Κατηγορία: " + this.getCategory() + "\n" + "Ερώτηση: " + this.getQuestion() + "\n" + "Α) " + this.getCorrect() + "\n" + "B) " + this.getAllWrongs()[0] + "\n" + "C) " + this.getAllWrongs()[1] + "\n" + "D) " + this.getAllWrongs()[2] + "\n"; } public boolean isImage() { return false; } }
TeamLS/Buzz
src/logic/Question.java
948
import java.io.File; import java.io.FileWriter; import java.io.IOException; import java.util.ArrayList; public class Main { public static void main(String[] args) { // Θα προσθέτουμε στοιχεία σε αρχείο κειμένου. ArrayList<String> names = new ArrayList<>(); names.add("John"); names.add("Mary"); names.add("Helen"); names.add("Bob"); names.add("Nick"); // Δημιουργώ ένα αρχείο File f = new File("names.txt"); //Δημιουργώ ένα αντικείμενο FileWriter για να γράψω σε αρχείο και στέλνω το αρχείο που δημιούργησα πιο πάνω. // Στην αρχή, μας εμφανίζει ένα checked exception. // Πρέπει να κάνω χειρισμό. Επιλέγω try/catch try { FileWriter writer = new FileWriter(f); for(String name: names){ writer.write(name); // Εγγραφή στο αρχείο writer.write(System.lineSeparator()); // Αλλαγή γραμμής στο σύστημα που εκτελείται ο κώδικας } writer.close(); // Κλείνω το ρεύμα... } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } new GUI(); } }
iosifidis/UoM-Applied-Informatics
s3/object_oriented_programming/lectures/Files_v2/src/Main.java
950
/** *GUMA a simple math game for elementary school students * Copyright (C) 2013-2014 Dimitrios Desyllas (pc_magas) * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. *Contact with me by main at thes address: [email protected] */ package guma.gui; import javax.swing.*; import java.awt.*; import java.awt.event.*; import javax.swing.event.*; import guma.core.Game; import guma.net.WebGameLoader; public class WebGui extends JPanel implements ActionListener,Runnable { /** *Shows the Label for seting the size of downloaded file */ private JLabel sizeLabel= new JLabel("Μέγεθος Αρχείου σε Kilobytes"); /** *Shows the Label for seting the url of Downloaded file */ private JLabel urlLabel= new JLabel("Url παιχνιδιού στο διαδίκτυο"); /** *Input of Url */ private JTextField urlInput=new JTextField(); /** *Input of size */ private JTextField sizeInput=new JTextField("0"); /** *Menu for Paste */ private JPopupMenu pastemenu=new JPopupMenu(); /** *Showing the paste MenuItem */ private JMenuItem paste=new JMenuItem("Επικόληση"); /** *Showing the cut MenuItem */ private JMenuItem cut=new JMenuItem("Αποκοπή"); /** *Showing the cut MenuItem */ private JMenuItem cοpy=new JMenuItem("Αντιγραφή"); /** *Returns stores the created Game **/ private Game gameToCreate=null; /** *Method that does all the dirty job to download the file **/ WebGameLoader w=null; /** *Consructor Method Initialises a new WebGui */ public WebGui() { super(); /*Setting right Click menu*/ cut.addActionListener(this); cοpy.addActionListener(this); paste.addActionListener(this); pastemenu.add(cut); pastemenu.add(cοpy); pastemenu.add(paste); urlInput.addMouseListener(new ShowMenu()); sizeInput.addMouseListener(new ShowMenu()); /*Setting Layout*/ GridBagLayout gridbag= new GridBagLayout(); GridBagConstraints c=new GridBagConstraints();//This variable helps us out in making the gui c.fill=GridBagConstraints.HORIZONTAL; c.weightx=1.0; c.weighty=1.0; setLayout(gridbag); /*Adding the Url Label*/ c.gridwidth = GridBagConstraints.REMAINDER; addComponent(urlLabel,gridbag,c); addComponent(urlInput,gridbag,c); c.gridwidth = GridBagConstraints.RELATIVE; addComponent(sizeLabel,gridbag,c); c.gridwidth = GridBagConstraints.REMAINDER; addComponent(sizeInput,gridbag,c); } /** *Inner Class that allows you to show the copy paste popup menu */ private class ShowMenu extends MouseAdapter { public void mousePressed(MouseEvent e) { switch(e.getModifiers()) { case InputEvent.BUTTON3_MASK: pastemenu.show(e.getComponent(), e.getX(), e.getY()); break; case InputEvent.BUTTON2_MASK: JTextField jte = (JTextField)pastemenu.getInvoker(); jte.paste(); } } } /** *Method that allows you to Add component on a GridBagLayout Panel or Frame */ public void addComponent(JComponent component,GridBagLayout gridbag,GridBagConstraints c) { gridbag.setConstraints(component,c); add(component); } @Override public void actionPerformed(ActionEvent e) { Object source=e.getSource(); if(source==paste) { JTextField jte = (JTextField)pastemenu.getInvoker(); jte.paste(); } else if(source==cοpy) { JTextField jte = (JTextField)pastemenu.getInvoker(); jte.copy(); } else if(source==cut) { JTextField jte = (JTextField)pastemenu.getInvoker(); jte.cut(); } } /** *Returns a Game from the Web */ public Game getGame() { String[] options={"OK","Ακύρωση"}; gameToCreate=null; int returnVal=JOptionPane.showOptionDialog(null,this,"Κατέβασμα παιχνιδιού από το web", JOptionPane.OK_CANCEL_OPTION, JOptionPane.QUESTION_MESSAGE, null,(Object[])options, (Object)options[1]);//Shows the Dialog if(returnVal==JOptionPane.OK_OPTION) { String url=urlInput.getText(); long sizev=0; try { String sizes=sizeInput.getText(); if(!sizes.equals("")) { sizev=(long)Float.parseFloat(sizes)*1024; } Thread t = new Thread(new Runnable() { public void run() { JOptionPane.showMessageDialog(null,"Παρακαλώ Περιμένετε", "Παρακαλώ Περιμένετε", JOptionPane.PLAIN_MESSAGE); while(true){} } }); t.start(); w=new WebGameLoader(url,sizev); gameToCreate=w.getGame(); JOptionPane.getRootFrame().dispose(); t.stop(); } catch(java.io.IOException x) { x.printStackTrace(); JOptionPane.showMessageDialog(null,"Σφάλμα","Η διεύθυνση δικτύου δεν αντιστοιχεί σε παιχνίδι",JOptionPane.ERROR_MESSAGE); return null; } catch(ClassNotFoundException c) { c.printStackTrace(); JOptionPane.showMessageDialog(null,"Σφάλμα","Το αρχείο δεν αντιστοιχεί σε παιχνίδι",JOptionPane.ERROR_MESSAGE); return null; } catch(Exception e) { JOptionPane.showMessageDialog(null,"Σφάλμα","Δεν δώσατε αριθμιτική τιμή στο μέγεθος",JOptionPane.ERROR_MESSAGE); return this.getGame(); } } else { gameToCreate=null; } System.out.println("Before Return"); return gameToCreate; } public void run() { } }
pc-magas/guma
src/guma/gui/WebGui.java
952
package week10; /** * * @author Yannis Tzitzikas ([email protected]) * 1. Change the sleep time and see the impact * 2. Uncomment Part C */ class MyThread_A extends Thread { static final int NUM=10; public void run() { for (int i=0; i<NUM; i++) { System.out.print(" A"+i); try { Thread.sleep(300); } catch (Exception e) { } } } } class MyThread_B implements Runnable { static final int NUM=10; public void run() { for (int i=0; i<NUM; i++) { System.out.print(" B" +i); try { Thread.sleep(800); } catch (Exception e) { } } } } class A_StartingExample { public static void main(String arg[]) { /* Creation of the first thread */ MyThread_A mtA = new MyThread_A(); mtA.start(); /* Creation of the second thread */ Thread mtB = new Thread(new MyThread_B()); mtB.start(); /* //perimene na teleiwsei to B try { mtA.join(); System.out.println("\nTέλειωσε το Α "); mtB.join(); System.out.println("\nTέλειωσε το Β Συνεχίζω"); } catch (Exception e) { } */ // Part C try { mtA.join(); // try commenting these lines //mtB.join(); mtB.join(1000); // wait until B finishes OR 1sec has expired if (mtB.isAlive()) { System.out.println("\nΔεν σε περιμένω άλλο"); mtB.stop(); //mtB.destroy(); } } catch (Exception e) { } /* new Thread( new Runnable() { public void run() { for (int i=0;i<100*1000;i++) System.out.print(i+"-"); } } ).start(); */ System.out.println("\n-End of main: Καλημέρα !"); } }
YannisTzitzikas/CS252playground
CS252playground/src/week10/A_StartingExample.java
954
package com.mgiandia.library.domain; import java.time.LocalDate; import com.mgiandia.library.LibraryException; import com.mgiandia.library.util.Money; import com.mgiandia.library.util.SystemDate; import java.time.temporal.ChronoUnit; /** * Ο δανεισμός ενός αντιτύπου για κάποιο δανειζόμενο. * Καταγράφει το γεγονός του δανεισμού και της επιστροφής. * @author Νίκος Διαμαντίδης * */ public class Loan { private LocalDate loanDate = SystemDate.now(); private LocalDate returnDate; private Borrower borrower; private Item item; /** * Ο κατασκευαστής της κλάσης έχει προκαθορισμένη ορατότητα. * Μόνο αντικείμενα εντός του πακέτου μπορούν * να δημιουργήσουν αντικείμενα της κλάσης. */ Loan() { } /** * Βοηθητικός κατασκευαστής που αρχικοποιεί έναν δανεισμό. * @param borrower Δανειζόμενος * @param item Αντίτυπο * @param loanDate Ημερομηνία δανεισμού */ Loan(Borrower borrower, Item item, LocalDate loanDate) { this.borrower = borrower; this.item = item; this.loanDate = loanDate; } /** * Θέτει την ημερομηνία δανεισμού. * @param loanDate Η ημερομηνία δανεισμού. */ protected void setLoanDate(LocalDate loanDate) { this.loanDate = loanDate; } /** * Επιστρέφει την ημερομηνία δανεισμού. * @return Η ημερομηνία δανεισμού. */ public LocalDate getLoanDate() { return loanDate; } /** * Επιστρέφει την προθεσμία επιστροφής του δανεισμού. * Εάν δεν έχει οριστεί ημερομηνία δανεισμού επιστρέφει {@code null}. * Εάν δεν υπάρχει δανειζόμενος επιστρέφει {@code null}. * @return Η προθεσμία επιστροφής */ public LocalDate getDue() { if (loanDate == null) { return null; } if (borrower == null) { return null; } return borrower.getLoanDue(loanDate); } /** * Θέτει την ημερομηνία επιστροφής του αντιτύπου. * @param returnDate Η ημερομηνία επιστοφής. */ protected void setReturnDate(LocalDate returnDate) { this.returnDate = returnDate; } /** * Επιστρέφει την ημερομηνία επιστροφής του αντιτύπου. * @return Η ημερομηνία επιστροφής */ public LocalDate getReturnDate() { return returnDate; } /** * Θέτει το δανειζόμενο του δανεισμού. * @param borrower Ο δανειζόμενος του δανεισμού * @see Borrower#getLoans() */ protected void setBorrower(Borrower borrower) { if (this.borrower != null) { this.borrower.friendLoans().remove(this); } this.borrower = borrower; if (borrower != null) { this.borrower.friendLoans().add(this); } } /** * Επιστρέφει το δανειζόμενο του δανεισμού. * @return Ο δανειζόμενος */ public Borrower getBorrower() { return borrower; } /** * Θέτει το αντίτυπο του δανεισμού. * @param item Το αντίτυπο */ protected void setItem(Item item) { this.item = item; } /** * Επιστρέφει το αντίτυπο του δανεισμού. * @return Το αντίτυπο */ public Item getItem() { return item; } /** * Επιστρέφει {@code true} αν το αντίτυπο δεν έχει επιστραφεί. * @return {@code true} αν το αντίτυπο δεν έχει επιστραφεί */ public boolean isPending() { return returnDate == null; } /** * Η επιστροφή του αντιτύπου. * Πραγματοποιείται η επιστροφή * και ενημερώνεται η ημερομηνία επιστροφής. */ public void returnItem() { // πρέπει να στείλουμε μήνυμα στο item ότι είναι πλέον διαθέσιμο item.available(); setReturnDate(SystemDate.now()); } /** * Επιστρέφει {@code true} εάν έχει καθυστερήσει η επιστροφή του * αντιτύπου σε σχέση με την ημερομηνία του συστήματος. * Εάν το αντίτυπο έχει επιστραφεί τότε επιστρέφει * πάντα {@code false} * @return {@code true} εάν έχει καθυστερήσει η * επιστροφή του αντιτύπου αλλιώς {@code false} */ public boolean isOverdue() { if (!isPending()) { return false; } return daysToDue() < 0; } /** * Επιστρέφει τις ημέρες που υπολείπονται * έως την προθεσμία επιστροφής τους αντιτύπου. * Χρησιμοποιείται και για τον υπολογισμό των * ημερών κατά τον οποίο έχει γίνει * υπέρβαση της προθεσμίας επιστροφής. * Η {@link Loan#getOverdue()} είναι ότι ο αριθμός * των ημερών υπολογίζεται σε σχέση με την τρέχουσα * ημερομηνία αντί σε σχέση με την ημερομηνία * επιστροφής. * <p> * @return Ο αριθμός των ημερών έως την προθεσμία επιστροφής του δανεισμού. * Αν ο αριθμός είναι θετικός τότε είναι αριθμός που υπολείπεται * έως την προθεσμία επιστροφής. * Εάν ο αριθμός είναι αρνητικός τότε επιστρέφονται * οι μέρες υπέρβασης της προθεσμίας επιστροφής. * @throws LibraryException Εάν δεν μπορεί * να υπολογιστεί η προθεσμία επιστροφής */ public long daysToDue() { LocalDate due = getDue(); if (due == null) { throw new LibraryException(); } return ChronoUnit.DAYS.between(SystemDate.now(), due); } /** * Επιστρέφει τον αριθμό ημερών καθυστέρησης * κατά την επιστροφή του αντιτύπου. * <p> * Επιστρέφει {@code 0} αν η ημερομηνία δανεισμού * είναι {@code null} ή η ημερομηνία * επιστροφής είναι {@code null} (δεν * έχει γίνει δηλαδή η επιστροφή). * Επιστρέφει {@code 0} αν δεν υπάρχει δανειζόμενος. * Η διαφορά με τη μέθοδο {@link Loan#daysToDue()} * είναι ότι επιστρέφει τον αριθμό * των ημερών καθυστέρησης σε σχέση με την * ημερομηνία επιστροφής και όχι σε σχέση με την * τρέχουσα ημερομηνία. * @return Ο αριθμός ημερών καθυστέρησης της επιστροφής */ public long getOverdue() { if (loanDate == null || returnDate == null) { return 0; } if (borrower == null) { return 0; } if (getDue() == null) { return 0; } long overdue = ChronoUnit.DAYS.between(getDue(),getReturnDate()); return overdue > 0 ? overdue : 0 ; } /** * Επιστέφει το πρόστιμο για την καθυστέρηση * της επιστροφής και αν πράγματι υπάρχει καθυστέρηση. * @return Το πρόστιμο καθυστέρησης */ public Money getFine() { if (getDue() == null || getReturnDate() == null || getBorrower() == null) { return Money.euros(0); } long overdue = ChronoUnit.DAYS.between(getDue(),returnDate); if (overdue <= 0) { return Money.euros(0); } return getBorrower().getDailyFine().times(overdue); } }
diamantidakos/Library
src/main/java/com/mgiandia/library/domain/Loan.java
955
package gov.usgs.earthquake.nshmp.calc; import static gov.usgs.earthquake.nshmp.internal.TextUtils.NEWLINE; import static java.lang.Math.exp; import static java.nio.charset.StandardCharsets.UTF_8; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; import java.util.AbstractList; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import java.util.function.Function; import java.util.function.Predicate; import com.google.common.base.Strings; import com.google.common.collect.ComparisonChain; import com.google.common.collect.FluentIterable; import com.google.common.collect.ImmutableList; import com.google.common.collect.Iterables; import com.google.common.collect.Ordering; import com.google.gson.annotations.SerializedName; import gov.usgs.earthquake.nshmp.calc.CalcConfig.Deagg.Bins; import gov.usgs.earthquake.nshmp.calc.DeaggContributor.JsonContributor; import gov.usgs.earthquake.nshmp.calc.DeaggContributor.SourceSetContributor; import gov.usgs.earthquake.nshmp.calc.DeaggContributor.SystemContributor; import gov.usgs.earthquake.nshmp.data.Data; import gov.usgs.earthquake.nshmp.eq.model.SourceType; import gov.usgs.earthquake.nshmp.gmm.Imt; import gov.usgs.earthquake.nshmp.internal.Parsing; import gov.usgs.earthquake.nshmp.internal.Parsing.Delimiter; import gov.usgs.earthquake.nshmp.util.Maths; /** * Deaggregation dataset exporter. This class handles String/Text and JSON * output of DeaggDatasets. JSON output is supported through the serialization * of custom data containers. String output is supported through the * {@code toString()} methods of those objects. * * @author Peter Powers */ final class DeaggExport { final transient DeaggDataset ddTotal; final transient DeaggDataset dd; final transient DeaggConfig dc; @SerializedName("component") final String id; final DistanceMagnitudeData data; final SummaryElements summary; final List<JsonContributor> sources; private static final String DEAGG_DATA = "data.csv"; private static final String DEAGG_SUMMARY = "summary.txt"; /* * All component DeaggDatasets require data from the final total DeaggDataset * to correctly calculate contributions and represent summary data that is not * specific to the component dataset. */ DeaggExport( DeaggDataset ddTotal, DeaggDataset dd, DeaggConfig dc, String id, boolean jsonFlag, boolean εDataFlag, boolean summaryFlag) { this.ddTotal = ddTotal; this.dd = dd; this.dc = dc; this.id = id; summary = summaryFlag ? createSummaryElements(ddTotal, dd, dc) : null; data = εDataFlag ? createDistanceMagnitudeData(ddTotal, dd) : null; sources = jsonFlag ? createJsonContributorList(ddTotal, dd, dc.contributorLimit) : null; } void toFile(Path dir, String site) throws IOException { Path siteDir = dir.resolve(site); Files.createDirectories(siteDir); Path dataPath = siteDir.resolve(DEAGG_DATA); Files.write( dataPath, data.toString().getBytes(UTF_8)); Path summaryPath = siteDir.resolve(DEAGG_SUMMARY); String summaryString = summaryStringBuilder() .append(DATASET_SEPARATOR) .toString(); Files.write( summaryPath, summaryString.getBytes(UTF_8)); } @Override public String toString() { StringBuilder sb = summaryStringBuilder(); sb.append(SECTION_SEPARATOR); appendData(sb, data, dd); sb.append(DATASET_SEPARATOR); return sb.toString(); } private StringBuilder summaryStringBuilder() { StringBuilder sb = new StringBuilder() .append("Component: ") .append(id) .append(NEWLINE) .append(SECTION_SEPARATOR) .append(summary); sb.append(SECTION_SEPARATOR); appendContributions(sb, ddTotal, dd, dc.contributorLimit); return sb; } /* * Deaggregation data. * * Create a container of distance-magnitude-epsilon data bins. This object * serializes to a JSON array of distance-magnitude (r-m) bins, each of which * contans an array of non-zero ε bins. The r-m bins are sorted ascending in * distance but descending in magnitude to facilitate rendering order in a * standard deaggregation 3D histogram. */ private static DistanceMagnitudeData createDistanceMagnitudeData( DeaggDataset ddTotal, DeaggDataset dd) { ImmutableList.Builder<RmBin> rmBins = ImmutableList.builder(); List<Double> distances = dd.rmε.rows(); List<Double> magnitudes = dd.rmε.columns(); double toPercent = percentScalar(ddTotal); // iterate distances ascending, magnitudes descending for (int ri = 0; ri < distances.size(); ri++) { double r = distances.get(ri); for (int mi = magnitudes.size() - 1; mi >= 0; mi--) { double rmBinWeight = dd.rmWeights.get(ri, mi); // skip empty bins if (rmBinWeight == 0.0) { continue; } double m = magnitudes.get(mi); double rBar = dd.rmrScaled.get(ri, mi) / rmBinWeight; double mBar = dd.rmmScaled.get(ri, mi) / rmBinWeight; double εBar = dd.rmεScaled.get(ri, mi) / rmBinWeight; // scale a mutable copy of epsilon values to percentage List<Double> εValues = new ArrayList<>(dd.rmε.column(ri, mi).yValues()); Data.multiply(toPercent, εValues); ImmutableList.Builder<εData> εDataList = ImmutableList.builder(); for (int i = 0; i < εValues.size(); i++) { double εValue = εValues.get(i); if (εValue <= 0.0) { continue; } εDataList.add(new εData(i, εValue)); } RmBin rmBin = new RmBin( r, m, round(rBar, 2), round(mBar, 2), round(εBar, 2), εDataList.build(), ImmutableList.copyOf(εValues)); rmBins.add(rmBin); } } return new DistanceMagnitudeData( rmBins.build(), dd.rmε.levels().size()); } /* * Distance-magnitude bin list. */ private static final class DistanceMagnitudeData extends ListWrapper<RmBin> { final transient int εSize; DistanceMagnitudeData(List<RmBin> delegate, int εSize) { super(delegate); this.εSize = εSize; } @Override public String toString() { StringBuilder sb = new StringBuilder(DEAGG_DATA_HEADER); sb.append(",").append(epsilonHeader(εSize)); sb.append(NEWLINE); for (RmBin rmBin : RM_BIN_SORTER.immutableSortedCopy(this)) { sb.append(String.format( "%6.2f, %6.2f, %4.2f, %4.2f, %5.2f,", rmBin.r, rmBin.rBar, rmBin.m, rmBin.mBar, rmBin.εBar)); double total = Data.sum(rmBin.εValues); sb.append(EPSILON_FORMATTER.apply(total)).append(","); sb.append(formatEpsilonValues(rmBin.εValues)); sb.append(NEWLINE); } return sb.toString(); } // TODO consider ways to avoid repeating // this for multiple DeaggDatasets; it's // also the only reason we need εSize; // perhaps just carry the string with the model String epsilonHeader(int size) { StringBuilder sb = new StringBuilder(); for (int i = 0; i < size; i++) { if (i > 0) { sb.append(","); } sb.append(String.format("%6s", "ε" + i)); } return sb.toString(); } } /* * Data container for a single distance-magnitude (r-m) bin. * * Although we have the minimum necessary data in εdata for JSON * serialization, we want the complete εValue array for string serialization, * hence we persist the transient εValues list. */ @SuppressWarnings("unused") private static final class RmBin { final double r; final double m; final double rBar; final double mBar; final double εBar; final List<εData> εdata; final transient List<Double> εValues; private RmBin( double r, double m, double rBar, double mBar, double εBar, List<εData> εdata, List<Double> εValues) { this.r = r; this.m = m; this.rBar = rBar; this.mBar = mBar; this.εBar = εBar; this.εdata = εdata; this.εValues = εValues; } } /* * Single ε value bin. */ @SuppressWarnings("unused") private static final class εData { final int εbin; final double value; private εData(int εbin, double value) { this.εbin = εbin; this.value = value; } } /* * DistanceMagnitudeData string serialization helpers. */ private static final String DEAGG_DATA_HEADER = String.format( "%6s, %7s, %4s, %5s, %6s, %5s", "r", "r̅", "m", "m̅", "ε̅", "Σε"); private static final String E_TRACE = " T"; private static final String E_ZERO = " 0"; private static final String E_FORMAT = " %5.2f"; private static final double TRACE_LIMIT = 0.01; private static Function<Double, String> EPSILON_FORMATTER = new Function<Double, String>() { @Override public String apply(Double value) { return (value == 0.0) ? E_ZERO : (value < TRACE_LIMIT) ? E_TRACE : String.format(E_FORMAT, value); } }; private static String formatEpsilonValues(List<Double> values) { return Delimiter.COMMA.joiner().join(Iterables.transform( values, EPSILON_FORMATTER::apply)); } private static Ordering<RmBin> RM_BIN_SORTER = new Ordering<RmBin>() { @Override public int compare(RmBin left, RmBin right) { return ComparisonChain.start() .compare(left.r, right.r) .compare(left.m, right.m) .result(); } }; private static final String DISCRETIZATION_FMT = "min = %.1f, max = %.1f, Δ = %.1f"; /* * Deaggregation summary. * * TODO consider ways to not repeat building elements/items that are not * unique to a dataset; perhaps only include some items in the total component * * Create a container of summary information for a DeaggDataset. */ private static SummaryElements createSummaryElements( DeaggDataset total, DeaggDataset dd, DeaggConfig dc) { double toPercent = percentScalar(total); int ri, mi, εi; /* targets */ double recoveredRate = total.binned + total.residual; double recoveredReturnPeriod = 1.0 / recoveredRate; /* totals */ double ddTotal = dd.binned * toPercent; double ddResidual = dd.residual * toPercent; double ddTrace = traceContribution(dd); /* modes: largest r-m bin */ int[] rmIndex = dd.rmWeights.maxIndex(); ri = rmIndex[0]; mi = rmIndex[1]; double rmBinWeight = dd.rmWeights.get(ri, mi); double rmrMode = dd.rmrScaled.get(ri, mi) / rmBinWeight; double rmmMode = dd.rmmScaled.get(ri, mi) / rmBinWeight; double rmεMode = dd.rmεScaled.get(ri, mi) / rmBinWeight; double rmModeContrib = rmBinWeight * toPercent; /* modes: largest ε bin */ int[] rmεIndex = dd.rmε.maxIndex(); ri = rmεIndex[0]; mi = rmεIndex[1]; εi = rmεIndex[2]; double εBinWeight = dd.rmε.get(ri, mi, εi); double εrMode = dd.rScaled.get(ri, mi, εi) / εBinWeight; double εmMode = dd.mScaled.get(ri, mi, εi) / εBinWeight; double εεMode = dd.εScaled.get(ri, mi, εi) / εBinWeight; double εModeContrib = εBinWeight * toPercent; /* discretization */ Bins b = dc.bins; String rDiscr = String.format(DISCRETIZATION_FMT, b.rMin, b.rMax, b.Δr); String mDiscr = String.format(DISCRETIZATION_FMT, b.mMin, b.mMax, b.Δm); String εDiscr = String.format(DISCRETIZATION_FMT, b.εMin, b.εMax, b.Δε); /* custom imt formatting */ Imt imt = dc.imt; String imlLabel = (imt.isSA() ? imt.period() + " s SA" : imt.name()) + " ground motion"; ImmutableList.Builder<SummaryElement> summaryElements = ImmutableList.builder(); summaryElements.add( new SummaryElement("Deaggregation targets", true, ImmutableList.of( new SummaryItem("Return period", dc.returnPeriod, "yrs"), new SummaryItem("Exceedance rate", dc.rate, "yr⁻¹"), new SummaryItem(imlLabel, exp(dc.iml), dc.imt.units()))), new SummaryElement("Recovered targets", true, ImmutableList.of( new SummaryItem("Return period", recoveredReturnPeriod, "yrs"), new SummaryItem("Exceedance rate", recoveredRate, "yr⁻¹"))), new SummaryElement("Totals", true, ImmutableList.of( new SummaryItem("Binned", round(ddTotal, RME_ROUNDING), "%"), new SummaryItem("Residual", round(ddResidual, RME_ROUNDING), "%"), new SummaryItem("Trace", round(ddTrace, RME_ROUNDING), "%"))), new SummaryElement("Mean (over all sources)", true, ImmutableList.of( new SummaryItem("m", round(dd.mBar, RME_ROUNDING), null), new SummaryItem("r", round(dd.rBar, RME_ROUNDING), "km"), new SummaryItem("ε₀", round(dd.εBar, RME_ROUNDING), "σ"))), new SummaryElement("Mode (largest m-r bin)", true, ImmutableList.of( new SummaryItem("m", round(rmmMode, RME_ROUNDING), null), new SummaryItem("r", round(rmrMode, RME_ROUNDING), "km"), new SummaryItem("ε₀", round(rmεMode, RME_ROUNDING), "σ"), new SummaryItem("Contribution", round(rmModeContrib, RME_ROUNDING), "%"))), new SummaryElement("Mode (largest m-r-ε₀ bin)", true, ImmutableList.of( new SummaryItem("m", round(εmMode, RME_ROUNDING), null), new SummaryItem("r", round(εrMode, RME_ROUNDING), "km"), new SummaryItem("ε₀", round(εεMode, RME_ROUNDING), "σ"), new SummaryItem("Contribution", round(εModeContrib, RME_ROUNDING), "%"))), new SummaryElement("Discretization", true, ImmutableList.of( new SummaryItem("r", rDiscr, "km"), new SummaryItem("m", mDiscr, null), new SummaryItem("ε", εDiscr, "σ"))), new SummaryElement("Epsilon keys", true, dc.εBins.toSummaryItems())); return new SummaryElements(summaryElements.build()); } private static double traceContribution(DeaggDataset dd) { double toPercent = percentScalar(dd); double traceContribution = 0.0; for (int ri = 0; ri < dd.rmε.rows().size(); ri++) { for (int mi = 0; mi < dd.rmε.columns().size(); mi++) { if (dd.rmWeights.get(ri, mi) <= 0.0) { continue; } for (double εValue : dd.rmε.column(ri, mi).yValues()) { double rmεBinContribution = εValue * toPercent; if (rmεBinContribution < TRACE_LIMIT) { traceContribution += rmεBinContribution; } } } } return traceContribution; } private static double percentScalar(DeaggDataset dd) { return 100.0 / (dd.binned + dd.residual); } private static final int RME_ROUNDING = 2; private static final int SUMMARY_NAME_WIDTH = 22; /* * When all sources are out of range for a dataset (i.e. residual ≠ 0.0) the * rBar, mBar, and εBar fields are NaN as a result of dividing-by-zero rates, * as are other summary statistics. For the purpose of presentation and JSON * serialization we convert to a Double which may be null that can be handled * during serialization and in toString(). */ private static Double round(double value, int scale) { return Double.isNaN(value) ? null : Maths.round(value, scale); } /* * Summary data list. */ private static final class SummaryElements extends ListWrapper<SummaryElement> { SummaryElements(List<SummaryElement> delegate) { super(delegate); } @Override public String toString() { StringBuilder sb = new StringBuilder(NEWLINE); for (SummaryElement element : this) { sb.append(element.name).append(":").append(NEWLINE); for (SummaryItem item : element.data) { sb.append(Strings.padStart(item.name + ": ", SUMMARY_NAME_WIDTH, ' ')); if (item.value == null) { sb.append("no value"); } else { sb.append(item.value); if (item.units != null) { sb.append(' ').append(item.units); } } sb.append(NEWLINE); } sb.append(NEWLINE); } return sb.toString(); } } @SuppressWarnings("unused") private static final class SummaryElement { final String name; final boolean display; final List<SummaryItem> data; SummaryElement(String name, boolean display, List<SummaryItem> data) { this.name = name; this.display = display; this.data = data; } } private static final class SummaryItem { final String name; final Object value; final String units; SummaryItem(String name, Object value, String units) { this.name = name; this.value = value; this.units = units; } } private static final int OUTPUT_WIDTH = 105; private static final int NAME_WIDTH = 44; private static final int TYPE_WIDTH = 9; private static final String SRC_SET_NAME_FMT = "%-" + NAME_WIDTH + "s"; private static final String SRC_NAME_FMT = "%-" + (NAME_WIDTH + TYPE_WIDTH) + "s"; private static final String HEADER_LABEL_FMT = "%9s%9s%7s%7s%9s%8s%6s%8s"; private static final String HEADER_LINE_FMT = "%9s%8s%6s%7s%9s%8s%6s%8s"; private static final String SOURCE_COLUMN_FMT = "%8.2f%6.2f%7.2f%9.2f%8.2f%6.0f%8.2f"; private static final String CONTRIB_HEADER_LABEL_FMT = SRC_SET_NAME_FMT + HEADER_LABEL_FMT; private static final String CONTRIB_HEADER_LINE_FMT = SRC_SET_NAME_FMT + HEADER_LINE_FMT; static final String CONTRIB_SOURCE_SET_FMT = SRC_SET_NAME_FMT + "%9s%52.2f"; static final String CONTRIB_SOURCE_FMT = SRC_NAME_FMT + SOURCE_COLUMN_FMT; private static final String CONTRIBUTION_HEADER = new StringBuilder() .append(String.format(CONTRIB_HEADER_LABEL_FMT, "Source Set ↳ Source", "Type", "r̅", "m̅", "ε₀", "lon", "lat", "az", "%")) .append(NEWLINE) .append(String.format(CONTRIB_HEADER_LINE_FMT, "——————————————————————————————————————————", "—————————", "——————", "————", "—————", "———————", "——————", "————", "——————")) .append(NEWLINE) .toString(); private static final String DATASET_SEPARATOR = Strings.repeat("—", OUTPUT_WIDTH) + NEWLINE; private static final String SECTION_SEPARATOR = Strings.repeat("·", OUTPUT_WIDTH) + NEWLINE; /* Data table string helper. */ static StringBuilder appendData( StringBuilder sb, DistanceMagnitudeData data, DeaggDataset dd) { sb.append("Deaggregation data:"); if (dd.binned == 0.0) { sb.append(" Suppressed (binned rate = 0.0).").append(NEWLINE); } else { sb.append(NEWLINE).append(NEWLINE).append(data); } return sb; } /* Source contribution string helper. */ static StringBuilder appendContributions( StringBuilder sb, DeaggDataset ddTotal, DeaggDataset dd, double contributorLimit) { ContributionFilter contributionFilter = new ContributionFilter( contributorLimit, percentScalar(ddTotal)); /* * Could use a FluentIterable generated list below, but because we know the * contributors are sorted descending by total contribution, we short * circuit an iterator instead. */ List<DeaggContributor> sourceSetContributors = new ArrayList<>(); for (DeaggContributor contributor : dd.contributors) { if (contributionFilter.test(contributor)) { sourceSetContributors.add(contributor); continue; } break; } sb.append("Deaggregation contributors:"); if (sourceSetContributors.size() > 0) { sb.append(NEWLINE).append(NEWLINE).append(CONTRIBUTION_HEADER); boolean firstContributor = true; for (DeaggContributor contributor : sourceSetContributors) { sb.append(firstContributor ? "" : NEWLINE); firstContributor = false; contributor.appendTo(sb, "", contributionFilter); } } else { sb.append(" Suppressed (all contributions < ") .append(contributorLimit) .append("%).") .append(NEWLINE); } /* This will append content only if system sources contribute. */ appendSystemMfds(sb, dd, contributionFilter); return sb; } private static Predicate<SourceSetContributor> SYSTEM_FILTER = new Predicate<SourceSetContributor>() { @Override public boolean test(SourceSetContributor contributor) { return contributor.sourceSet.type() == SourceType.SYSTEM; } }; private static Function<DeaggContributor, SourceSetContributor> TO_SOURCE_SET_CONTRIBUTOR = new Function<DeaggContributor, SourceSetContributor>() { @Override public SourceSetContributor apply(DeaggContributor contributor) { return (SourceSetContributor) contributor; } }; /* Filters out contributors whose contribution is below supplied limit. */ static final class ContributionFilter implements Predicate<DeaggContributor> { private final double limit; private final double toPercent; ContributionFilter(double limit, double toPercent) { this.limit = limit; this.toPercent = toPercent; } double toPercent(double rate) { return rate * toPercent; } @Override public boolean test(DeaggContributor contributor) { return contributor.total() * toPercent >= limit; } } private List<JsonContributor> createJsonContributorList( DeaggDataset ddTotal, DeaggDataset dd, double contributorLimit) { ContributionFilter contributionFilter = new ContributionFilter( contributorLimit, percentScalar(ddTotal)); ImmutableList.Builder<JsonContributor> jsonContributors = ImmutableList.builder(); for (DeaggContributor contributor : dd.contributors) { if (contributionFilter.test(contributor)) { jsonContributors.addAll(contributor.toJson(contributionFilter)); continue; } break; } return jsonContributors.build(); } static final String SYSTEM_MFD_FORMAT = "%5s, %48s,"; static StringBuilder appendSystemMfds( StringBuilder sb, DeaggDataset dd, ContributionFilter contributionFilter) { List<SourceSetContributor> systemSourceSetContributors = FluentIterable .from(dd.contributors) .transform(TO_SOURCE_SET_CONTRIBUTOR::apply) .filter(SYSTEM_FILTER::test) .filter(contributionFilter::test) .toList(); boolean first = true; for (SourceSetContributor ssc : systemSourceSetContributors) { SystemContributor model = (SystemContributor) ssc.children.get(0); if (!contributionFilter.test(model)) { continue; } sb.append(first ? SECTION_SEPARATOR : NEWLINE) .append("System section MFDs: " + ssc.sourceSet.name()) .append(NEWLINE).append(NEWLINE) .append(String.format(SYSTEM_MFD_FORMAT, "Index", "Section")) .append(Parsing.toString(model.mfd.rows(), "%9.2f", ",", false, true)) .append(NEWLINE); for (DeaggContributor child : ssc.children) { if (contributionFilter.test(child)) { ((SystemContributor) child).appendMfd(sb); continue; } break; } first = false; } return sb; } /* Epsilon metadata. */ static class EpsilonBins extends ListWrapper<εBin> { EpsilonBins(List<εBin> delegate) { super(delegate); } @Override public String toString() { StringBuilder sb = new StringBuilder("Epsilon keys:").append(NEWLINE); for (εBin bin : this) { sb.append(Strings.padStart("ε" + bin.id + ": ", SUMMARY_NAME_WIDTH, ' ')); sb.append(bin) .append(NEWLINE); } sb.append(NEWLINE); return sb.toString(); } List<SummaryItem> toSummaryItems() { return FluentIterable.from(this) .transform(BIN_TO_SUMMARY_ITEM::apply) .toList(); } } private static final Function<εBin, SummaryItem> BIN_TO_SUMMARY_ITEM = new Function<εBin, SummaryItem>() { @Override public SummaryItem apply(εBin bin) { return new SummaryItem("ε" + bin.id, bin.toString(), null); } }; static final class εBin { final int id; final Double min; final Double max; εBin(int id, Double min, Double max) { this.id = id; this.min = min; this.max = max; } @Override public String toString() { return new StringBuilder("[") .append((min == null) ? "-∞" : Double.toString(min)) .append(" .. ") .append((max == null) ? "+∞" : Double.toString(max)) .append((max == null) ? "]" : ")") .toString(); } } /* * List wrapper that preserves JSON serialization yet permits custom * toString() methods for other export formats. */ private static class ListWrapper<T> extends AbstractList<T> { final transient List<T> delegate; ListWrapper(List<T> delegate) { this.delegate = delegate; } @Override public T get(int index) { return delegate.get(index); } @Override public int size() { return delegate.size(); } @Override public Iterator<T> iterator() { return delegate.iterator(); } } }
usgs/nshmp-haz
src/gov/usgs/earthquake/nshmp/calc/DeaggExport.java
958
/* * Copyright 2012 Google Inc. * * 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. */ package com.google.gwt.i18n.client.impl.cldr; // DO NOT EDIT - GENERATED FROM CLDR AND ICU DATA /** * Implementation of DateTimeFormatInfo for the "el" locale. */ public class DateTimeFormatInfoImpl_el extends DateTimeFormatInfoImpl { @Override public String[] ampms() { return new String[] { "π.μ.", "μ.μ." }; } @Override public String dateFormatFull() { return "EEEE, d MMMM y"; } @Override public String dateFormatLong() { return "d MMMM y"; } @Override public String dateFormatMedium() { return "d MMM y"; } @Override public String dateFormatShort() { return "d/M/yy"; } @Override public String dateTimeFull(String timePattern, String datePattern) { return datePattern + " - " + timePattern; } @Override public String dateTimeLong(String timePattern, String datePattern) { return datePattern + " - " + timePattern; } @Override public String dateTimeMedium(String timePattern, String datePattern) { return datePattern + ", " + timePattern; } @Override public String dateTimeShort(String timePattern, String datePattern) { return datePattern + ", " + timePattern; } @Override public String[] erasFull() { return new String[] { "προ Χριστού", "μετά Χριστόν" }; } @Override public String[] erasShort() { return new String[] { "π.Χ.", "μ.Χ." }; } @Override public String formatMonthAbbrev() { return "MMM"; } @Override public String formatMonthAbbrevDay() { return "d MMM"; } @Override public String formatMonthFull() { return "MMMM"; } @Override public String formatMonthFullDay() { return "d MMMM"; } @Override public String formatMonthFullWeekdayDay() { return "EEEE, d MMMM"; } @Override public String formatMonthNumDay() { return "d/M"; } @Override public String formatYearMonthAbbrev() { return "MMM y"; } @Override public String formatYearMonthAbbrevDay() { return "d MMM y"; } @Override public String formatYearMonthFull() { return "LLLL y"; } @Override public String formatYearMonthFullDay() { return "d MMMM y"; } @Override public String formatYearMonthNum() { return "M/y"; } @Override public String formatYearMonthNumDay() { return "d/M/y"; } @Override public String formatYearMonthWeekdayDay() { return "EEE, d MMM y"; } @Override public String[] monthsFull() { return new String[] { "Ιανουαρίου", "Φεβρουαρίου", "Μαρτίου", "Απριλίου", "Μαΐου", "Ιουνίου", "Ιουλίου", "Αυγούστου", "Σεπτεμβρίου", "Οκτωβρίου", "Νοεμβρίου", "Δεκεμβρίου" }; } @Override public String[] monthsFullStandalone() { return new String[] { "Ιανουάριος", "Φεβρουάριος", "Μάρτιος", "Απρίλιος", "Μάιος", "Ιούνιος", "Ιούλιος", "Αύγουστος", "Σεπτέμβριος", "Οκτώβριος", "Νοέμβριος", "Δεκέμβριος" }; } @Override public String[] monthsNarrow() { return new String[] { "Ι", "Φ", "Μ", "Α", "Μ", "Ι", "Ι", "Α", "Σ", "Ο", "Ν", "Δ" }; } @Override public String[] monthsShort() { return new String[] { "Ιαν", "Φεβ", "Μαρ", "Απρ", "Μαΐ", "Ιουν", "Ιουλ", "Αυγ", "Σεπ", "Οκτ", "Νοε", "Δεκ" }; } @Override public String[] monthsShortStandalone() { return new String[] { "Ιαν", "Φεβ", "Μάρ", "Απρ", "Μάι", "Ιούν", "Ιούλ", "Αύγ", "Σεπ", "Οκτ", "Νοέ", "Δεκ" }; } @Override public String[] quartersFull() { return new String[] { "1ο τρίμηνο", "2ο τρίμηνο", "3ο τρίμηνο", "4ο τρίμηνο" }; } @Override public String[] quartersShort() { return new String[] { "Τ1", "Τ2", "Τ3", "Τ4" }; } @Override public String timeFormatFull() { return "h:mm:ss a zzzz"; } @Override public String timeFormatLong() { return "h:mm:ss a z"; } @Override public String timeFormatMedium() { return "h:mm:ss a"; } @Override public String timeFormatShort() { return "h:mm a"; } @Override public String[] weekdaysFull() { return new String[] { "Κυριακή", "Δευτέρα", "Τρίτη", "Τετάρτη", "Πέμπτη", "Παρασκευή", "Σάββατο" }; } @Override public String[] weekdaysNarrow() { return new String[] { "Κ", "Δ", "Τ", "Τ", "Π", "Π", "Σ" }; } @Override public String[] weekdaysShort() { return new String[] { "Κυρ", "Δευ", "Τρί", "Τετ", "Πέμ", "Παρ", "Σάβ" }; } }
gwtproject/gwt
user/src/com/google/gwt/i18n/client/impl/cldr/DateTimeFormatInfoImpl_el.java
962
/* * Copyright 2014-present Deezer.com * * 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. */ package com.deezer.research.language; public class TestData { public static String[][] data = { {"en", "ENGLISH", "confiscation of goods is assigned as the penalty part most of the courts consist of members and when it is necessary to bring public cases before a jury of members two courts combine for the purpose the most important cases of all are brought jurors or"}, {"", "ARMENIAN", " ա յ եվ նա հիացած աչքերով նայում է հինգհարկանի շենքի տարօրինակ փոքրիկ քառակուսի պատուհաններին դեռ մենք շատ ենք հետամնաց ասում է նա այսպես է"}, {"", "CHEROKEE", "ᎠᎢᏍᎩ ᎠᏟᎶᏍᏗ ᏥᏄᏍᏛᎩ ᎦᎫᏍᏛᏅᎯ ᎾᎥᎢ"}, {"", "DHIVEHI", " ހިންދީ ބަހުން ވާހަކަ ދައްކާއިރު ދެވަނަ ބަހެއްގެ ގޮތުގައާއި އެނޫން ގޮތްގޮތުން ހިންދީ ބަހުން ވާހަކަ ދައްކާ މީހުންގެ އަދަދު މިލިއަނަށް"}, {"", "GEORGIAN", " ა ბირთვიდან მიღებული ელემენტი მენდელეევის პერიოდულ სიტემაში გადაინაცვლებს ორი უჯრით"}, {"el", "GREEK", " ή αρνητική αναζήτηση λέξης κλειδιού καταστήστε τις μεμονωμένες λέξεις κλειδιά περισσότερο στοχοθετημένες με τη μετατροπή τους σε"}, {"gu", "GUJARATI", " આના પરિણામ પ્રમાણસર ફોન્ટ અવતરણ ચિન્હવાળા પાઠને છુપાવો બધા સમૂહો શોધાયા હાલનો જ સંદેશ વિષયની"}, {"", "INUKTITUT", "ᐃᑯᒪᒻᒪᑦ ᕿᓈᖏᓐᓇᓲᖑᒻᒪᑦ ᑎᑎᖅᑕᓕᒫᖅᓃᕕᑦ ᑎᑦᕆᐊᑐᓐᖏᑦᑕᑎᑦ ᑎᑎᖅᑕᑉᐱᑦ ᓯᕗᓂᖓᓂ ᑎᑎᖅᖃᖅ ᑎᑎᕆᐊᑐᓐᖏᑕᐃᑦ ᕿᓂᓲᖑᔪᒍᑦ ᑎᑎᖅᑕᓕᒫᖅᓃᕕᑦ"}, {"kn", "KANNADA", " ಂಠಯ್ಯನವರು ತುಮಕೂರು ಜಿಲ್ಲೆಯ ಚಿಕ್ಕನಾಯಕನಹಳ್ಳಿ ತಾಲ್ಲೂಕಿನ ತೀರ್ಥಪುರ ವೆಂಬ ಸಾಧಾರಣ ಹಳ್ಳಿಯ ಶ್ಯಾನುಭೋಗರ"}, {"", "KHMER", " ក ខ គ ឃ ង ច ឆ ជ ឈ ញ ដ ឋ ឌ ឍ ណ ត ថ ទ ធ ន ប ផ ព ភ ម យ រ ល វ ស ហ ឡ អ ឥ ឦ ឧ ឪ ឫ ឬ ឯ ឱ ទាំងអស់"}, {"", "LAOTHIAN", " ກຫາທົ່ວທັງເວັບ ແລະໃນເວັບໄຮ້ສາຍ ທຳອິດໃຫ້ທຳການຊອກຫາກ່ອນ ຈາກນັ້ນ ໃຫ້ກົດປຸ່ມເມນູ ໃນໜ້າຜົນໄດ້"}, {"", "LIMBU", "ᤁᤡᤖᤠᤳ ᤕᤠᤰᤌᤢᤱ ᤆᤢᤶᤗᤢᤱᤖᤧ ᤛᤥᤎᤢᤱᤃᤧᤴ ᤀᤡᤔᤠᤴᤛᤡᤱ ᤆᤧᤶᤈᤱᤗᤧ ᤁᤢᤔᤡᤱᤅᤥ ᤏᤠᤈᤡᤖᤡ ᤋᤱᤒᤣ ᥈᥆᥆᥉ ᤒᤠ ᤈᤏᤘᤖᤡ ᤗᤠᤏᤢᤀᤠᤱ ᤁ᤹ᤏᤠ ᤋᤱᤒᤣ ᤁᤠᤰ ᤏᤠ᤺ᤳᤋᤢ ᤕᤢᤖᤢᤒᤠ ᤀᤡᤔᤠᤴᤛᤡᤱ ᤋᤱᤃᤡᤵᤛᤡᤱ ᤌᤡᤶᤒᤣᤴ ᤂᤠᤃᤴ ᤛᤡᤛᤣ᤺ᤰᤗᤠ ᥇᥍ ᤂᤧᤴ ᤀᤡᤛᤡᤰ ᥇ ᤈᤏᤘᤖᤡ ᥈᥆᥆᥊ ᤀᤥ ᤏᤠᤛᤢᤵ ᤆᤥ᤺ᤰᤔᤠ ᤌᤡᤶᤒᤣ ᤋᤱᤃᤠᤶᤛᤡᤱᤗ ᤐᤳᤐᤠ ᤀᤡᤱᤄᤱ ᤘᤠ᤹"}, {"ml", "MALAYALAM", " ം അങ്ങനെ ഞങ്ങള് അവരുടെ മുമ്പില് നിന്നു ഔടും ഉടനെ നിങ്ങള് പതിയിരിപ്പില് നിന്നു എഴുന്നേറ്റു"}, {"", "ORIYA", "ଅକ୍ଟୋବର ଡିସେମ୍ବର"}, {"pa", "PUNJABI", " ਂ ਦਿਨਾਂ ਵਿਚ ਭਾਈ ਸਾਹਿਬ ਦੀ ਬੁੱਚੜ ਗੋਬਿੰਦ ਰਾਮ ਨਾਲ ਅੜਫਸ ਚੱਲ ਰਹੀ ਸੀ ਗੋਬਿੰਦ ਰਾਮ ਨੇ ਭਾਈ ਸਾਹਿਬ ਦੀਆਂ ਭੈਣਾ"}, {"", "SINHALESE", " අනුරාධ මිහිඳුකුල නමින් සකුරා ට ලිපියක් තැපෑලෙන් එවා තිබුණා කි ් රස්ටි ෂෙල්ටන් ප ් රනාන්දු ද"}, {"", "SYRIAC", "ܐܕܪܝܣ ܓܛܘ ܫܘܪܝܐ ܡܢ ܦܪܢܣܐ ܡܢ ܐܣܦܢܝܐ ܚܐܪܘܬܐ ܒܐܕܪ ܒܢܝܣܢ ܫܛܝܚܘܬܐ ܟܠܢܝܐ ܡܝ̈ܐ ܒܥܠܡܐ"}, // Language-Detection does not support the Tagalog script //{"tl", "TAGALOG", " ᜋᜇ᜔ ᜐᜓᜎᜆ᜔ ᜃ ᜈᜅ᜔ ᜊᜌ᜔ᜊᜌᜒᜈ᜔ ᜂᜉᜅ᜔᜔ ᜋᜐᜈᜌ᜔ ᜎᜅ᜔ ᜁᜐ ᜉᜅ᜔ ᜀᜃ᜔ᜎᜆ᜔ ᜆᜓᜅ᜔ᜃᜓᜎ᜔ ᜐ ᜊᜌ᜔ᜊᜌᜒᜈ᜔ ᜐ ᜆᜒᜅᜒᜈ᜔ ᜃᜓ"}, {"tl", "TAGALOG", "Bawat tao'y isinilang na may laya at magkakapantay ang taglay na dangal at karapatan.Sila'y pinagkalooban ng pangangatwiran at budhi na kailangang gamitin nila sa pagtuturingan nila sa diwa ng pagkakapatiran."}, {"ta", "TAMIL", " அங்கு ராஜேந்திர சோழனால் கட்டப்பட்ட பிரம்மாண்டமான சிவன் கோவில் ஒன்றும் உள்ளது தொகு"}, {"te", "TELUGU", " ఁ దనర జయించిన తత్వ మరసి చూడఁ దాన యగును రాజయోగి యిట్లు తేజరిల్లుచు నుండు విశ్వదాభిరామ వినర వేమ"}, {"th", "THAI", " กฏในการค้นหา หรือหน้าเนื้อหา หากท่านเลือกลงโฆษณา ท่านอาจจะปรับต้องเพิ่มงบประมาณรายวันตา"}, {"zh-cn", "Chinese", "产品的简报和公告 提交该申请后无法进行更改 请确认您的选择是正确的 对于要提交的图书 我确认 我是版权所有者或已得到版权所有者的授权 要更改您的国家 地区 请在此表的最上端更改您的"}, // Language-Detection has a bug concerning traditional chinese and korean. See https://code.google.com/p/language-detection/issues/detail?id=66 //{"zh-tw", "ChineseT", " 之前為 帳單交易作業區 已變更 廣告內容 之前為 銷售代表 之前為 張貼日期為 百分比之前為 合約 為 目標對象條件已刪除 結束日期之前為"}, {"ja", "Japanese", " このペ ジでは アカウントに指定された予算の履歴を一覧にしています それぞれの項目には 予算額と特定期間のステ タスが表示されます 現在または今後の予算を設定するには"}, {"ko", "Korean", " 개별적으로 리포트 액세스 권한을 부여할 수 있습니다 액세스 권한 부여사용자에게 프로필 리포트에 액세스할 수 있는 권한을 부여하시려면 가용 프로필 상자에서 프로필 이름을 선택한 다음"}, {"af", "AFRIKAANS", " aam skukuza die naam beteken hy wat skoonvee of hy wat alles onderstebo keer wysig bosveldkampe boskampe is kleiner afgeleë ruskampe wat oor min fasiliteite beskik daar is geen restaurante of winkels nie en slegs oornagbesoekers word toegelaat bateleur"}, {"sq", "ALBANIAN", " a do të kërkoni nga beogradi që të njohë pavarësinë e kosovës zoti thaçi prishtina është gati ta njoh pavarësinë e serbisë ndërsa natyrisht se do të kërkohet një gjë e tillë që edhe beogradi ta njoh shtetin e pavarur dhe sovran të"}, {"ar", "ARABIC", "احتيالية بيع أي حساب"}, {"", "AZERBAIJANI", " a az qalıb breyn rinq intellektual oyunu üzrə yarışın zona mərhələləri keçirilib miq un qalıqlarının dənizdən çıxarılması davam edir məhəmməd peyğəmbərin karikaturalarını çap edən qəzetin baş redaktoru iş otağında ölüb"}, {"", "BASQUE", " a den eraso bat honen kontra hortaz eragiketa bakarrik behar dituen eraso batek aes apurtuko luke nahiz eta oraingoz eraso bideraezina izan gaur egungo teknologiaren mugak direla eta oraingoz kezka hauek alde batera utzi daitezke orain arteko indar"}, {"", "BELARUSIAN", " а друкаваць іх не было тэхнічна магчыма бліжэй за вільню тым самым часам нямецкае кіраўніцтва прапаноўвала апроч ўвядзення лацінкі яе"}, {"bn", "BENGALI", "গ্যালারির ৩৮ বছর পূর্তিতে মূল্যছাড় অর্থনীতি বিএনপির ওয়াক আউট তপন চৌধুরী হারবাল অ্যাসোসিয়েশনের সভাপতি আন্তর্জাতিক পরামর্শক বোর্ড দিয়ে শরিয়াহ্ ইনন্ডেক্স করবে সিএসই মালিকপক্ষের কান্না, শ্রমিকের অনিশ্চয়তা মতিঝিলে সমাবেশ নিষিদ্ধ: এফবিসিসিআইয়ের ধন্যবাদ বিনোদন বিশেষ প্রতিবেদন বাংলালিংকের গ্র্যান্ডমাস্টার সিজন-৩ ব্রাজিলে বিশ্বকাপ ফুটবল আয়োজনবিরোধী বিক্ষোভ দেশের নিরাপত্তার চেয়ে অনেক বেশি সচেতন । প্রার্থীদের দক্ষতা ও যোগ্যতার পাশাপাশি তারা জাতীয় ইস্যুগুলোতে প্রাধান্য দিয়েছেন । ” পাঁচটি সিটিতে ২০ লাখ ভোটারদের দিয়ে জাতীয় নির্বাচনে ৮ কোটি ভোটারদের সঙ্গে তুলনা করা যাবে কি একজন দর্শকের এমন প্রশ্নে জবাবে আব্দুল্লাহ আল নোমান বলেন , “ এই পাঁচটি সিটি কর্পোরেশন নির্বাচন দেশের পাঁচটি বড় বিভাগের প্রতিনিধিত্ব করছে । এছাড়া এখানকার ভোটার রা সবাই সচেতন । তারা"}, {"", "BIHARI", "काल में उनका हमला से बचे खाती एहिजा भाग के अइले आ भोजपुर नाम से नगर बसवले. एकरा बारे में विस्तार से जानकारी नीचे दीहल गइल बा. बाकिर आश्चर्यजनक रूप से मालवा के राजा भोज के बिहार आवे आ भोजपुर नगर बसावे आ चाहे भोजपुरी के साथे उनकर कवनो संबंध होखे के कवनो जानकारी भोपाल के भोज संस्थान आ चाहे मध्य प्रदेश के इतिहासकार लोगन के तनिको नइखे. हालांकि ऊ सब लोग एह बात के मानत बा कि एकरा बारे में अबहीं तकले मूर्ति बनवइलें. राजा भोज के जवना जगहा पऽ वाग्देवी के दर्शन भइल रहे, ओही स्थान पऽ एह मूर्ति के स्थापना कइल गइल. अब अगर एह मंदिर के एह शिलालेख के तस्वीर {पृष्ठ संख्या 33 पऽ प्रकाशित} रउआ धेयान से देखीं तऽ एकरा पऽ कैथी लिपि में -सीताराम- लिखल साफ लउकत बा. कैथी भोजपुरी के बहुत प्रचलित लिपि रहल बिया. एकरा बारे में कवनो शंका संदेह बिहार-यूपी के जानकार लोगन में नइखे. एल. एस. एस. वो माले के लिखल पढ़ीं "}, {"bg", "BULGARIAN", " а дума попада в състояние на изпитание ключовите думи с предсказана малко под то изискване на страниците за търсене в"}, {"", "CATALAN", "al final en un únic lloc nhorabona l correu electrònic està concebut com a eina de productivitat aleshores per què perdre el temps arxivant missatges per després intentar recordar on els veu desar i per què heu d eliminar missatges importants per l"}, {"", "CEBUANO", "Ang Sugbo usa sa mga labing ugmad nga lalawigan sa nasod. Kini ang sentro sa komersyo, edukasyon ug industriya sa sentral ug habagatang dapit sa kapupod-an. Ang mipadayag sa Sugbo isip ikapito nga labing nindot nga pulo sa , ang nag-inusarang pulo sa Pilipinas nga napasidunggan sa maong magasin sukad pa sa tuig"}, {"hr", "CROATIAN", "Posljednja dva vladara su Kijaksar {Κυαξαρης; 625-585 prije Krista}, fraortov sin koji će proširiti teritorij Medije i Astijag. Kijaksar je imao kćer ili unuku koja se zvala Amitis a postala je ženom Nabukodonosora II. kojoj je ovaj izgradio Viseće vrtove Babilona. Kijaksar je modernizirao svoju vojsku i uništio Ninivu 612. prije Krista. Naslijedio ga je njegov sin, posljednji medijski kralj, Astijag, kojega je detronizirao {srušio sa vlasti} njegov unuk Kir Veliki. Zemljom su zavladali Perzijanci."}, {"cs", "CZECH", " a akci opakujte film uložen vykreslit gmail tokio smazat obsah adresáře nelze načíst systémový profil jednotky smoot okud používáte pro určení polokoule značky z západ nebo v východ používejte nezáporné hodnoty zeměpisné délky nelze"}, {"da", "DANISH", " a z tallene og punktummer der er tilladte log ud angiv den ønskede adgangskode igen november gem personlige oplysninger kontrolspørgsmål det sidste tegn i dit brugernavn skal være et bogstav a z eller tal skriv de tegn du kan se i billedet nedenfor"}, {"nl", "DUTCH", " a als volgt te werk om een configuratiebestand te maken sitemap gen py ebruik filters om de s op te geven die moeten worden toegevoegd of uitgesloten op basis van de opmaaktaal elke sitemap mag alleen de s bevatten voor een bepaalde opmaaktaal dit"}, {"en", "ENGLISH", " a backup credit card by visiting your billing preferences page or visit the adwords help centre for more details https adwords google com support bin answer py answer hl en we were unable to process the payment of for your outstanding google adwords"}, {"et", "ESTONIAN", " a niipea kui sinu maksimaalne igakuine krediidi limiit on meie poolt heaks kiidetud on sinu kohustuseks see krediidilimiit"}, {"fi", "FINNISH", " a joilla olet käynyt tämä kerro meille kuka ä olet ei tunnistettavia käyttötietoja kuten virheraportteja käytetään google desktopin parantamiseen etsi näyttää mukautettuja uutisia google desktop keskivaihto leikkaa voit kaksoisnapsauttaa"}, {"fr", "FRENCH", " a accès aux collections et aux frontaux qui lui ont été attribués il peut consulter et modifier ses collections et exporter des configurations de collection toutefois il ne peut pas créer ni supprimer des collections enfin il a accès aux fonctions"}, {"", "GALICIAN", " debe ser como mínimo taranto tendas de venda polo miúdo cociñas servizos bordado canadá viaxes parques de vehículos de recreo hotel oriental habitación recibir unha postal no enderezo indicado anteriormente"}, {"", "GANDA", " abaana ba bani lukaaga mu ana mu babiri abaana ba bebayi lukaaga mu abiri mu basatu abaana ba azugaadi lukumi mu ebikumi bibiri mu abiri mu babiri abaana ba adonikamu lukaaga mu nltaaga mu mukaaga abaana ba biguvaayi enkumi bbiri mu ataano mu mukaaga"}, {"de", "GERMAN", " abschnitt ordner aktivieren werden die ordnereinstellungen im farbabschnitt deaktiviert öchten sie wirklich fortfahren eldtypen angeben optional n diesem schritt geben sie für jedesfeld aus dem datenset den typ an ieser schritt ist optional eldtypen"}, {"", "HAITIAN_CREOLE", " ak pitit tout sosyete a chita se pou sa leta dwe pwoteje yo nimewo leta fèt pou li pwoteje tout paran ak pitit nan peyi a menm jan kit paran yo marye kit yo pa marye tout manman ki fè pitit leta fèt pou ba yo konkoul menm jan tou pou timoun piti ak pou"}, {"he", "HEBREW", " או לערוך את העדפות ההפצה אנא עקוב אחרי השלבים הבאים כנס לחשבון האישי שלך ב"}, {"hi", "HINDI", " ं ऐडवर्ड्स विज्ञापनों के अनुभव पर आधारित हैं और इनकी मदद से आपको अपने विज्ञापनों का अधिकतम लाभ"}, {"", "HMONG", " Kuv hlub koj txawm lub ntuj yuav si ntshi nphaus los kuv tsis ua siab nkaug txawm ntiab teb yuav si ntshi nphaus los kuv tseem ua lon tsaug vim kuv hlub koj tag lub siab"}, {"hu", "HUNGARIAN", " a felhasználóim a google azonosító szöveget ikor látják a felhasználóim a google azonosító szöveget felhasználók a google azonosító szöveget fogják látni minden tranzakció után ha a vásárlását regisztrációját oldalunk"}, {"", "ICELANDIC", " a afköst leitarorða þinna leitarorð neikvæð leitarorð auglýsingahópa byggja upp aðallista yfir ný leitarorð fyrir auglýsingahópana og skoða ítarleg gögn um árangur leitarorða eins og samkeppni auglýsenda og leitarmagn er krafist notkun"}, {"id", "INDONESIAN", "berdiri setelah pengurusnya yang berusia 83 tahun, Fayzrahman Satarov, mendeklarasikan diri sebagai nabi dan rumahnya sebagai negara Islam Satarov digambarkan sebagai mantan ulama Islam tahun 1970-an. Pengikutnya didorong membaca manuskripnya dan kebanyakan dilarang meninggalkan tempat persembunyian bawah tanah di dasar gedung delapan lantai mereka. Jaksa membuka penyelidikan kasus kriminal pada kelompok itu dan menyatakan akan membubarkan kelompok kalau tetap melakukan kegiatan ilegal seperti mencegah anggotanya mencari bantuan medis atau pendidikan. Sampai sekarang pihak berwajib belum melakukan penangkapan meskipun polisi mencurigai adanya tindak kekerasan pada anak. Pengadilan selanjutnya akan memutuskan apakah anak-anak diizinkan tetap tinggal dengan orang tua mereka. Kazan yang berada sekitar 800 kilometer di timur Moskow merupakan wilayah Tatarstan yang"}, {"", "IRISH", " a bhfuil na focail go léir i do cheist le fáil orthu ní gá ach focail breise a chur leis na cinn a cuardaíodh cheana chun an cuardach a bheachtú nó a chúngú má chuirtear focal breise isteach aimseofar fo aicme ar leith de na torthaí a fuarthas"}, {"it", "ITALIAN", " a causa di un intervento di manutenzione del sistema fino alle ore circa ora legale costa del pacifico del novembre le campagne esistenti continueranno a essere pubblicate come di consueto anche durante questo breve periodo di inattività ci scusiamo per"}, {"", "JAVANESE", " account ten server niki kalian username meniko tanpo judul cacahe account nggonanmu wes pol pesen mu wes diguwak pesenan mu wes di simpen sante wae pesenan mu wes ke kirim mbuh tekan ora pesenan e ke kethok pesenan mu wes ke kirim mbuh tekan ora pesenan"}, {"", "KINYARWANDA", " dore ibyo ukeneye kumenya ukwo watubona ibibazo byinshi abandi babaza ububonero byibibina google onjela ho izina dyikyibina kyawe onjela ho yawe mulugo kulaho ibyandiko byawe shyilaho tegula yawe tulubaka tukongeraho iyanya mishya buliko tulambula"}, {"lv", "LATVIAN", " a gadskārtējā izpārdošana slēpošana jāņi atlaide izmaiņas trafikā kas saistītas ar sezonas izpārdošanu speciālajām atlaidēm u c ir parastas un atslēgvārdi kas ir populāri noteiktos laika posmos šajā laikā saņems lielāku klikšķu"}, {"lt", "LITHUANIAN", " a išsijungia mano idėja dėl geriausio laiko po pastarųjų savo santykių pasimokiau penki dalykai be kurių negaliu gyventi mano miegamajame tu surasi ideali pora išsilavinimas aukštoji mokykla koledžas universitetas pagrindinis laipsnis metai"}, {"mk", "MACEDONIAN", " гласовите коалицијата на вмро дпмне како партија со најмногу освоени гласови ќе добие евра а на сметката на коализијата за македонија"}, {"", "MALAY", "pengampunan beramai-ramai supaya mereka pulang ke rumah masing-masing. Orang-orang besarnya enggan mengiktiraf sultan yang dilantik oleh Belanda sebagai Yang DiPertuan Selangor. Orang ramai pula tidak mahu menjalankan perniagaan bijih timah dengan Belanda, selagi raja yang berhak tidak ditabalkan. Perdagang yang lain dibekukan terus kerana untuk membalas jasa beliau yang membantu Belanda menentang Riau, Johor dan Selangor. Di antara tiga orang Sultan juga dipandang oleh rakyat sebagai seorang sultan yang paling gigih. 1 | 2 SULTAN Sebagai ganti Sultan Ibrahim ditabalkan Raja Muhammad iaitu Raja Muda. Walaupun baginda bukan anak isteri pertama bergelar Sultan Muhammad bersemayam di Kuala Selangor juga. Pentadbiran baginda yang lemah itu menyebabkan Kuala Selangor menjadi sarang ioleh Cina di Lukut tidak diambil tindakan, sedangkan baginda sendiri banyak berhutang kepada 1"}, {"", "MALTESE", " ata ikteb messaġġ lil indirizzi differenti billi tagħżilhom u tagħfas il buttuna ikteb żid numri tfittxijja tal kotba mur print home kotba minn pagni ghal pagna minn ghall ktieb ta aċċessa stieden habib iehor grazzi it tim tal gruppi google"}, {"mr", "MARATHI", "हैदराबाद उच्चार ऐका {सहाय्य·माहिती}तेलुगू: హైదరాబాదు , उर्दू: حیدر آباد हे भारतातील आंध्र प्रदेश राज्याच्या राजधानीचे शहर आहे. हैदराबादची लोकसंख्या ७७ लाख ४० हजार ३३४ आहे. मोत्यांचे शहर अशी एकेकाळी ओळख असलेल्या या शहराला ऐतिहासिक, सांस्कृतिक आणि स्थापत्यशास्त्रीय वारसा लाभला आहे. १९९० नंतर शिक्षण आणि माहिती तंत्रज्ञान त्याचप्रमाणे औषधनिर्मिती आणि जैवतंत्रज्ञान क्षेत्रातील उद्योगधंद्यांची वाढ शहरात झाली. दक्षिण मध्य भारतातील पर्यटन आणि तेलुगू चित्रपटनिर्मितीचे हैदराबाद हे केंद्र आहे"}, {"ne", "NEPALI", "अरू ठाऊँबाटपनि खुलेको छ यो खाता अर अरू ठाऊँबाटपनि खुलेको छ यो खाता अर ू"}, {"no", "NORWEGIAN", " a er obligatorisk tidsforskyvning plassering av katalogsøk planinformasjon loggfilbane gruppenavn kontoinformasjon passord domene gruppeinformasjon alle kampanjesporing alternativ bruker grupper oppgaveplanlegger oppgavehistorikk kontosammendrag antall"}, {"fa", "PERSIAN", " آب خوردن عجله می کردند به جای باز ی کتک کاری می کردند و همه چيز مثل قبل بود فقط من ماندم و يک دنيا حرف و انتظار تا عاقبت رسيد احضاريه ی ای با"}, {"pl", "POLISH", " a australii będzie widział inne reklamy niż użytkownik z kanady kierowanie geograficzne sprawia że reklamy są lepiej dopasowane do użytkownika twojej strony oznacza to także że możesz nie zobaczyć wszystkich reklam które są wyświetlane na"}, {"pt", "PORTUGUESE", " a abit prevê que a entrada desses produtos estrangeiros no mercado têxtil e vestuário do brasil possa reduzir os preços em cerca de a partir de má notícia para os empresários que terão que lutar para garantir suas margens de lucro mas boa notícia"}, {"ro", "ROMANIAN", " a anunţurilor reţineţi nu plătiţi pentru clicuri sau impresii ci numai atunci când pe site ul dvs survine o acţiune dorită site urile negative nu pot avea uri de destinaţie daţi instrucţiuni societăţii dvs bancare sau constructoare să"}, // Language-Detection does not support cyrillic for romanaian //{"ro", "ROMANIAN", "оперативэ а органелор ши институциилор екзекутиве ши а органелор жудичиаре але путерий де стат фиекэруй орган ал путерий де стат и се"}, {"ru", "RUSSIAN", " а неправильный формат идентификатора дн назад"}, {"", "SCOTS_GAELIC", " air son is gum bi casg air a h uile briosgaid no gum faigh thu brath nuair a tha briosgaid a tighinn gad rannsachadh ghoogle gu ceart mura bheil briosgaidean ceadaichte cuiridh google briosgaid dha do neach cleachdaidh fa leth tha google a cleachdadh"}, {"", "SERBIAN", "балчак балчак на мапи србије уреди демографија у насељу балчак живи пунолетна становника а просечна старост становништва износи година"}, {"", "SERBIAN", "Društvo | četvrtak 1.08.2013 | 13:43 Krade se i izvorska voda Izvor: Gornji Milanovac -- U gružanskom selu Belo Polje prošle noći ukradeno je više od 10.000 litara kojima je obijen bazen. Bazen je bio zaključan i propisno obezbeđen."}, {"sk", "SLOVAK", " a aktivovať reklamnú kampaň ak chcete kampaň pred spustením ešte prispôsobiť uložte ju ako šablónu a pokračujte v úprave vyberte si jednu z možností nižšie a kliknite na tlačidlo uložiť kampaň nastavenia kampane môžete ľubovoľne"}, {"sl", "SLOVENIAN", " adsense stanje prijave za google adsense google adsense račun je bil začasno zamrznjen pozdravljeni hvala za vaše zanimanje v google adsense po pregledu vaše prijavnice so naši strokovnjaki ugotovili da spletna stran ki je trenutno povezana z vašim"}, {"es", "SPANISH", " a continuación haz clic en el botón obtener ruta también puedes desplazarte hasta el final de la página para cambiar tus opciones de búsqueda gráfico y detalles ésta es una lista de los vídeos que te recomendamos nuestras recomendaciones se basan"}, {"sw", "SWAHILI", " a ujumbe mpya jumla unda tafuta na angalia vikundi vya kujadiliana na kushiriki mawazo iliyopangwa kwa tarehe watumiaji wapya futa orodha hizi lugha hoja vishikanisho vilivyo dhaminiwa ujumbe sanaa na tamasha toka udhibitisho wa neno kwa haraka fikia"}, {"sv", "SWEDISH", " a bort objekt från google desktop post äldst meny öretag dress etaljer alternativ för vad är inne yaste google skrivbord plugin program för nyheter google visa nyheter som är anpassade efter de artiklar som du läser om du till exempel läser"}, {"tl", "TAGALOG", " a na ugma sa google ay nakaka bantog sa gitna nang kliks na nangyayari sa pamamagitan nang ordinaryong paggagamit at sa kliks na likha nang pandaraya o hindi tunay na paggamit bunga nito nasasala namin ang mga kliks na hindi kailangan o hindi gusto nang"}, {"tr", "TURKISH", " a ayarlarınızı görmeniz ve yönetmeniz içindir eğer kampanyanız için günlük bütçenizi gözden geçirebileceğiniz yeri arıyorsanız kampanya yönetimi ne gidin kampanyanızı seçin ve kampanya ayarlarını düzenle yi tıklayın sunumu"}, {"uk", "UKRAINIAN", " а більший бюджет щоб забезпечити собі максимум прибутків від переходів відстежуйте свої об яви за датою географічним розташуванням"}, {"ur", "URDU", " آپ کو کم سے کم ممکنہ رقم چارج کرتا ہے اس کی مثال کے طور پر فرض کریں اگر آپ کی زیادہ سے زیادہ قیمت فی کلِک امریکی ڈالر اور کلِک کرنے کی شرح ہو تو"}, {"vi", "VIETNAMESE", " adsense cho nội dung nhà cung cấp dịch vụ di động xác minh tín dụng thay đổi nhãn kg các ô xem chi phí cho từ chối các đơn đặt hàng dạng cấp dữ liệu ác minh trang web của bạn để xem"}, {"", "WELSH", " a chofrestru eich cyfrif ymwelwch a unwaith i chi greu eich cyfrif mi fydd yn cael ei hysbysu o ch cyfeiriad ebost newydd fel eich bod yn gallu cadw mewn cysylltiad drwy gmail os nad ydych chi wedi clywed yn barod am gmail mae n gwasanaeth gwebost"}, {"", "YIDDISH", "און פאנטאזיע ער איז באקאנט צים מערסטן פאר זיינע באַלאַדעס ער האָט געוווינט אין ווארשע יעס פאריס ליווערפול און לאנדאן סוף כל סוף איז ער"}, {"so", "SOMALI", " a oo maanta bogga koobaad ugu qoran yahey beesha caalamka laakiin si kata oo beesha caalamku ula guntato soomaaliya waxa aan shaki ku jirin in aakhirataanka dadka soomaalida oo kaliya ay yihiin ku soomaaliya ka saari kara dhibka ay ku jirto"}, {"", "IGBO", "Chineke bụ aha ọzọ ndï omenala Igbo kpọro Chukwu. Mgbe ndị bekee bịara, ha mee ya nke ndi Christian. N\'echiche ndi ekpere chi Omenala Ndi Igbo, Christianity, Judaism, ma Islam, Chineke nwere ọtụtụ utu aha, ma nwee nanị otu aha. Ụzọ abụọ e si akpọ aha ahụ bụ Jehovah ma Ọ bụ Yahweh. Na ọtụtụ Akwụkwọ Nsọ, e wepụla aha Chineke ma jiri utu aha bụ Onyenwe Anyị ma ọ bụ Chineke dochie ya. Ma mgbe e dere akwụkwọ nsọ, aha ahụ bụ Jehova pụtara n’ime ya, ihe dị ka ugboro pụkụ asaa{7,000}."}, {"", "HAUSA", " a cikin a kan sakamako daga sakwannin a kan sakamako daga sakwannin daga ranar zuwa a kan sakamako daga guda daga ranar zuwa a kan sakamako daga shafukan daga ranar zuwa a kan sakamako daga guda a cikin last hour a kan sakamako daga guda daga kafar"}, {"", "YORUBA", " abinibi han ikawe alantakun le ni opolopo ede abinibi ti a to lesese bi eniyan to fe lo se fe lati se atunse jowo mo pe awon oju iwe itakunagbaye miran ti ako ni oniruru ede abinibi le faragba nipa atunse ninu se iwadi blogs ni ori itakun agbaye ti e ba"}, {"", "ZULU", " ana engu uma inkinga iqhubeka siza ubike kwi isexwayiso ngenxa yephutha lomlekeleli sikwazi ukubuyisela emuva kuphela imiphumela engaqediwe ukuthola imiphumela eqediwe zama ukulayisha kabusha leli khasi emizuzwini engu uma inkinga iqhubeka siza uthumele"}, {"", "BOSNIAN", "Novi predsjednik Mešihata Islamske zajednice u Srbiji {IZuS} i muftija dr. Mevlud ef. Dudić izjavio je u intervjuu za Anadolu Agency {AA} kako je uvjeren da će doći do vraćanja jedinstva među muslimanima i unutar Islamske zajednice na prostoru Sandžaka, te da je njegova ruka pružena za povratak svih u okrilje Islamske zajednice u Srbiji nakon skoro sedam godina podjela u tom dijelu Srbije. Dudić je za predsjednika Mešihata IZ u Srbiji izabran 4. januara, a zvanična inauguracija će biti obavljena u prvoj polovini februara. Kako se očekuje, prisustvovat će joj i reisu-l-ulema Islamske zajednice u Srbiji Husein ef. Kavazović koji će i zvanično promovirati Dudića u novog prvog čovjeka IZ u Srbiji. Dudić će danas boraviti u prvoj zvaničnoj posjeti reisu Kavazoviću, što je njegov privi simbolični potez nakon imenovanja. "}, {"id", "INDONESIAN", "sukiyaki wikipedia indonesia ensiklopedia bebas berbahasa bebas berbahasa indonesia langsung ke navigasi cari untuk pengertian lain dari sukiyaki lihat sukiyaki irisan tipis daging sapi sayur sayuran dan tahu di dalam panci besi yang dimasak di atas meja makan dengan cara direbus sukiyaki dimakan dengan mence"}, {"", "MALAY", "sukiyaki wikipedia bahasa melayu ensiklopedia bebas sukiyaki dari wikipedia bahasa melayu ensiklopedia bebas lompat ke navigasi gelintar sukiyaki sukiyaki hirisan tipis daging lembu sayur sayuran dan tauhu di dalam periuk besi yang dimasak di atas meja makan dengan cara rebusan sukiyaki dimakan dengan mence"}, {"fr", "FRENCH", "A accès aux chiens et aux frontaux qui lui ont été il peut consulter et modifier ses collections et exporter Cet article concerne le pays européen aujourd’hui appelé République française. Pour d’autres usages du nom France, Pour une aide rapide et effective, veuiller trouver votre aide dans le menu ci-dessus."}, }; }
deezer/weslang
javatests/com/deezer/research/language/TestData.java
963
import java.util.ArrayList; import java.util.HashMap; import java.lang.Integer; public class OnlineRoom { private HashMap<Shop, Integer> totalLikes; private HashMap<Shop, Integer> totalSuperLikes; private CategoryList totalCategories; private ArrayList<String> roomCustomers; private Order finalOrder; public void mergeLikes(ArrayList<Shop> newLikes){ //Προσθέτει 1 like σε κάθε μαγαζί μέσα στο totalLikes που υπάρχει στο newLikes for (int i=0; i< newLikes.size();i++) { Shop key = newLikes.get(i); if (this.totalLikes.containsKey(key)) { Integer previousLikes = this.totalLikes.get(key); //this.totalLikes.replace(key, Integer(previousLikes.intValue()+1)); } else { //this.totalLikes.put(newLikes.get(i), Integer(1)); } } } }
iloudaros/nomnomr
code/app/src/main/java/OnlineRoom.java
974
// Κλάση που κάνει το parse των ημερομηνιών σε αντικείμενο DateRange package service; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Date; import javax.swing.JOptionPane; public class DateParser { private final SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd"); private String from; private String to; public DateParser(String from, String to) { this.from = from; this.to = to; } // Επιστρέφει το αντικείμενο DateRange, κάνοντας κάποιους έλεγχους ασφάλειας public DateRange get() { try { // Παίρνει τα δεδομένα από την φόρμα Date dateFrom = formatter.parse(from); Date dateTo = formatter.parse(to); // Έλεγχος αν είναι σωστές οι ημερομηνίες try { return new DateRange(dateFrom, dateTo); } catch (IllegalArgumentException e) { JOptionPane.showMessageDialog(null, e.getMessage(), "Σφάλμα", JOptionPane.INFORMATION_MESSAGE); return null; } } catch (ParseException e) { JOptionPane.showMessageDialog(null, e, "Σφάλμα", JOptionPane.INFORMATION_MESSAGE); return null; } } }
ikiranis/tzokerApp
src/service/DateParser.java
975
package model; import java.io.Serializable; import java.text.SimpleDateFormat; import java.util.Collection; import java.util.Date; import javax.persistence.Basic; import javax.persistence.CascadeType; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.Id; import javax.persistence.JoinColumn; import javax.persistence.ManyToOne; import javax.persistence.NamedQueries; import javax.persistence.NamedQuery; import javax.persistence.OneToMany; import javax.persistence.Table; import javax.persistence.Temporal; import javax.persistence.TemporalType; import javax.xml.bind.annotation.XmlRootElement; import javax.xml.bind.annotation.XmlTransient; @Entity @Table(name = "DRAW") @XmlRootElement @NamedQueries({ @NamedQuery(name = "Draw.findAll", query = "SELECT d FROM Draw d") , @NamedQuery(name = "Draw.findById", query = "SELECT d FROM Draw d WHERE d.id = :id") , @NamedQuery(name = "Draw.findByDrawDate", query = "SELECT d FROM Draw d WHERE d.drawDate = :drawDate") , @NamedQuery(name = "Draw.findByDrawDateRange", query = "SELECT d FROM Draw d WHERE (d.drawDate BETWEEN :drawFromDate AND :drawToDate) AND d.gameId=:gameId") , @NamedQuery(name = "Draw.findByColumns", query = "SELECT d FROM Draw d WHERE d.columns = :columns") }) public class Draw implements Serializable { private static final long serialVersionUID = 1L; @Id @Basic(optional = false) @Column(name = "ID") private Integer id; @Basic(optional = false) @Column(name = "DRAW_DATE") @Temporal(TemporalType.DATE) private Date drawDate; @Basic(optional = false) @Column(name = "COLUMNS") private int columns; @OneToMany(cascade = CascadeType.ALL, mappedBy = "drawId") private Collection<WinNumber> winNumberCollection; @OneToMany(cascade = CascadeType.ALL, mappedBy = "drawId") private Collection<Prize> prizeCollection; @JoinColumn(name = "GAME_ID", referencedColumnName = "ID") @ManyToOne(optional = false) private Game gameId; public Draw() { } public Draw(Integer id) { this.id = id; } public Draw(Integer id, Date drawDate, int columns) { this.id = id; this.drawDate = drawDate; this.columns = columns; } public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public Date getDrawDate() { return drawDate; } public void setDrawDate(Date drawDate) { this.drawDate = drawDate; } // Επιστρέφει την ημερομηνία σε... ανθρώπινη μορφή public String getFormatedDrawDate() { SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd"); return formatter.format(drawDate); } public int getColumns() { return columns; } public void setColumns(int columns) { this.columns = columns; } public Game getGameId() { return gameId; } public void setGameId(Game gameId) { this.gameId = gameId; } @XmlTransient public Collection<WinNumber> getWinNumberCollection() { return winNumberCollection; } public void setWinNumberCollection(Collection<WinNumber> winNumberCollection) { this.winNumberCollection = winNumberCollection; } @XmlTransient public Collection<Prize> getPrizeCollection() { return prizeCollection; } public void setPrizeCollection(Collection<Prize> prizeCollection) { this.prizeCollection = prizeCollection; } @Override public int hashCode() { int hash = 0; hash += (id != null ? id.hashCode() : 0); return hash; } @Override public boolean equals(Object object) { // TODO: Warning - this method won't work in the case the id fields are not set if (!(object instanceof Draw)) { return false; } Draw other = (Draw) object; if ((this.id == null && other.id != null) || (this.id != null && !this.id.equals(other.id))) { return false; } return true; } @Override public String toString() { return "model.Draw[ id=" + id + " drawDate=" + drawDate + " columns=" + columns + " winNumbers=" + winNumberCollection + " " + " prizeCategories=" + prizeCollection + "]"; } // Επιστρέφει τους αριθμούς σε ενιαίο string public String getNumbersInString() { String numbers = ""; for (WinNumber number : winNumberCollection) { if (number.getType() == '1') { numbers = numbers + number.getNumber() + " "; } else { numbers = numbers + "(" + number.getNumber() + ")"; } } return numbers; } }
ikiranis/tzokerApp
src/model/Draw.java
976
package com.ilearnrw.api.selectnextword.levels; /* * Copyright (c) 2015, iLearnRW. Licensed under Modified BSD Licence. See licence.txt for details. */ import ilearnrw.utils.LanguageCode; import java.util.List; import com.ilearnrw.api.selectnextword.GameElement; import com.ilearnrw.api.selectnextword.GameLevel; import com.ilearnrw.api.selectnextword.LevelParameters; import com.ilearnrw.api.selectnextword.WordSelectionUtils; public class TrainStationGR extends GameLevel { /** * * @author hector * * Levels configuration for train dispatcher * * prefix/suffix split the problem, syllables split the syllables * */ @Override public List<GameElement> getWords(LevelParameters parameters, int languageArea, int difficulty) { return WordSelectionUtils.getTargetWordsWithDistractors( LanguageCode.GR, languageArea, difficulty, parameters, -1, false, false); } @Override public int[] modeLevels(int languageArea, int difficulty) { LanguageAreasGR lA = LanguageAreasGR.values()[languageArea]; if((lA==LanguageAreasGR.SYLLABLE_DIVISION)) return new int[]{0};//Syllables else if(lA==LanguageAreasGR.PREFIXES) return new int[]{2};//Prefixes else return new int[]{1};//suffixes } @Override public boolean allowedDifficulty(int languageArea, int difficulty) { if(languageArea>=LanguageAreasGR.values().length) return false; LanguageAreasGR lA = LanguageAreasGR.values()[languageArea]; switch(lA){ case SYLLABLE_DIVISION://Consonants return true; case CONSONANTS://Consonants return false; case VOWELS://Vowels return false; case DERIVATIONAL://Blends and letter patterns return true;//true; case INFLECTIONAL://Syllables return true;//true; case PREFIXES://Suffixes return true;//true; case GP_CORRESPONDENCE://Prefixes return false; case FUNCTION_WORDS://Confusing letters return false; case LETTER_SIMILARITY: return false; default: return false; } } /* Instructions for the games */ public String instructions(int languageArea, int difficulty,LevelParameters param){ if(param.mode==0) return "Γράψε τις συλλαβές της λέξης σε ξεχωριστά βαγόνια"; else if(param.mode==1){ if(languageArea==6) return "Γράψε την κατάληξη της λέξης σε ξεχωριστό βαγόνι από την υπόλοιπη λέξη (π.χ. αγαπη-μένος)"; else if(languageArea==7) return "Γράψε την κατάληξη της λέξης σε ξεχωριστό βαγόνι από την υπόλοιπη λέξη (π.χ. αγαπη-μένος)"; }else if(param.mode==2) return "Γράψε το πρώτο μέρος της λέξης (π.χ. υπο-τιμώ) σε ξεχωριστά βαγόνια από την υπόλοιπη λέξη"; return "Not available"; } }
mpakarlsson/ilearnrw-service
src/main/java/com/ilearnrw/api/selectnextword/levels/TrainStationGR.java
979
/* * copyright 2013-2020 * codebb.gr * ProtoERP - Open source invocing program * [email protected] */ /* * Changelog * ========= * 29/12/2020 (georgemoralis) - fix issue in confirm dialog for updater * 13/10/2020 (georgemoralis) - Added UpdateSetting * 04/10/2020 (georgemoralis) - Initial commit */ package gr.codebb.protoerp.generic; import gr.codebb.dlg.AlertDlg; import gr.codebb.lib.util.WebUtil; import gr.codebb.protoerp.MainSettings; import gr.codebb.protoerp.settings.SettingsHelper; import java.awt.Desktop; import java.io.File; import java.io.IOException; import java.net.URI; import java.net.URISyntaxException; import java.net.URL; import java.util.ResourceBundle; import javafx.event.ActionEvent; import javafx.fxml.FXML; import javafx.fxml.Initializable; import javafx.scene.control.ButtonType; import javafx.scene.control.Label; import javafx.scene.web.WebEngine; import javafx.scene.web.WebView; import javafx.stage.Modality; import javafx.stage.Stage; import org.apache.commons.lang3.SystemUtils; public class UpdateInfoView implements Initializable { @FXML private Label oldVersionLabel; @FXML private Label newVersionLabel; @FXML private WebView webViewEngine; public void setVersions(String old, String newv) { oldVersionLabel.setText(old); newVersionLabel.setText(newv); WebEngine engine = webViewEngine.getEngine(); String version = newVersionLabel.getText().replace(".", "_"); String constructUrl = "https://deploy.codebb.gr/changelog/" + MainSettings.getInstance().getAppName() + "/" + version + ".html"; if (WebUtil.urlExists(constructUrl)) { engine.load(constructUrl); } else { engine.load( "https://deploy.codebb.gr/changelog/" + MainSettings.getInstance().getAppName() + "/generic.html"); } } @Override public void initialize(URL url, ResourceBundle rb) {} @FXML private void visitForum(ActionEvent event) { Desktop desktop = Desktop.getDesktop(); try { desktop.browse(new URI("https://forum.codebb.gr/")); } catch (URISyntaxException | IOException ex) { ex.printStackTrace(); } } @FXML private void updateNowButton(ActionEvent event) { ButtonType response = AlertDlg.create() .message( "Προσοχή! Η εκκίνηση της εφαρμογής θα τερματίσει το πρόγραμμα.\nΘέλετε να συνεχίσετε?") .title("Εκκίνηση εφαρμογής Update") .owner(webViewEngine.getScene().getWindow()) .modality(Modality.APPLICATION_MODAL) .showAndWaitConfirm(); if (response == ButtonType.OK) { if (SystemUtils.IS_OS_WINDOWS) { // support only for windows for now File f = new File(""); ProcessBuilder pb = new ProcessBuilder( "cmd", "/c", "start", "C:\\codebb\\updater\\updater.exe", "--application=" + MainSettings.getInstance().getAppName(), "--os=windows", "--platform=" + System.getProperty("os.arch"), "--applicationPath=\"" + f.getAbsolutePath() + "\""); pb.directory(new File("C:\\codebb\\updater")); try { Process process = pb.start(); } catch (IOException ex) { ex.printStackTrace(); } System.exit(0); } else { // OS is not windows AlertDlg.create() .type(AlertDlg.Type.ERROR) .message("Δεν υποστηρίζεται o updater σε άλλο περιβάλλον εκτός windows") .title("Πρόβλημα") .owner(null) .modality(Modality.APPLICATION_MODAL) .showAndWait(); } } } @FXML private void remindLaterButton(ActionEvent event) { Stage stage = (Stage) webViewEngine.getScene().getWindow(); stage.close(); } @FXML private void noUpdatesButton(ActionEvent event) { SettingsHelper.updateIntegerSetting("checkUpdates", 0); Stage stage = (Stage) webViewEngine.getScene().getWindow(); stage.close(); } }
georgemoralis/protoERP
src/main/java/gr/codebb/protoerp/generic/UpdateInfoView.java
984
/* * copyright 2013-2020 * codebb.gr * ProtoERP - Open source invocing program * [email protected] */ /* * Changelog * ========= * 29/12/2020 (georgemoralis) - fix issue in confirm dialog for backup * 13/10/2020 (georgemoralis) - Added checkforupdates option * 12/10/2020 (georgemoralis) - Added backup and update actions * 11/10/2020 (georgemoralis) - Added about button action * 04/10/2020 (georgemoralis) - Initial commit */ package gr.codebb.protoerp.generic; import static gr.codebb.lib.util.ThreadUtil.runAndWait; import com.jfoenix.controls.JFXHamburger; import com.jfoenix.transitions.hamburger.HamburgerNextArrowBasicTransition; import gr.codebb.ctl.CbbDetachableTabPane; import gr.codebb.dlg.AlertDlg; import gr.codebb.lib.util.FxmlUtil; import gr.codebb.lib.util.StageUtil; import gr.codebb.lib.util.WebUtil; import gr.codebb.protoerp.MainSettings; import gr.codebb.protoerp.about.AboutView; import gr.codebb.protoerp.settings.SettingsHelper; import gr.codebb.util.version.VersionUtil; import gr.codebb.webserv.rest.Util.Calls; import java.awt.Desktop; import java.io.File; import java.io.IOException; import java.net.URI; import java.net.URISyntaxException; import java.net.URL; import java.util.ResourceBundle; import java.util.concurrent.ExecutionException; import javafx.concurrent.Service; import javafx.concurrent.Task; import javafx.event.ActionEvent; import javafx.fxml.FXML; import javafx.fxml.Initializable; import javafx.scene.Scene; import javafx.scene.control.ButtonType; import javafx.scene.input.MouseEvent; import javafx.scene.layout.StackPane; import javafx.stage.Modality; import javafx.stage.Stage; import org.apache.commons.lang3.SystemUtils; import org.controlsfx.control.MasterDetailPane; public class MainAppView implements Initializable { @FXML private StackPane mainStackPane; @FXML private JFXHamburger hamburgermenu; @FXML private CbbDetachableTabPane mainDetachPane; HamburgerNextArrowBasicTransition hammenu; MasterDetailPane masterDetailPane; public CbbDetachableTabPane getMainDetachPane() { return mainDetachPane; } public void setMasterPane(MasterDetailPane masterDetailPane) { this.masterDetailPane = masterDetailPane; } /** * Initializes the controller class. * * @param url * @param rb */ @Override public void initialize(URL url, ResourceBundle rb) { hammenu = new HamburgerNextArrowBasicTransition(hamburgermenu); hammenu.setRate(-1); // check for updates service Service<Void> service = new Service<Void>() { @Override protected Task<Void> createTask() { return new Task<Void>() { @Override protected Void call() throws Exception { Thread.sleep(10000); checkForUpdates(true); return null; } }; } }; service.start(); } @FXML private void hamburgerMenuMouseClicked(MouseEvent event) { hammenu.setRate(hammenu.getRate() * -1); hammenu.play(); if (masterDetailPane.isShowDetailNode()) { masterDetailPane.setShowDetailNode(false); } else { masterDetailPane.setShowDetailNode(true); } } @FXML private void onBackupButtonPressed(ActionEvent event) { ButtonType response = AlertDlg.create() .message( "Προσοχή! Η εκκίνηση της εφαρμογής θα τερματίσει το πρόγραμμα.\nΘέλετε να συνεχίσετε?") .title("Εκκίνηση εφαρμογής Backup") .owner(masterDetailPane.getScene().getWindow()) .modality(Modality.APPLICATION_MODAL) .showAndWaitConfirm(); if (response == ButtonType.OK) { if (SystemUtils.IS_OS_WINDOWS) { // support only for windows for now File f = new File(""); ProcessBuilder pb = new ProcessBuilder( "cmd", "/c", "start", "C:\\codebb\\backup\\backup.exe", "--application=" + MainSettings.getInstance().getAppName(), "--applicationPath=\"" + f.getAbsolutePath() + "\""); pb.directory(new File("C:\\codebb\\backup")); try { Process process = pb.start(); } catch (IOException ex) { ex.printStackTrace(); } System.exit(0); } else { // OS is not windows AlertDlg.create() .type(AlertDlg.Type.ERROR) .message("Δεν υποστηρίζεται το backup σε άλλο περιβάλλον εκτός windows") .title("Πρόβλημα") .owner(null) .modality(Modality.APPLICATION_MODAL) .showAndWait(); } } } @FXML private void onUpdateButtonPressed(ActionEvent event) { Service<Void> service = new Service<Void>() { @Override protected Task<Void> createTask() { return new Task<Void>() { @Override protected Void call() throws Exception { checkForUpdates(false); return null; } }; } }; service.start(); } @FXML private void onHelpButtonPressed(ActionEvent event) { Desktop desktop = Desktop.getDesktop(); try { desktop.browse(new URI("https://codebb.gr/documentation/protoERP/protoERP.html")); } catch (URISyntaxException | IOException ex) { ex.printStackTrace(); } } @FXML private void onAboutButtonPressed(ActionEvent event) { FxmlUtil.LoadResult<AboutView> aboutWindow = FxmlUtil.load("/fxml/about/About.fxml"); Stage stage = StageUtil.setStageSettings( "Άδεια Χρήσης", new Scene(aboutWindow.getParent()), Modality.APPLICATION_MODAL, mainStackPane.getScene().getWindow(), null, "/img/protoerp.png"); stage.setResizable(false); stage.show(); } public void checkForUpdates(boolean startup) { String currentVersion = MainSettings.getInstance().getVersion(); System.out.println("version : " + currentVersion); if (!WebUtil.pingURL("https://clients.codebb.gr", 1000)) { if (!startup) { try { runAndWait( () -> { AlertDlg.create() .type(AlertDlg.Type.ERROR) .message( "Η υπηρεσία αναβαθμίσεων δεν είναι διαθέσιμη αυτή τη στιγμή.\nΔοκιμάστε αργότερα") .title("Πρόβλημα") .owner(mainDetachPane.getScene().getWindow()) .modality(Modality.APPLICATION_MODAL) .showAndWait(); }); } catch (InterruptedException | ExecutionException ex) { ex.printStackTrace(); } } return; // if not found URL then don't go further } else { System.out.println("webserv seems reachable."); } if (startup) { boolean checkforUpdates = SettingsHelper.loadIntegerSetting("checkUpdates") != 0; if (checkforUpdates) { String version_string = null; try { version_string = Calls.UpdaterRequest( "K8PBC-HTURS-BH5E9-2B039-56044", MainSettings.getInstance().getAppName()); } catch (IOException | InterruptedException ex) { ex.printStackTrace(); } if (version_string == null) { System.out.println("api call seems unreachable"); return; } System.out.println("webserv replies that the latest version is " + version_string); final String vfinal = version_string; if (VersionUtil.isComparedVersionNewer( MainSettings.getInstance().getVersion(), version_string)) { System.out.println("New version found"); try { runAndWait( () -> { FxmlUtil.LoadResult<UpdateInfoView> versionWindow = FxmlUtil.load("/fxml/generic/UpdateInfo.fxml"); versionWindow .getController() .setVersions(MainSettings.getInstance().getVersion(), vfinal); Stage stage = StageUtil.setStageSettings( "Νέα έκδοση!", new Scene(versionWindow.getParent()), Modality.APPLICATION_MODAL, mainStackPane.getScene().getWindow(), null, "/img/protoerp.png"); stage.setResizable(false); stage.show(); }); } catch (InterruptedException | ExecutionException ex) { ex.printStackTrace(); } } } else { System.out.println("check for updates disabled"); } } else { String version_string = null; try { version_string = Calls.UpdaterRequest( "K8PBC-HTURS-BH5E9-2B039-56044", MainSettings.getInstance().getAppName()); } catch (IOException | InterruptedException ex) { ex.printStackTrace(); } if (version_string == null) { System.out.println("webserv seems unreachable"); return; } final String vfinal = version_string; if (VersionUtil.isComparedVersionNewer( MainSettings.getInstance().getVersion(), version_string)) { System.out.println("New version found"); try { runAndWait( () -> { FxmlUtil.LoadResult<UpdateInfoView> versionWindow = FxmlUtil.load("/fxml/generic/UpdateInfo.fxml"); versionWindow .getController() .setVersions(MainSettings.getInstance().getVersion(), vfinal); Stage stage = StageUtil.setStageSettings( "Νέα έκδοση!", new Scene(versionWindow.getParent()), Modality.APPLICATION_MODAL, mainStackPane.getScene().getWindow(), null, "/img/protoerp.png"); stage.setResizable(false); stage.show(); }); } catch (InterruptedException | ExecutionException ex) { ex.printStackTrace(); } } else { System.out.println("version is up to date!"); try { runAndWait( () -> { AlertDlg.create() .type(AlertDlg.Type.INFORMATION) .message("Δεν υπάρχουν διαθέσιμες ενημερώσεις αυτή τη στιγμή") .title("Πληροφόρηση") .owner(mainDetachPane.getScene().getWindow()) .modality(Modality.APPLICATION_MODAL) .showAndWait(); }); } catch (InterruptedException | ExecutionException ex) { ex.printStackTrace(); } } } } }
georgemoralis/protoERP
src/main/java/gr/codebb/protoerp/generic/MainAppView.java
996
// Κλάση που υπολογίζει την πληρότητα των δεδομένων στην βάση // // Παράδειγμα χρήσης: // // DBCompleteness complete = new DBCompleteness(dateRange); // complete.calculate(); // String result = complete.getResult(); // package controller; import api.RangeDrawIdsApi; import java.util.ArrayList; import java.util.function.Consumer; import model.Draw; import service.DateRange; import service.FetchData; import service.SplittedDateRange; public class DBCompleteness { private final DateRange dateRange; private int numberOfDrawsInDB; private int numberOfDrawsInApi; private Consumer<Integer> worker; private String result; public String getResult() { return result; } public void setWorker(Consumer<Integer> worker) { this.worker = worker; } public int getNumberOfDrawsInDB() { return numberOfDrawsInDB; } public int getNumberOfDrawsInApi() { return numberOfDrawsInApi; } public DBCompleteness(DateRange dateRange) { this.dateRange = dateRange; } // Επιστρέφει τις κληρώσεις που γίνανε στο συγκεκριμένο διάστημα private int getSumOfDrawsInRange() { ArrayList<String> drawIds = new ArrayList<>(); int progress = 0; // Σπάει το range σε τρίμηνα SplittedDateRange splittedDateRange = new SplittedDateRange(dateRange); ArrayList<DateRange> dateRanges = splittedDateRange.getSplitted(); // Κάνει κλήσεις στο API για κάθε τρίμηνο και τα αποτελέσματα τα // περνάει στην λίστα drawIds for (DateRange range : dateRanges) { RangeDrawIdsApi api = new RangeDrawIdsApi(range); drawIds.addAll(api.getData()); // Επιστροφή στο worker του ποσοστού προόδου worker.accept(100 * (progress + 1) / dateRanges.size()); progress++; } return drawIds.size(); } // Επιστρέφει το string για εμφάνιση της πληρότητας στην βάση δεδομένων public void calculate() { FetchData fetch = new FetchData(); ArrayList<Draw> draws = fetch.getDrawsInRange(dateRange); numberOfDrawsInDB = draws.size(); if (draws.isEmpty()) { result = null; } numberOfDrawsInApi = getSumOfDrawsInRange(); double percentage = ((double) numberOfDrawsInDB / (double) numberOfDrawsInApi) * 100; result = "Υπάρχουν " + numberOfDrawsInDB + " εγγραφές στην βάση, από τις " + numberOfDrawsInApi + " που έχουν γίνει. Η πληρότητα στην βάση είναι: " + String.format("%.2f", percentage) + "%"; } }
ikiranis/tzokerApp
src/controller/DBCompleteness.java
1,008
// Υποκλάση που δημιουργεί γράφημα για τις συχνότητες εμφάνισης των αριθμών τζόκερ package controller; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import model.Draw; import model.WinNumber; import service.FetchData; import service.Utils; public class TzokersFreqGraph extends Graph { public TzokersFreqGraph() { super("Συχνότητα τζοκερς (5 πρώτοι)", "Εμφανίσεις", "Αριθμοί"); } // Αντλεί τα δεδομένα για τις συχνότητες εμφάνισης των αριθμών @Override public Map<Integer, Long> getData() { ArrayList<Draw> drawsInDB; List<WinNumber> numbersInDB = new ArrayList<>(); Map<Integer, Long> numbers = new HashMap<>(); // Άντληση των κληρώσεων στο συγκεκριμένο εύρος ημερομηνιών FetchData fetch = new FetchData(); drawsInDB = fetch.getDrawsInRange(getDateRange()); // Για κάθε κλήρωση παίρνει τους αριθμούς που έχουν κληρωθεί σε αυτή for (Draw draw : drawsInDB) { numbersInDB.addAll(draw.getWinNumberCollection()); } // Υπολογίζει τις εμφανίσεις του αριθμού for (int i = 1; i <= 20; i++) { numbers.put(i, (long) Utils.countOccurrences(numbersInDB, Integer.toString(i), '2')); } return Utils.sortNumbersByKey(numbers, 5); } }
ikiranis/tzokerApp
src/controller/TzokersFreqGraph.java
1,009
// Υποκλάση που δημιουργεί γράφημα για τις συχνότητες εμφάνισης των αριθμών package controller; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import model.Draw; import model.WinNumber; import service.FetchData; import service.Utils; public class NumbersFreqGraph extends Graph { public NumbersFreqGraph() { super("Συχνότητα αριθμών (5 πρώτοι)", "Εμφανίσεις", "Αριθμοί"); } // Αντλεί τα δεδομένα για τις συχνότητες εμφάνισης των αριθμών @Override public Map<Integer, Long> getData() { ArrayList<Draw> drawsInDB; List<WinNumber> numbersInDB = new ArrayList<>(); Map<Integer, Long> numbers = new HashMap<>(); // Άντληση των κληρώσεων στο συγκεκριμένο εύρος ημερομηνιών FetchData fetch = new FetchData(); drawsInDB = fetch.getDrawsInRange(getDateRange()); // Για κάθε κλήρωση παίρνει τους αριθμούς που έχουν κληρωθεί σε αυτή for(Draw draw : drawsInDB) { numbersInDB.addAll(draw.getWinNumberCollection()); } // Υπολογίζει τις εμφανίσεις του αριθμού for (int i = 1; i <= 45; i++) { numbers.put(i, (long) Utils.countOccurrences(numbersInDB, Integer.toString(i), '1')); } return Utils.sortNumbersByKey(numbers, 5); } }
ikiranis/tzokerApp
src/controller/NumbersFreqGraph.java
1,011
package com.example.skinhealthchecker; /** //Οντότητα με πληροφορίες για κάθε ελιά Οι πληροφορίες περιλαμβάνουν : double Diameter; // η διάμετρος mole double width;// υψος mole double height;// πλάτος mole double [][] morfology;//πινακας μορφολόγίας double [] morfology1;// αριστερή μορφολογία mole double [] morfology2;// δεξιά μορφολογία mole boolean Isbad =false;//αν δεν φαίνεται υγιής String mole; // η θέση της φωτογραφίας στο storage double colorcurves; //πόσες καμπύλες έχει το ιστόγραμμα String Name;// το όνομα του mole int PID;// σε πιο id προφίλ ανοίκει το mole int id;// το μοναδικό id του mole boolean BadBorder;//αν έχει κακή περίμετρο boolean HasAsymmetry;//αν έχει ασσυμετρία boolean Evolving; // αν εξελίσεται boolean DLD;// αν έχει ανέβει στον server Περιλαμβάνονται συναρτίσεις για την εγραφή και ανάγνωση των τιμών double Diameter; // the moles diameter   double width; // moles height   double height; // width of mole   double [] [] morphology; //moles morphology table   double [] morphology1; // left moles morphology   double [] morphology2; // right moles morphology   boolean Isbad = false; // if the mole does not look healthy   String mole; // the moles photo location   double colorcurves; // how many curves the histogram of mole has   String Name; // the name of the mole   int PID; // the id of profile the mole is set   int id; // the unique id of the mole   boolean BadBorder; // if it has a bad perimeter   boolean HasAsymmetry; // if it has asymmetry   boolean Evolving; // if it evolves   boolean DLD; // if it's upgraded to the server An object that manipulates the necessary information that the application must have eg Language: this object has information about the language that is active, PID: Active profile id PIDCOUnt: Last ganarated profile's s ididc: Last ganarated mole's id it Includes readings and writings function for the variables */ import org.json.JSONArray; import org.json.JSONObject; import org.opencv.core.*; import org.w3c.dom.Element; import org.xmlpull.v1.XmlSerializer; import java.io.StringWriter; import java.util.ArrayList; import java.util.Arrays; import java.util.List; public class Mole { double Diameter; double width; double height; double [][] morfology; double [] morfology1; double [] morfology2; boolean Isbad =false; String mole; double colorcurves; String Name; int PID; int id; boolean BadBorder; boolean HasAsymmetry; boolean Evolving; boolean DLD; // boolean IsLiquid = false; boolean HasBlood=false; boolean HasItch=false; boolean IsHard=false; boolean BadHistory=false; String Gender; //0 man 1 woman boolean InPain= false; int Age; // ID NAME AGE ITCH ISHARD INPAIN SEX REALWIDTH REALHIGTH EDGESPROBLEM COLORPROBLEM EDGESSIMILATIRY MORFOLOGY1 MORFOLOGY2 DIAMETER PHOTO // public Mole (int id1, String Name1,int Age1,boolean HasItch1,boolean InPain1,boolean ishard1,boolean HasBlood1, String Gender1, // double width1,double hight1, boolean BadBorder1,double colorcurves1, boolean HasAsymmetry1,boolean BadHistory1, // String morfology11,String morfology21 , double Diameter1, String mole1,Boolean isbad1){ public Mole (int id1, String Name1,boolean HasItch1,boolean ishard1,boolean HasBlood1,boolean InPain1, double width1,double height1, boolean BadBorder1,double colorcurves1, boolean HasAsymmetry1, String morfology11,String morfology21 , double Diameter1, String mole1,Boolean isbad1,int PID1 ,boolean DLD1,boolean Evolving1){ SetMorfologyAr(morfology11,morfology21); id= id1; Name= Name1; // Age= Age1; HasItch= HasItch1; InPain= InPain1; //Gender= Gender1; HasBlood =HasBlood1; width= width1;height = height1; BadBorder= BadBorder1; colorcurves = colorcurves1; HasAsymmetry= HasAsymmetry1; Diameter= Diameter1; mole= mole1; // BadHistory=BadHistory1; IsHard=ishard1; Isbad=isbad1; PID=PID1; DLD=DLD1; Evolving=Evolving1; } public Mole (){} /** public boolean GetIsLiquid ( ){ return IsLiquid; } public void SetIsLiquid (boolean in){ IsLiquid=in; } **/ public void SetDLD (boolean in){ DLD=in; } public boolean GetDLD ( ){ return DLD; } public void SetPID (int in){ PID=in; } public int GetPID ( ){ return PID; } public void SetIsbad (boolean in){ Isbad=in; } public boolean GetIsbad ( ){ return Isbad; } public void SetHasBlood (boolean in){ HasBlood=in; } public boolean GetInPain ( ){ return InPain; } public void SetInPain (boolean in){ InPain=in; } public boolean GetHasBlood ( ){ return HasBlood; } public void SetHasItch (boolean in){ HasItch=in; } public boolean GetHasItch ( ){ return HasItch; } public void SetIsHard (boolean in){ IsHard=in; } public boolean GetIsHard ( ){ return IsHard; } public void SetBadHistory (boolean in){ BadHistory=in; } public boolean GetBadHistory (Mole mol, DatabaseHandler db ){ Profile test =db.getProfile(mol.GetPID()); return test.GetHistory(); } public void SetGender (String in){ Gender=in; } public String GetGender ( ){ return Gender; } public void SetAge (int in){ Age=in; } public int GetAge ( ){ return Age; } public void SetEvolving (boolean in){ Evolving=in; } public boolean GetEvolving ( ){ return Evolving; } public void SetHasAsymmetry (boolean in){ HasAsymmetry=in; } public boolean GetHasAsymmetry ( ){ return HasAsymmetry; } public void SetBadBorder (boolean in){ BadBorder=in; } public boolean GetBadBorder ( ){ return BadBorder; } public void SetDiameter(double in){ Diameter=in; } public void SetMorfology(double in [][]){ morfology=in; } public void SetMole (String in){ mole=in; } public void SetColorCurve (double in) { colorcurves=in; } public void SetId(int in){ id=in; } public void SetName (String in){ Name=in; } public double GetDiameter(){ return Diameter; } public void SetWidth( double in){ width= in; } public void SetHeight(double in){ height=in; } public double GetWidth(){ return width; } public double Getheight(){ return height; } public void SetMorfologyAr(String in,String in1){ String[] lines = in.split(System.getProperty("line.separator")); String[] lines1 = in1.split(System.getProperty("line.separator")); morfology= new double[lines.length][2]; for(int i=0; i<lines.length; i++) { morfology[i][0]= Double.parseDouble(lines[i]); morfology[i][1]= Double.parseDouble(lines1[i]); } } public String GetMorfologyAr1(){ StringBuilder sb = new StringBuilder(); for (int i=0;i<morfology.length;i++) { String s=Double.toString(morfology[i][0]); sb.append(s); sb.append(System.getProperty("line.separator")); } return sb.toString(); } public String GetMorfologyAr2(){ StringBuilder sb = new StringBuilder(); for (int i=0;i<morfology.length;i++) { String s=Double.toString(morfology[i][1]); sb.append(s); sb.append(System.getProperty("line.separator")); } return sb.toString(); } public double [][] GetMorfology(){ return morfology; } public String GetMole (){ return mole; } public double GetColorCurve () { return colorcurves; } public int GetId(){ return id; } public String GetName (){ return Name; } }
litsakis/SkinHealthChecker
skinHealthChecker/src/main/java/com/example/skinhealthchecker/Mole.java
1,012
/** * Class used to construct the query for ChatGPT to process. * It contains information about our university, the questionnaire along with the users answers and a prompt from the user or a default question */ public class QueryBuilder { // Define a constant string for the university information final static String TEXT = "Σε ενα πανεπιστημιο υπαρχουν 8 τμηματα: " + "1) διεθνων ευρωπαικων και οικονομικων σπουδων, " + "2) οικονομικων επιστημων, " + "3) διοικητικης επιστημης και τεχνολογιας, " + "4) οργανωσης και διοικησης επιχειρησεων, " + "5) λογιστικης και χρηματοοικονομικης, " + "6) μαρκετινγκ και επικοινωνιας, " + "7) πληροφορικης, " + "8) στατιστικης. " + "Ενας μαθητης θελει να σπουδασει σε αυτο το πανεπιστημιο, αλλα δεν ξερει ποιο τμημα να διαλεξει. " + "Ο μαθητης απαντησε στο παρακατω ερωτηματολογιο οσων αφορα στις προτιμησεις του: "; //Define a default question for Chatgpt: choose a department based on answers final static String defaultQuestion = "Ποιο τμήμα να διαλέξει ο χρήστης;"; /** * Method that utilizes StringBuilder's append method to create one String containing everything that is needed in the query * * @param questions an array containing the questions of the questionnaire * @see Questions#createQuestionsOnly() * * @param answers an array containing the answers the user gave * @see User#answers * @see Gui#processAnswers() * * @param message the prompt at the end. If it's "" that means we want to ask the deafult question * @return the full String */ public static String query(String[] questions, String[] answers, String message) { // Initialize a StringBuilder to construct the final message StringBuilder builder = new StringBuilder(); // Append the university information builder.append(TEXT); // Append each question and its corresponding answer for (int i = 0; i < questions.length; i++) { builder.append(questions[i] + " "); builder.append(answers[i] + " "); } // Append an additional message if provided if (message != "") { builder.append(message); } else { builder.append(defaultQuestion + " "); } // Convert the StringBuilder to a String and return it String toChat = builder.toString(); return toChat; } }
CHATAUEB/ChatAUEB
QueryBuilder.java
1,015
//package Calculations; import java.util.ArrayList; import java.util.Arrays; import java.util.Scanner; import java.util.Timer; import java.util.concurrent.ThreadLocalRandom; ; public class Probabilities { public static void random() { int n,a,b; while(true) { try { Scanner in = new Scanner(System.in); System.out.print("please give me how many numbers:"); n= in.nextInt(); break; } catch(Exception e) { System.out.println("wrong iput of data!"); } } while(true) { try { do { Scanner in = new Scanner(System.in); System.out.println("Give me the interval of random numbers (only integers and first the smallest then the biggest)"); System.out.print("Smaller:"); a=in.nextInt(); System.out.print("Larger:"); b=in.nextInt(); }while(a>b); break; } catch(Exception e) { } } int [] numbers = new int[n]; int [] counter = new int[n]; // εισαγουμε τα δεδομενα μας με τυχαιο τροπο απο α εως β for(int i=0;i<n;i++) { numbers[i] = ThreadLocalRandom.current().nextInt(a,b+1); System.out.print(+numbers[i]+" "); } // System.out.println("\n"+Arrays.toString(numbers)); //ενας πινακας που μετραει ποσες φορες εμφανιζεται ο καθες αρθμος for (int i=0;i<n;i++) { for (int j=0;j<n;j++) { if (numbers[i]==numbers[j]) { counter[i]++; } } } // System.out.println(""+Arrays.toString(counter)); ArrayList<Integer> results1 = new ArrayList<>(); ArrayList<Integer> results2 = new ArrayList<>(); //βαζει τα αποτελεσματα σε 2 λιστες.μια για τους αριθμους μια για το ποσες φορες //και σβηνει τις διπλες τιμες for (int i=a;i<b+1;i++) { for (int j=0;j<n;j++) { if (i==numbers[j]) { results1.add(numbers[j]); results2.add(counter[j]); break; } } } // System.out.println("\n"+results1); // System.out.println(""+results2); ArrayList<Float> probability = new ArrayList<>(); // μια λιστα που εμφανιζει τις πιθανοτητες for (int i=0;i<results2.size();i++) { probability.add(i,(float)results2.get(i)*100/n); } //τυπωνει τα αποτελεσματα for(int i=0;i<results2.size();i++) { System.out.print("\nThe number "+results1.get(i)+" appears "+results2.get(i)+" times"+" with probability:"+probability.get(i)+"%"); } // System.out.println("\n"+probability); //ελεγχουμε ποιοι αριθμοί δεν υπαρχουνε στη λιστα!!! System.out.print("\n\n\n**those numbers don't exist: "); int k; for(int i=a;i<b+1;i++) { k=0; for (int j=0;j<results1.size();j++) { if (i!=results1.get(j)) { k=k+1; if(k==results1.size()) { System.out.print(+i+","); } } } } System.out.println(".So the probality is 0%"); } }
vmaurop/Math_is_fun
Probabilities.java
1,017
package api; import java.io.Serializable; import java.util.ArrayList; public class Movie implements Serializable { private String title, desc, category; private Boolean isOver18; private String actors; private User user; private int fyear, duration; private Double rating; private ArrayList<Double> ratings; private ArrayList<Review> reviews = new ArrayList<>(); public static ArrayList<Movie> moviesList = new ArrayList<>(); public Movie(Admin user, String title, String desc, Boolean isOver18, String category, int fyear, int duration, String actors, Double rating) { this.user = user; this.title = title; this.desc = desc; this.isOver18 = isOver18; this.category = category; this.fyear = fyear; this.duration = duration; this.actors = actors; this.rating = rating; this.ratings = new ArrayList<>(); this.ratings.add(rating); //Καθε φορα που δημιουργειτε μια ταινια αυτοματα αποθηκευεται σε αυτη την λιστα, ή οποια επειδη ειναι static ολα τα αντικειμενα εχουν προσβαση σε αυτη. Movie.moviesList.add(this); } public String getDescription(){ return desc; } public ArrayList<Review> getReviews(){ return reviews; } public String getTitle() {return title;} public String getDesc() {return desc;} public String getCategory() {return category;} public boolean getIsOver18() {return this.isOver18;} public String getActors(){return actors;} public int getFyear() {return fyear;} public int getDuration() {return duration;} public Double getRating() {return rating;} public void addReview(Review review){ this.reviews.add(review); // Re calculate the rating double sum = 0; for(Review rw : this.reviews){ sum = sum + rw.getRating(); } this.rating = this.rating / (this.reviews.size() + 1); } public static ArrayList<Movie> searchMovies(String title, String actorName, String minRanking, boolean isOver18, String selectedGenre) { ArrayList<Movie> matchingMovies = new ArrayList<>(); if(minRanking.isEmpty() && title.isEmpty() && actorName.isEmpty() && selectedGenre.equals("Select")){ return Movie.moviesList; } for(Movie movie : Movie.moviesList){ if( title.equalsIgnoreCase(movie.getTitle()) && isOver18 == movie.getIsOver18() && Double.parseDouble(minRanking) <= movie.getRating() && movie.getActors().contains(actorName) && movie.getCategory().equalsIgnoreCase(selectedGenre) ){ matchingMovies.add(movie); } } return matchingMovies; } }
billtsol/netflix-app
src/api/Movie.java
1,019
package gr.aueb.cf.ch4; /** * Demonstation. Declare, init chars. */ public class HelloChar { public static void main(String[] args) { char star = '*'; // Τα char σε '' char alpha = 'a'; char upperAlpha = 'A'; char dot = '.'; char bang = '!'; char EMPTY_SPACE = ' '; int hash = '#'; System.out.print((int) star); System.out.print(alpha); System.out.println(dot); System.out.println("Hash: =" + (char) hash); if (alpha > upperAlpha) { System.out.println("a is greater (greater ordinal) than A"); } else { System.out.println("A is greater than a"); } } }
MytilinisV/codingfactorytestbed
ch4/HelloChar.java
1,025
//ArtHistory.java package projectsiamoglou; public class ArtHistory //Περιγραφή Αρχαιολογικού Χώρου ως Αξιοθέατο { private String arthist_name; //όνομα δραστηριότητας π.χ. επίσκεψη σε Μουσείο private String arthist_type; //είδος π.χ. επίσκεψη, περίπατος, ξενάγηση private double arthist_distance; //απόσταση αρχαιολογικού χώρου από ξενοδοχείο private String arthist_place; //τοποθεσία αρχαιολογικού χώρου private String arthist_timetable; //Ωράριο λειτουργίας αρχαιολογικού χώρου private double arthist_cost; //Κόστος επίσκεψης αρχαιολογικού χώρου public ArtHistory(String arthist_name, String arthist_type, double arthist_distance, String arthist_place, String arthist_timetable, double arthist_cost) { this.arthist_name = arthist_name; this.arthist_type = arthist_type; this.arthist_distance = arthist_distance; this.arthist_place = arthist_place; this.arthist_timetable = arthist_timetable; this.arthist_cost = arthist_cost; } public ArtHistory() { } public String getArthist_name() { return arthist_name; } public void setArthist_name(String arthist_name) { this.arthist_name = arthist_name; } public String getArthist_type() { return arthist_type; } public void setArthist_type(String arthist_type) { this.arthist_type = arthist_type; } public double getArthist_distance() { return arthist_distance; } public void setArthist_distance(double arthist_distance) { this.arthist_distance = arthist_distance; } public String getArthist_place() { return arthist_place; } public void setArthist_place(String arthist_place) { this.arthist_place = arthist_place; } public String getArthist_timetable() { return arthist_timetable; } public void setArthist_timetable(String arthist_timetable) { this.arthist_timetable = arthist_timetable; } public double getArthist_cost() { return arthist_cost; } public void setArthist_cost(double arthist_cost) { this.arthist_cost = arthist_cost; } @Override public String toString() { return "ArtHistory{" + "arthist_name=" + arthist_name + ", arthist_type=" + arthist_type + ", arthist_distance=" + arthist_distance + ", arthist_place=" + arthist_place + ", arthist_timetable=" + arthist_timetable + ", arthist_cost=" + arthist_cost + '}'; } }
SiamoglouB/SMART-BUSINESS
src/ArtHistory.java
1,027
package api; import java.io.Serializable; import java.time.LocalDate; /** * Η κλάση αυτή αναπαριστά μια αξιολόγηση ενός καταλύματος * @author Anestis Zotos */ public class Evaluation implements Serializable { private String txt_eval; //αξιολόγηση σε μορφή κειμένου private double num_eval; //αξιολόγηση σε μορφή αριθμού private LocalDate curDate; //ημερομηνία τελευταίας(πιο πρόσφατης)αξιολόγησης //constructor public Evaluation(String txt,double num) { txt_eval=txt; num_eval=num; curDate=LocalDate.now(); } //empty constructor public Evaluation(){ curDate=LocalDate.now(); txt_eval=null; num_eval=0; } //getters public String getTxt_eval(){ return txt_eval; } public double getNum_eval(){ return num_eval; } //setters public void setTxt_eval(String s){ txt_eval=s; curDate=LocalDate.now(); } public void setNum_eval(double num){ num_eval=num; curDate=LocalDate.now(); } }
AnestisZotos/Accommodations-rating-platform
api/Evaluation.java
1,031
import java.util.ArrayList; import java.util.HashSet; /** * Η κλάση αυτή αποθηκεύει στη μνήμη τις συναλλαγές σε ένα σούπερ μάρκετ. * This class saves in memory all the transactions of a supermarket. * * @author Grigorios Tsoumakas */ public class Supermarket { ArrayList<Transaction> transactions = new ArrayList<>(); /** * Αυτή η μέθοδος αποθηκεύει μια συναλλαγή * This method saves a transaction * * @param t μια συναλλαγή , a transaction */ public void addTransaction(Transaction t) { transactions.add(t); } /** * Αυτή η μέθοδος επιστρέφει το πλήθος όλων των πωλήσεων ενός προϊόντος σε * όλες τις αποθηκευμένες συναλλαγές. * This method returns the total number of sales of a product from all saved transactions. * * @param product ένα προϊόν , a product * @return το πλήθος των πωλήσεων του προϊόντος, the total sales number */ public int getTotalSalesOfProduct(String product) { int total = 0; for (Transaction t : transactions) { total += t.getAmountOfProduct(product); } return total; } /** * Η μέθοδος αυτή επιστρέφει το πλήθος των μοναδικών προϊόντων που έχουν * βρεθεί σε συναλλαγές. * This method returns the number of unique products that have been found * in the transactions. * * @return Το πλήθος των μοναδικών προϊόντων, the total number of unique products */ public int uniqueProducts() { HashSet<String> unique = new HashSet<>(); for (Transaction t : transactions) { String[] products = t.getProducts(); for (String product : products) { unique.add(product); } } return unique.size(); } }
auth-csd-oop-2020/lab-advancedBehavior-Supermarket-solved
src/Supermarket.java
1,032
import java.io.BufferedReader; import java.io.FileReader; import java.io.IOException; import java.util.Random; /** * * Η Κλαση αυτη δημιουργει λογικη για το παιχνιδι Sudoku * * @author Alexandros Vladovitis,Stelios Verros */ public class SudokuLogic { final int SIZE_ARRAY = 81; private int[] array; private int[] arraySolver; private int[] arrayKiller; private String[] arrayKillerColours; private int rand; private boolean[] arraycheck; /** * Ο κατασκευαστης δημιουργει τους πινακες array(ο οποιος αποθηκευει τις επιλογες του χρηστη) * arraycheck(ο οποιος ελεγχει αν τα στοιχεια ειναι απο το αρχειο ή οχι)arraySolver(ο οποιος δεχεται * τις λυσεις του killer sudoku)arrayKiller(ο οποιος δεχεται τους αριθμους απο το αρχειο killer) * arrayKillerColours(ο οποιος δεχεται τα γραμματα του αρχειου killer ωστε να ξεχωριζει απο τους * υπολοιπους ιδιους αριθμους) * * @author Alexandros Vladovitis,Stelios Verros */ public SudokuLogic() { array = new int[SIZE_ARRAY]; arraycheck = new boolean[SIZE_ARRAY]; arraySolver=new int[SIZE_ARRAY]; arrayKiller=new int[SIZE_ARRAY]; arrayKillerColours=new String[SIZE_ARRAY]; for (int i = 0; i < SIZE_ARRAY; i++) { array[i] = -1; arraySolver[i]=-1; arrayKiller[i]=-1; } /* * Η checkMoveLine ελεγχει αν μπορει να μπει το item στην * θεση x που δεχεται ελεγχοντας μονο την γραμμη του πινακα * * @author Alexandros Vladovitis,Stelios Verros */ } public boolean checkMoveLine(int x, int item) { int line = x / 9; //ευρεση γραμμης int startLine = line * 9; int endLine = line * 9 + 8; for (int i = startLine; i <= endLine; i++) { if (item == array[i]) { return false; } } return true; } /** * Η checkMoveColumn ελεγχει αν μπορει να μπει το item στην * θεση x που δεχεται ελεγχοντας μονο την στηλη του πινακα * * @author Alexandros Vladovitis,Stelios Verros */ public boolean checkMoveColumn(int x, int item) { int startColumn = x % 9;//ευρεση στηλης int endColumn = 72 + startColumn; for (int i = startColumn; i <= endColumn; i += 9) { if (item == array[i]) { return false; } } return true; } /** * Η checkMoveBox ελεγχει αν μπορει να μπει το item στην * θεση x που δεχεται ελεγχοντας μονο την κουτακι του πινακα * * @author Alexandros Vladovitis,Stelios Verros */ public boolean checkMoveBox(int x, int item) { int column = x % 9; int line = x / 9; int box = (line / 3) + (column / 3) + (2 * (line / 3));// ευρεση τετραγωνακι int startBoxLine = ((box / 3) * 27) + (box % 3) * 3; int endBoxLine = startBoxLine + 2; for (int i = startBoxLine; i <= endBoxLine; i++) { for (int j = 0; j <= 18; j += 9) { if (item == array[i + j]) { return false; } } } return true; } /** * Η checkMove ελεγχει αν μπορει να μπει το item στην * θεση x που δεχεται ελεγχοντας ολο τον πινακα χρησιμοποιωντας και * τις προηγουμενες συναρτησεις * * @author Alexandros Vladovitis,Stelios Verros */ public boolean checkMove(int x, int item) { return checkMoveBox(x, item) && checkMoveColumn(x, item) && checkMoveLine(x, item); } /** * Η addMove προσθετει το στοιχεο στον πινακα εφοσον μπορει να μπει το item στην * θεση x που δεχεται ελεγχοντας αν εδωσε σωστο αριθμο και ειναι αδειο το κελι * * @author Alexandros Vladovitis,Stelios Verros */ public void addMove(int x, int item) { if (checkItem(item) && checkEmptyBox(x)) { array[x] = item; } } /** * Η checkEmptyBox ελεγχει αν το κελι στην θεση χ ειναι αδειο και εφοσον ειναι = με -1 * (δηλαδη ειναι αδειο λογω αρχικοποιησης)τοτε γυρναει true * * @author Alexandros Vladovitis,Stelios Verros */ public boolean checkEmptyBox(int x) { //ελεχει αν εχει μπει στο κουτι αριθμος αν εχει μπει δεν σε αφηνει να το αλλαξεις return array[x] == -1; } /** * Η checkEmptyBox ελεγχει αν το item ειναι απο 1-9 * * @author Alexandros Vladovitis,Stelios Verros */ public boolean checkItem(int item) { return item > 0 && item < 10; } /** * Η checkPuzzle ελεγχει αν το κελι του πινακα ειναι απο το αρχειο ή οχι * και εφοσον ειναι δεν επιδεχεται αλλαγη αρα επιστρεφει false * * @author Alexandros Vladovitis,Stelios Verros */ public void checkPuzzle(){ for(int i=0;i<SIZE_ARRAY;i++){ arraycheck[i]= array[i] == -1; } } /** * Η removeMove ελεγχει αν το κελι του πινακα ειναι απο το αρχειο ή οχι * και εφοσον δεν ειναι το αφαιρει * * @author Alexandros Vladovitis,Stelios Verros */ public void removeMove(int x) { if(arraycheck[x]) array[x] = -1; } /** * Η TheEndOfTheGame ελεγχει αν εχουν συμπληρωθει ολα τα κελια του πινακα * και αν ναι επιστεφει true * * @author Alexandros Vladovitis,Stelios Verros */ public boolean TheEndOfTheGame() { int sum = 0; for (int i = 0; i < SIZE_ARRAY; i++) { if (array[i] != -1) { sum += 1; } } return sum == 81; } /** * Η GameResult ελεγχει χρησιμοποιωντας την προηγουμενη συναρτηση αν το αθροισμα * στηλων και γραμμων ειναι 405 αντοιστοιχα ωστε να επιστεψει true για να τελειωσει το παιχνιδι * * @author Alexandros Vladovitis,Stelios Verros */ public boolean GameResult() { if (TheEndOfTheGame() ) { int sumLine = 0;//βρισκω το sum για καθε γραμμη for (int i = 0; i < SIZE_ARRAY; i += 9) { for (int j = i; j <= i + 8; j++) { sumLine += array[j]; } } int sumColumn = 0;//βρισκω το sum για καθε στηλη for (int i = 0; i < 9; i++) { for (int j = i; j < SIZE_ARRAY; j += 9) { sumColumn += array[j]; } } return sumColumn == 405 && sumLine == 405; } return false; } public int[] getArray() { return array; } public boolean[] getArraycheck(){return arraycheck;} /** * Η addMoveKiller προσθετει τον αριθμο του αρχειου στον πινακα arrayKiller * και το γραμμα c στο arrayKillerColours ωστε να ξεχωριζει απο τα αλλους παρομοιους αριθμους * * @author Alexandros Vladovitis,Stelios Verros */ public void addMoveKiller(int x,int item,String c) { arrayKiller[x]=item; arrayKillerColours[x]=c; } public int[] getArrayKiller() { return arrayKiller; } public String[] getArrayKillerColours() { return arrayKillerColours; } /** * Η addMoveSolver προσθετει τον αριθμο του αρχειου Solver στον πινακα arrayKillerSolver * ωστε να ελεχθει η λυση * * @author Alexandros Vladovitis,Stelios Verros */ public void addMoveSolver(int x,int item){ arraySolver[x]=item; } /** * Η puzzle αρχικα δημιουργει ενα random στοιχειο ωστε να διαβασει απο τα 10 αρχεια ενα αρχειο * στην τυχη καθε φορα και μετα διαβαζει εναν εναν τον χαρακτηρα του text και καθε φορα * που ο χαρακτηρας ειναι τελεια(δηλαδη στο unicode =46)τοτε ανεβαζει το sum(που ειναι η θεση στον πινακα) * και αν δεν ειναι τελεια τοτε βαζει την κινηση στον πινακα χρησιμοποιωντας την addMove * * @author Alexandros Vladovitis,Stelios Verros */ public void puzzle() { try { Random rand = new Random(); int randomSudoku = rand.nextInt(10); randomSudoku++; FileReader in = new FileReader("sudoku_" + randomSudoku + ".txt"); int c; int sum = 0; while ((c = in.read()) != -1) { char c1 = (char) c; if (c1 != 46) { int item = c1 - 48; addMove(sum, item); } sum++; } } catch (IOException e) { System.out.println(e); } checkPuzzle(); } /** * Η puzzleKillerSolver χρησιμοποιει το ιδιο rand με την συναρτηση puzzleKiller ωστε να ταιριαξει τα txt files * και περναει την κινηση στην addMoveSolver * * @author Alexandros Vladovitis,Stelios Verros */ public void puzzleKillerSolver() { try { BufferedReader in = new BufferedReader(new FileReader("killer_sudoku_solve_" + rand +".txt")); String l; int sum = 0; while ((l = in.readLine()) != null) { int result = Integer.parseInt(l); addMoveSolver(sum,result); sum++; } } catch (IOException e) { System.out.println(e); } } /** * Η puzzleKillerSolver χρησιμοποιει ενα rand ωστε να παρει τυχαι ενα killer sudoku txt file * και χρησιμοποιωντας τα string και τις συναρτησεις valueof και charAt ξεχωριζουμε τους αριθμους με * τα γραμματα και αντιστοιχα τα περναμε στις αντοιστιχες συναρτησεις * * @author Alexandros Vladovitis,Stelios Verros */ public void puzzleKiller() { try { Random rand1 = new Random(); int randomSudoku1 = rand1.nextInt(10); randomSudoku1++; rand=randomSudoku1; BufferedReader in = new BufferedReader(new FileReader("killer_sudoku_"+ rand + ".txt")); String l; int sum=0; while ((l = in.readLine()) != null) { String c=""; StringBuilder number= new StringBuilder(); int len=l.length(); for(int i=0;i<len;i++) if (i== (len-1)){ c= String.valueOf((l.charAt(len-1))); }else number.append(String.valueOf((l.charAt(i)))); int result = Integer.parseInt(number.toString()); addMoveKiller(sum,result,c); sum++; } } catch (IOException e) { System.out.println(e); } } /** * Η FinishKiller ελεχγει τον πινακα arraySolver των λυσεων και τον πινακα array των επιλογων του * χρηστη ωστε να επιστρεψει true για να τερματισει το παιχνιδι * * @author Alexandros Vladovitis,Stelios Verros */ public boolean FinishKiller(){ int sum=0; for(int i=0;i<SIZE_ARRAY;i++){ if(arraySolver[i]==array[i]) sum++; } return sum == 81; } }
alexvlad14/sudokuGames
src/SudokuLogic.java
1,033
import java.util.ArrayList; import java.util.HashSet; /** * Η κλάση αυτή αποθηκεύει στη μνήμη τις συναλλαγές σε ένα σούπερ μάρκετ. * This class saves in memory all the transactions of a supermarket. * * @author Grigorios Tsoumakas */ public class Supermarket { ArrayList<Transaction> transactions = new ArrayList<>(); /** * Αυτή η μέθοδος αποθηκεύει μια συναλλαγή * This method saves a transaction * * @param t μια συναλλαγή , a transaction */ public void addTransaction(Transaction t) { transactions.add(t); } /** * Αυτή η μέθοδος επιστρέφει το πλήθος όλων των πωλήσεων ενός προϊόντος σε * όλες τις αποθηκευμένες συναλλαγές. * This method returns the total number of sales of a product from all saved transactions. * * @param product ένα προϊόν. A product * @return το πλήθος των πωλήσεων του προϊόντος. The total sales number */ public int getTotalSalesOfProduct(String product) { int total = 0; for (Transaction t : transactions) { total += t.getAmountOfProduct(product); } return total; } /** * Η μέθοδος αυτή επιστρέφει το πλήθος των μοναδικών προϊόντων που έχουν * βρεθεί σε συναλλαγές. * This method returns the number of unique products that have been found * in the transactions. * * @return Το πλήθος των μοναδικών προϊόντων. The total number of unique products */ public int uniqueProducts() { HashSet<String> unique = new HashSet<>(); for (Transaction t : transactions) { String[] products = t.getProducts(); for (String product : products) { unique.add(product); } } return unique.size(); } }
auth-csd-oop-2023/lab-advancedBehavior-Supermarket-solved
src/Supermarket.java
1,034
import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; /** * Η κλάση αυτή αφορά μια συναλλαγή ενός πελάτη με ένα supermarket. Με άλλα * λόγια αντιπροσωπεύει το καλάθι με τα προϊόντα που αγόρασε σε μια επίσκεψη. * This class represents a transaction of a super market customer. In other words, * the basket with the products of a visit to the supermarket. * * @author Grigorios Tsoumakas */ public class Transaction { private HashMap<String, Integer> items; public Transaction() { // συμπληρώστε τον κώδικα items = new HashMap<>(); } /** * Η μέθοδος αυτή αντιστοιχεί στο σκανάρισμα ενός προϊόντος και άρα στην * προσθήκη του στην τρέχουσα συναλλαγή ενός πελάτη. * This method represents the scanning process in a supermarket. It adds the product * to the current transaction. * * @param product συμβολοσειρά με το όνομα του προϊόντος, π.χ. γάλα, string containing the name of * the product e.g. milk */ public void scanItem(String product) { // συμπληρώστε τον κώδικα scanItems(product, 1); } /** * Η μέθοδος αυτή αντιστοιχεί στο σκανάρισμα πολλών προϊόντων του ίδιου * είδους και προσθήκη τους στην τρέχουσα συναλλαγή ενός πελάτη. * * This method represents the scanning of the same product multiple times * and adds them to the customers transactions. * * @param product συμβολοσειρά με το όνομα του προϊόντος, π.χ. γάλα, string containing the name of * the product e.g. milk * @param amount ποσότητα προϊόντος, the amount of the products */ public void scanItems(String product, int amount) { // συμπληρώστε τον κώδικα if (items.containsKey(product)) { items.put(product, items.get(product)+amount); } else { items.put(product, amount); } } /** * Η μέθοδος αυτή επιστρέφει τo πλήθος εμφάνισης ενός προϊόντος στο * καλάθι ενός πελάτη. * The number of times a product appears in the basket. * * @param product συμβολοσειρά με το όνομα του προϊόντος, π.χ. γάλα, string containing the name of * the product e.g. milk */ public int getAmountOfProduct(String product) { if (items.containsKey(product)) { return items.get(product); } else { return 0; } // συμπληρώστε τον κώδικα } /** * Η μέθοδος αυτή επιστέφει έναν πίνακα με τα ονόματα των προϊόντων που * υπάρχουν στο καλάθι του πελάτη. Αν το ίδιο προϊόν υπάρχει πάνω από μία * φορές στο καλάθι, θα πρέπει στον επιστρεφόμενο πίνακα να εμφανίζεται μία * φορά μόνο. * * This method returns a table with the names of the products that exist in the basket. * The returning table should not contain duplicate items and each product should appear only once. * * @return ο πίνακας με τα ονόματα των προϊόντων, the table with the names of the products purchased. */ public String[] getProducts() { String[] products = new String[items.size()]; Iterator<String> it = items.keySet().iterator(); for (int i=0; i<products.length; i++) { products[i] = it.next(); } return products; } }
auth-csd-oop-2020/lab-advancedBehavior-Supermarket-solved
src/Transaction.java
1,035
package api; import java.io.Serializable; import java.util.ArrayList; /** * Η κλάση αυτή αφορά τις παροχές που προσφέρουν τα καταλύματα. */ public class Utility implements Serializable { private ArrayList<String> specifics; //λίστα συμβολοσειρών με τις παροχές public Utility() { specifics = new ArrayList<>(); } /** * Η μέθοδος αυτή προσθέτει μια καινούρια παροχή αν δεν υπάρχει ήδη. * @param somethingNew Η νέα παροχή. * @return True αν έγινε επιτυχώς η προσθήκη της νέας παροχής, false διαφορετικά. */ public boolean addSpecificUtility(String somethingNew) { if (!specifics.isEmpty()) { if (specifics.contains(somethingNew)) { return false; } } specifics.add(somethingNew); return true; } /** * Η μέθοδος αυτή αφαιρεί μια παροχή. * @param toRemove Η παροχή που πρόκειται να διαγραφεί. * @return True αν η παροχή υπήρχε και αφαιρέθηκε, false διαφορετικά. */ public boolean removeSpecificUtility(String toRemove) { if (!specifics.isEmpty()) { if (specifics.contains(toRemove)) { specifics.remove(toRemove); return true; } } return false; } /** * Επιστρέφει τις συγκεκριμένες παροχές του αντικειμένου. Δηλαδή, αν το παρών αντικείμενο είναι Utility view, τότε * η λίστα specifics θα περιλαμβάνει "Θέα σε θάλασσα", "Θέα στο λιμάνι" κτλ. * @return τη λίστα των συγκεκριμένων παροχών */ public ArrayList<String> getSpecifics() { return specifics; } }
patiosga/myreviews
src/api/Utility.java
1,036
import java.util.HashMap; import java.util.Iterator; /** * Η κλάση αυτή αφορά μια συναλλαγή ενός πελάτη με ένα supermarket. Με άλλα * λόγια αντιπροσωπεύει το καλάθι με τα προϊόντα που αγόρασε σε μια επίσκεψη. * This class represents a transaction of a super market customer. In other words, * the basket with the products of a visit to the supermarket. * * @author Grigorios Tsoumakas */ public class Transaction { private HashMap<String, Integer> items; public Transaction() { items = new HashMap<>(); } /** * Η μέθοδος αυτή αντιστοιχεί στο σκανάρισμα ενός προϊόντος και άρα στην * προσθήκη του στην τρέχουσα συναλλαγή ενός πελάτη. * This method represents the scanning process in a supermarket. It adds the product * to the current transaction. * * @param product συμβολοσειρά με το όνομα του προϊόντος, π.χ. γάλα. String containing the name of * the product e.g. milk */ public void scanItem(String product) { scanItems(product, 1); } /** * Η μέθοδος αυτή αντιστοιχεί στο σκανάρισμα πολλών προϊόντων του ίδιου * είδους και προσθήκη τους στην τρέχουσα συναλλαγή ενός πελάτη. * <p> * This method represents the scanning of the same product multiple times * and adds them to the customers transactions. * * @param product συμβολοσειρά με το όνομα του προϊόντος, π.χ. γάλα. String containing the name of * the product e.g. milk * @param amount ποσότητα προϊόντος. The amount of the products */ public void scanItems(String product, int amount) { if (items.containsKey(product)) { items.put(product, items.get(product) + amount); } else { items.put(product, amount); } } /** * Η μέθοδος αυτή επιστρέφει τo πλήθος εμφάνισης ενός προϊόντος στο * καλάθι ενός πελάτη. * The number of times a product appears in the basket. * * @param product συμβολοσειρά με το όνομα του προϊόντος, π.χ. γάλα. String containing the name of * the product e.g. milk */ public int getAmountOfProduct(String product) { //return items.getOrDefault(product, 0); if (items.containsKey(product)) { return items.get(product); } else { return 0; } } /** * Η μέθοδος αυτή επιστέφει έναν πίνακα με τα ονόματα των προϊόντων που * υπάρχουν στο καλάθι του πελάτη. Αν το ίδιο προϊόν υπάρχει πάνω από μία * φορές στο καλάθι, θα πρέπει στον επιστρεφόμενο πίνακα να εμφανίζεται μία * φορά μόνο. * <p> * This method returns a table with the names of the products that exist in the basket. * The returning table should not contain duplicate items and each product should appear only once. * * @return ο πίνακας με τα ονόματα των προϊόντων. The table with the names of the products purchased. */ public String[] getProducts() { String[] products = new String[items.keySet().size()]; Iterator<String> it = items.keySet().iterator(); for (int i = 0; i < products.length; i++) { products[i] = it.next(); } return products; // String[] products = new String[items.keySet().size()]; // return items.keySet().toArray(products); } }
auth-csd-oop-2023/lab-advancedBehavior-Supermarket-solved
src/Transaction.java
1,038
import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.IOException; import java.net.Socket; import java.util.HashMap; public class ServerThread extends Thread{ private Socket clientSocket; private DataInputStream inputFromClient; private DataOutputStream outputToClient; private HashMap<Integer, Account> allAccounts; private HashMap<Integer, Message> allMessages; public ServerThread(Socket clientSocket, HashMap<Integer, Account> allAccounts, HashMap<Integer, Message> allMessages){ try{ this.clientSocket=clientSocket; this.allAccounts= allAccounts; this.allMessages= allMessages; inputFromClient= new DataInputStream(this.clientSocket.getInputStream()); outputToClient= new DataOutputStream(this.clientSocket.getOutputStream()); }catch (IOException e){ System.err.println("Error: No Connection" +"\n" + e.getMessage()); } } /** * Στη μεταβλητή dataFromClient αποθηκεύεται το αίτημα του client. Στον πρώτο χαρακτήρα είναι αποθηκευμένος ένας αριθμός από το 1 έως το 6, ο οποίος αντιστοιχεί σε κάποια λειτουργία που θέλει να εκτελέσει ο client. * Αυτός ο αριθμός αποθηκεύεται στη μεταβλητή functionID. Ανάλογα με την τιμή του functionID καλείται μία διαφορετική συνάρτηση, που η κάθε μία παίρνει ως όρισμα την υπόλοιπη συμβολοσειρά της dataFromClient * Τα αποτελέσματα των συναρτήσεων επιστρέφονται ως απάντηση στον client * */ public void run(){ try{ String dataFromClient= inputFromClient.readUTF(); String functionId= dataFromClient.charAt(0)+""; dataFromClient=dataFromClient.substring(1); if(functionId.equals("1")){ outputToClient.writeInt(createAccount(dataFromClient)); } else if(functionId.equals("2")){ outputToClient.writeUTF(showAccounts(dataFromClient)); } else if(functionId.equals("3")){ outputToClient.writeInt(sendMessage(dataFromClient)); } else if(functionId.equals("4")){ outputToClient.writeUTF(showInbox(dataFromClient)); } else if(functionId.equals("5")){ outputToClient.writeUTF(readMessage(dataFromClient)); } else if(functionId.equals("6")){ outputToClient.writeInt(deleteMessage(dataFromClient)); } }catch (IOException e){ System.err.println("Error: " + e.getMessage()); } finally { try{ clientSocket.close(); }catch (IOException e){ System.err.println("Error" + e.getMessage()); } } } /** * Η συνάρτηση createAccount αποτελεί την πρώτη λειτουργία - functionID=1 - * Σε αυτή την περίπτωση, στο String dataFromClient θα υπάρχει μόνο το username * Αρχικά, ελέγχεται αν το username ανήκει σε κάποιον άλλο χρήστη. Αν ανήκει, τότε η συνάρτηση επιστρέφει την τιμή -1 * Έπειτα, ελέγχονται όλοι οι χαρακτήρες του username, ώστε να διαπιστωθεί αν υπάρχουν μη-έγκυροι χαρακτήρες. Αν υπάρχουν, τότε η συνάρτηση επιστρέφει την τιμή -2 * Τέλος, δημιουργείται ένα νέο account και η συνάρτηση επιστρέφει το authToken του χρήστη */ private int createAccount(String dataFromClient){ String newUsername= dataFromClient; for(Account account: allAccounts.values()){ if( account.getUsername().equals(newUsername)) return -1; } char character; for(int i=0;i<newUsername.length();i++){ character=newUsername.charAt(i); if(!( (character>='a' && character<='z') || (character>='A' && character<='Z') || (character>='0' && character<='9') || character=='_') ) return -2; } int newAuthToken= Server.getAuthToken(); Account account= new Account(newUsername, newAuthToken); allAccounts.put(newAuthToken, account); return newAuthToken; } /** * Η συνάρτηση showAccounts αποτελεί τη δεύτερη λειτουργία - functionID=2 - * Σε αυτή την περίπτωση, στο dataFromClient θα υπάρχει μόνο το authToken ενός χρήστη. * Αρχικά, ελέγχεται αν το authToken αντιστοιχεί σε κάποιον χρήστη. * Αν ανήκει, τότε η συνάρτηση επιστρέφει όλα τα username των χρηστών * αλλιώς επιστρέφει ένα String που αναφέρει ότι το authToken δεν ανήκει σε κάποιον χρήστη **/ private String showAccounts(String dataFromClient){ int authToken= Integer.parseInt(dataFromClient); if(allAccounts.get(authToken)==null){ return "Invalid Auth Token"; } String temp=""; int i=0; for(Account account: allAccounts.values()){ temp+= ++i +". " + account.getUsername() + "\n"; } return temp; } /** * Η συνάρτηση sendMessage αποτελεί την τρίτη λειτουργία - functionID=3 - * Σε αυτή την περίπτωση στο dataFromClient θα υπάρχει ένα String της μορφής: authToken^recipient.length()^recipient^messageBody * * Αρχικά, ελέγχεται αν το authToken αντιστοιχεί σε κάποιον χρήστη. Αν δεν υπάρχει, τότε η συνάρτηση επιστρέφει την τιμή: 2 * ενώ αν υπάρχει τότε στη μεταβλητή sender αποθηκεύεται ο συγκεκριμένος χρήστης * Έπειτα, ελέγχεται αν υπάρχει χρήστης με username ίδιο με αυτό της μεταβλητής recipient. Αν δεν υπάρχει η συνάρτηση επιστρέφει την τιμή: 1, * Αλλιώς δημιουργείται και στέλνεται το μήνυμα και η συνάρτηση επιστρέφει την τιμή 0 */ private int sendMessage(String dataFromClient){ String tempAuthToken=""; int authToken; String recipient=""; String tempRecipient=""; int tempRecipient2; String messageBody=""; int i; for(i=0;dataFromClient.charAt(i)!='^';i++){ tempAuthToken+=dataFromClient.charAt(i)+""; } authToken=Integer.parseInt(tempAuthToken); for(i++;dataFromClient.charAt(i)!='^';i++){ tempRecipient+=dataFromClient.charAt(i); } tempRecipient2=Integer.parseInt(tempRecipient); for(i++;tempRecipient2>0;i++){ recipient+=dataFromClient.charAt(i); tempRecipient2--; } messageBody=dataFromClient.substring(i+1); Account sender= allAccounts.get(authToken); if(sender==null) return 2; Account receiver=null; for(Account account : allAccounts.values()){ if(account.getUsername().equals(recipient)){ receiver= account; } } if(receiver==null){ return 1; } int messId= Server.getMessageId(); Message message= new Message(sender.getUsername(), receiver.getUsername(), messageBody, messId); allMessages.put(messId, message); receiver.addMessage(message); return 0; } /** * Η συνάρτηση showInbox αποτελεί την τέταρτη λειτουργία - functionID=4 - * Σε αυτή την περίπτωση στο dataFromClient θα υπάρχει μόνο το authToken ενός χρήστη * Αν αντιστοιχεί σε κάποιον χρήστη, τότε η συνάρτηση θα επιστρέφει ένα String με όλα τα εισερχόμενα μηνύματα του χρήστη * αλλιώς, θα επιστρέφει ένα String που να αναφέρει ότι το authToken δεν ανήκει σε κάποιον χρήστη */ private String showInbox(String dataFromClient){ int authToken= Integer.parseInt(dataFromClient); Account account= allAccounts.get(authToken); if(account==null){ return "Invalid Auth Token"; } String answer=""; for(Message message: account.getMessageBox()){ answer+= message.getMessageId() +". from: " + message.getSender(); if(!message.getIsRead()) answer+="*"; answer+="\n"; } return answer; } /** * Η συνάρτηση readMessage αποτελεί την πέμπτη λειτουργία - functionID=5 - * Σε αυτή την περίπτωση στο dataFromClient θα υπάρχει ένα String της μορφής: authToken^messageId * Αρχικά, ελέγχεται αν το authToken αντιστοιχίζεται σε κάποιον χρήστη * Αν δεν υπάρχει, τότε η συνάρτηση επιστρέφει to String "2" * Αν υπάρχει, τότε ελέγχεται αν το messageId υπάρχει και αν ανήκει στα εισερχόμενά του. * Αν όχι, τότε η συνάρτηση επιστρέφει το String "1" * Αλλιώς, χρησιμοποιείται η συνάρτηση messageRead, ώστε να ενημερωθεί η κατάσταση του μηνύματος * και στέλνεται στον client ένα String, που ο πρώτος χαρακτήρας είναι το '0', ακολουθεί το username του αποστολέα μέσα σε παρενθέσεις και έπειτα το μήνυμα */ private String readMessage(String dataFromClient){ String tempAuthToken=""; int authToken; int messageId; int i; for(i=0;dataFromClient.charAt(i)!='^';i++){ tempAuthToken+=dataFromClient.charAt(i); } authToken=Integer.parseInt(tempAuthToken); messageId= Integer.parseInt(dataFromClient.substring(i+1)); Account account= allAccounts.get(authToken); if(account==null) return "2"; Message message= allMessages.get(messageId); if(message==null || !message.getReceiver().equals(account.getUsername())) return "1"; message.messageRead(); return "0" + "(" + message.getSender() + ")" + message.getBody(); } /** * Η συνάρτηση deleteMessage αποτελεί την έκτη λειτουργία - functionID=6 - * Σε αυτή την περίπτωση στο dataFromClient θα υπάρχει ένα String της μορφής: authToken^messageId * Αρχικά, ελέγχεται αν το authToken αντιστοιχίζεται σε κάποιον χρήστη * Αν δεν υπάρχει, τότε η συνάρτηση επιστρέφει την τιμή 2 * Αν υπάρχει, τότε ελέγχεται αν το messageId υπάρχει και αν ανήκει στα εισερχόμενά του. * Αν όχι, τότε η συνάρτηση επιστρέφει την τιμή 1 * Αλλιώς, το μήνυμα διαγράφεται και η συνάρτηση επιστρέφει την τιμή 0 */ private int deleteMessage(String dataFromClient){ String tempAuthToken=""; int authToken; int messageId; int i; for(i=0;dataFromClient.charAt(i)!='^';i++){ tempAuthToken+=dataFromClient.charAt(i); } authToken=Integer.parseInt(tempAuthToken); messageId= Integer.parseInt(dataFromClient.substring(i+1)); Account account= allAccounts.get(authToken); if(account==null) return 2; Message message= allMessages.get(messageId); if(message==null || !message.getReceiver().equals(account.getUsername())) return 1; allMessages.remove(messageId); for(i=0;i<account.getMessageBox().size();i++){ if(account.getMessageBox().get(i).getMessageId()==messageId) account.getMessageBox().remove(i); } return 0; } }
kefthymic/Client-Server
src/ServerThread.java
1,039
package api; import java.io.Serializable; import java.util.ArrayList; import java.util.HashSet; /** * Η κλάση αυτή αφορά τους παρόχους καταλυμάτων. */ public class Provider extends User implements Serializable { /** * Συνολικές αξιολογήσεις καταλύματος. Πρέπει να ενημερώνεται κάθε φορά που προστίθεται ή αφαιρείται αξιολόγηση */ private int totalRatings; private float avgRatingOfAllAccom; /** * Κατασκευαστής της κλάσης Provider. Αρχικοποιεί το αντικείμενο του παρόχου θέτοντας τα πεδία firstName, lastName, * username και password ανάλογα με τα ορίσματα που δίνονται αξιοποιώντας τον κατασκευαστή της abstract * κλάσης User. Επίσης, αρχικοποιούνται η μέση βαθμολογία των καταλυμάτων του παρόχου και ο συνολικός αριθμός των * αξιολογήσεων τους στο 0. * @param firstName μικρό όνομα παρόχου * @param lastName επίθετο παρόχου * @param userName username παρόχου * @param password κωδικός χρήστης * @param type τύπος χρήστη --> provider */ public Provider(String firstName,String lastName,String userName, String password, String type) { super(firstName,lastName,userName, password, type); totalRatings = 0; avgRatingOfAllAccom = 0; } /** * Υπολογίζει τη μέση βαθμολογία όλων των καταλυμάτων του παρόχου. Χρησιμοποιείται όταν προστίθεται νέα αξιολόγηση * σε κατάλυμα του παρόχου. * @param evaluations Η λίστα όλων των αξιολογήσεων για όλα τα καταλύματα */ public void updateAvgRatingOfAllAccom(ArrayList<Evaluation> evaluations) { //πρέπει να καλείται μετά τη μέθοδο που ενημερώνει το κατάλυμα μετά από προσθήκη ή αφαίρεση αξιολόγησης if (evaluations.size() == 0) { avgRatingOfAllAccom = 0; totalRatings = 0; return; } float totalSum = 0; int numOfEvaluations = 0; for (Evaluation evaluation : evaluations) { if (evaluation.getAccommodation().getProvider().equals(this)) { totalSum += evaluation.getGrade(); numOfEvaluations++; } } if (numOfEvaluations == 0) { avgRatingOfAllAccom = 0; totalRatings = 0; return; } totalRatings = numOfEvaluations; avgRatingOfAllAccom = totalSum / numOfEvaluations; } /** * Η μέθοδος αυτή επιστρέφει τη μέση βαθμολογία όλων των καταλυμάτων του παρόχου. * @return μέση βαθμολογία όλων των καταλυμάτων του παρόχου. */ public float getAvgRatingOfAllAccom() { return avgRatingOfAllAccom; } /** * Η μέθοδος αυτή επιστρέφει τον συνολικό βαθμό των αξιολογήσεων των καταλυμάτων του παρόχου. * @return συνολικός βαθμός αξιολογήσεων των καταλυμάτων του παρόχου. */ public int getTotalRatings() { return totalRatings; } }
patiosga/myreviews
src/api/Provider.java
1,040
package api; import java.io.Serializable; import java.util.ArrayList; /** * Αυτή η κλάση αναπαριστά έναν πάροχο και κληρονομεί όλα τα χαρακτηριστικά του γενικού χρήστη. * @author Χρήστος Θεοφυλακτίδης */ public class Provider extends GeneralUser implements Serializable { /** * Κατασκευαστής όπου δέχεται ως ορίσματα το όνομα, το επίθετο, το Username και τον κωδικό του παρόχου και αρχικοποιεί * μια λίστα με τα καταλύματα που ανήκουν στον πάροχο. * @param name Το όνομα του παρόχου * @param surname Το επίθετο του παρόχου * @param username Το username του παρόχου * @param password Ο κωδικός του παρόχου */ public Provider(String name, String surname, String username, String password){ super(name,surname,username,password,"Provider"); } /** * Κατασκευαστής όπου δημιουργεί έναν πάροχο και παίρνει ως παράμετρο την κλάση γονέα του, GeneralUser * @param g το αντικείμενο GeneralUser το οποίο μετατρέπεται σε πάροχο. */ public Provider(GeneralUser g){ super(g.getName(),g.getSurname(),g.getUsername(),g.getPassword(),g.getUserType()); } /** * Αυτή η μέθοδος δέχεται ως όρισμα ένα κατάλυμα και το προσθέτει στη λίστα με τα καταλύματα. * @param a Ένα κατάλυμα */ public void addAccommodation(Accommodation a){ ArrayList<Accommodation> accommodationsDB = (ArrayList<Accommodation>)FileInteractions.loadFromBinaryFile("src/files/accommodations.bin"); accommodationsDB.add(a); FileInteractions.saveToBinaryFile("accommodations.bin",accommodationsDB); } /** * Αυτή η μέθοδος τροποποιεί ένα ήδη υπάρχον κατάλυμα του πάροχου. * @param a Το κατάλυμα το οποίο τροποποιείται * @param name το όνομα του καταλύματος * @param type το είδος του καταλύματος * @param address η διεύθυνση του καταλύματος * @param city η πόλη στην οποία βρίσκεται το κατάλυμα * @param postalCode ο ταχυδρομικός κώδικας του καταλύματος * @param description Η περιγραφή του καταλύματος * @param listOfAmenities Η λίστα με τα είδη παροχών τα οποία προσφέρει το κατάλυμα */ public void editAccommodation(Accommodation a,String name, String type, String address, String city, String postalCode, String description, ArrayList<String> listOfAmenities){ ArrayList<Accommodation> accommodationsDB = (ArrayList<Accommodation>) FileInteractions.loadFromBinaryFile("src/files/accommodations.bin"); removeAccommodation(a); a.editAccommodation(name,type,address,city,postalCode,description,listOfAmenities); accommodationsDB.add(a); FileInteractions.saveToBinaryFile("accommodations.bin",accommodationsDB); } /** * Μέθοδος που αφαιρεί ενα κατάλυμα απο τη λίστα των καταλυμάτων. * @param a Το κατάλυμα το οποίο αφαιρείται */ public void removeAccommodation(Accommodation a){ ArrayList<Accommodation> accommodationsDB = (ArrayList<Accommodation>) FileInteractions.loadFromBinaryFile("src/files/accommodations.bin"); for(Accommodation accom : accommodationsDB){ for (Review r : accom.getListOfReviews()){ r.delete(); } } accommodationsDB.remove(a); } /** * Μέθοδος επιστροφής του αριθμού καταλυμάτων που ανήκουν στον πάροχο. * @return αριθμού καταλυμάτων του παρόχου */ public int getNumberOfAccommodations(){ return getListOfAccommodations().size(); } /** * Μέθοδος επιστροφής του συνόλου αξιολογήσεων όλων των καταλυμάτων του παρόχου. * @return του σύνολο αξιολογήσεων όλων των καταλυμάτων του παρόχου */ public int numberOfTotalReviews(){ int sum = 0; for(Accommodation a:getListOfAccommodations()){ sum+=a.getNumberOfReviews(); } return sum; } /** * Μέθοδος επιστροφής όλων των καταχωρήσεων καταλυμάτων του παρόχου. * @return λίστα με τα καταλύματα του παρόχου */ public ArrayList<Accommodation> getListOfAccommodations() { ArrayList<Accommodation> accommodationsDB = (ArrayList<Accommodation>) FileInteractions.loadFromBinaryFile("src/files/accommodations.bin"); ArrayList<Accommodation> list = new ArrayList<>(); for (Accommodation a : accommodationsDB){ if (a.getOwner().equals(getUsername())){ list.add(a); } } return list; } /** * Η μέση βαθμολογία απο όλα τα καταλύματα του παρόχου. * @return τη μέση βαθμολογία απο όλα τα καταλύματα του παρόχου. */ public float averageRating(){ float sum = 0; if(getNumberOfAccommodations()==0){ return 0; } int count =0; for(Accommodation a:getListOfAccommodations()){ if(a.getAverageRating()!=0){ sum+=a.getAverageRating(); count+=1; } } if(count==0){ return 0; } return sum/(float)count; } }
dallasGeorge/reviewsApp
src/api/Provider.java
1,041
package api; import java.io.Serializable; /** * Η κλάση αυτή αφορά την τοποθεσία κάποιου καταλύματος και περιλαμβάνει την πόλη, τη διεύθυνση και τον Τ.Κ. */ public class Location implements Serializable { private String address; private String town; private String postCode; /** * Κατασκευαστής της κλάσης της τοποθεσίας. Αρχικοποιεί τα πεδία address, town και postCode σύμφωνα με το ορίσματα * που δίνονται. Πριν την κλήση του κατασκευαστή ελέγχεται αν ο Τ.Κ. που δίνεται ως συμβολοσειρά είναι όντως * αριθμός μεγαλύτερος του μηδενός * @param address Διεύθυνση * @param town Πόλη * @param postCode Ταχυδρομικός κώδικας */ public Location(String address, String town, String postCode) { this.address = address; this.town = town; this.postCode = postCode; } /** * Επιστρέφει τη διεύθυνση της τοποθεσίας * @return διεύθυνση */ public String getAddress() { return address; } /** * Αλλάζει τη διεύθυνση σε όποια συμβολοσειρά δίνεται ως όρισμα * @param address νέα διεύθυνση */ public void setAddress(String address) { this.address = address; } /** * Επιστρέφει το όνομα της πόλης της τοποθεσίας * @return όνομα πόλης */ public String getTown() { return town; } /** * Αλλάζει το όνομα της πόλης σε όποια συμβολοσειρά δίνεται ως όρισμα. * @param town νέο όνομα πόλης */ public void setTown(String town) { this.town = town; } /** * Επιστρέφει τον ταχυδρομικό κώδικα της τοποθεσίας * @return Τ.Κ. */ public String getPostCode() { return postCode; } /** * Αλλάζει τον Τ.Κ. σε όποια συμβολοσειρά δίνεται ως όρισμα. * @param postCode νέος Τ.Κ. */ public void setPostCode(String postCode) { this.postCode = postCode; } }
patiosga/myreviews
src/api/Location.java
1,042
package logic; import java.util.ArrayList; import java.util.Random; import java.util.Collections; import java.util.List; /** * * Αυτή η κλάση χειρίζεται το σύνολο των γύρων. Περιέχει μία λίστα από * αντικείμενα τύπου Round και μεθόδους ώστα να φορτώνει με τυχαίο τρόπο όσους * γύρους της ζητηθεί και στην συνέχεια να τους εκτελεί. * * @author thanasis * @author tasosxak * @since 9/11/16 * @version 1.0 */ public class RoundList { private List<String> roundTypes; private List<Round> rounds; private int numRounds; private int numOfPlayers; private int currentRoundId = 0; private final int numRoundTypes; /** * * Ο κενός κατασκευαστής */ public RoundList(int numOfPlayers) { this(6, numOfPlayers); } /** * * Αυτός ο κατασκευαστής ορίζει τους τύπους των γύρων του παιχνιδιού και * γεμίζει τη λίστα με τους γύρους. * * @param numRounds Το πλήθος των γύρων που θέλουμε σε ένα παιχνίδι * @param numOfPlayers */ public RoundList(int numRounds, int numOfPlayers) { if (numOfPlayers <= 0 || numRounds <= 0) { numRounds = 6; numOfPlayers = 1; } rounds = new ArrayList<>(); roundTypes = new ArrayList<>(); roundTypes.add("CorrectAnswerRound"); roundTypes.add("CountDownRound"); roundTypes.add("BetRound"); if (numOfPlayers > 1) { roundTypes.add("FastAnswerRound"); roundTypes.add("ThermometerRound"); } numRoundTypes = roundTypes.size(); this.numRounds = numRounds; this.numOfPlayers = numOfPlayers; loadRounds(); } /** * * Αυτή η μέθοδος φορτώνει όσους γύρους απαιτούνται για το παιχνίδι * (numRounds). Εξασφαλίζει να μην ξαναεμφανιστεί ο ίδιος τύπος γύρου αν δεν * έχουν παιχτεί όλοι οι τύποι γύρων. */ private void loadRounds() { List<Integer> randomRoundTypeIds = new ArrayList<>(); List<Integer> temp = new ArrayList<>(); int roundsLeft = numRounds; long seed; /* Δημιουργία του πίνακα randomRoundTypeIds που έχει τυχαίους αριθμόυς (id) που αντιστοιχούν σε τύπους γύρων. Το μέγεθός του είναι όσο και το πλήθος των γύρων που έχει δοθεί στον κατασκευαστή της RoundList (numRounds). Ο πίνακας αυτός δημιουργείται ώστε να μην εμφανίζεται ένας τύπος γύρου δύο φορές χωρίς να έχουν εμφανιστεί όλοι οι υπόλιποι τύποι γύρων. */ while (roundsLeft != 0) { for (int i = 0; i < numRoundTypes; i++) { temp.add(i); } seed = System.nanoTime(); Collections.shuffle(temp, new Random(seed)); int limit = Math.min(roundsLeft, numRoundTypes); for (int i = 0; i < limit; i++) { randomRoundTypeIds.add(temp.get(i)); } temp.clear(); roundsLeft -= limit; } // Φόρτωση των γύρων με τη σειρά που ορίζεται από τον πίνακα randomRoundTypeIds for (Integer rand : randomRoundTypeIds) { loadOneRound(rand); } } /** * * Αυτός ο κατασκευαστής ορίζει τους τύπους των γύρων του παιχνιδιού και * γεμίζει τη λίστα με τους γύρους. * * @param myRoundTypeId Το id του τύπου γύρου που θέλουμε να φορτώσουμε στην * λίστα (πχ 0 -> CorrectAnswerRound, 1 -> BetRound). */ private void loadOneRound(int myRoundTypeId) { String myRoundType = roundTypes.get(myRoundTypeId); switch (myRoundType) { case "CorrectAnswerRound": CorrectAnswerRound caRound = new CorrectAnswerRound(); rounds.add(caRound); break; case "BetRound": List<String> bet_options = new ArrayList<>(); bet_options.add("250"); bet_options.add("500"); bet_options.add("750"); bet_options.add("1000"); BetRound bRound = new BetRound(bet_options); rounds.add(bRound); break; case "CountDownRound": CountDownRound cdRound = new CountDownRound(); rounds.add(cdRound); break; case "FastAnswerRound": List<Integer> bonuses = new ArrayList<>(); bonuses.add(1000); bonuses.add(500); FastAnswerRound faRound = new FastAnswerRound(bonuses); rounds.add(faRound); break; case "ThermometerRound": ThermometerRound thRound = new ThermometerRound(numOfPlayers); rounds.add(thRound); break; default: break; } } /** * * @return Επιστρέφει true αν υπάρχει και άλλος γύρος για να παιχτεί, αλλιώς * false. */ public boolean hasNext() { return currentRoundId < numRounds; } /** * * @return Επιστρέφει το αντικείμενο Round που αντιστοιχεί στον επόμενο * γύρο. */ public Round getNextRound() { if (this.hasNext()) { return rounds.get(currentRoundId++); } else { return null; } } public int getNumOfRounds() { return numRounds; } }
TeamLS/Buzz
src/logic/RoundList.java
1,045
package com.mgiandia.library.dao; import java.util.List; import com.mgiandia.library.domain.Borrower; /** * Η διεπαφή DAO για την κλάση {@link Borrower}. * @author Νίκος Διαμαντίδης * */ public interface BorrowerDAO { /** * Η αναζήτηση ενός δανειζομένου με βάση τον αριθμό δανειζομένου. * @param borrowerNo Ο αριθμός δανειζομένου. * @return Το δανειζόμενο ή {@code null} εάν αυτός δεν βρεθεί. */ Borrower find(int borrowerNo); /** * Αποθηκεύει ένα αντικείμενο στην εξωτερική πηγή * δεδομένων. Το αντικείμενο μπορεί να είναι κάποιο * νέο αντικείμενο που δεν υπάρχει στην πηγή δεδομένων * ή κάποιο το οποίο ήδη υπάρχει και ενημερώνεται η * κατάστασή του. * @param entity Το αντικείμενο του οποίου η κατάσταση * αποθηκεύεται στην εξωτερική πηγή δεδομένων. */ void save(Borrower entity); /** * Διαγράφει το αντικείμενο από την εξωτερική πηγή δεδομένων. * @param entity Το αντικείμενο προς διαγραφή. */ void delete(Borrower entity); /** * Επιστρέφει όλα τα αντικείμενα από την εξωτερική πηγή δεδομένων. * @return Ο κατάλογος των αντικειμένων */ List<Borrower> findAll(); }
diamantidakos/Library
src/main/java/com/mgiandia/library/dao/BorrowerDAO.java
1,047
package gr.aueb.cf.ch5; /** * Χρησιμοποιεί τη μέθοδο swap() για * να ανταλλάξει αμοιβαία τις τιμές των α, β. * Ο τρόπος αυτός αμοιβαίας ανταλλαγής δε * δουλεύει γιατί τα a, b περνάνε ως input * (readonly) και όχι ως output. * */ public class SwapApp { public static void main(String[] args) { int a = 5; int b = 7; swap(a, b); System.out.printf("a = %d, b = %d",a, b); } /** * Swaps a, b. * * @param a the first int * @param b the second int */ public static void swap(int a, int b) { int tmp = a; a = b; b = tmp; } }
a8anassis/cf4
src/gr/aueb/cf/ch5/SwapApp.java
1,048
package com.example.carpicker; import androidx.appcompat.app.*; import android.os.*; import android.view.*; import android.widget.*; import java.util.*; public class MainActivity extends AppCompatActivity { // Δημιουργώ αντικείμενο CarBrandList που θα το χρησιμοποιήσω σε κάποια μέθοδο private CarBrandList cbl; // ορίζουμε το RadioGroup εδώ για να το δούν όλες οι μέθοδοι. private RadioGroup rg; // Ορίζω την IP μου για να μην την γράφω σε κάθε μέθοδο private final String myIP = "192.168.1.104"; // Γράφουμε την μέθοδο για το τι θα κάνει το κουμπί όταν πατηθεί. public void PickCarOnClick(View v) { // Φτιάχνω ένα αντικείμενο spinner. Επιλεγμένο αντικείμενο από την λίστα Spinner dropDown = (Spinner) findViewById(R.id.cars); // Από το spinner παίρνω το επιλεγμένο αντικείμενο και το αποθηκεύω στο brand String brand = String.valueOf(dropDown.getSelectedItem()); // Σύνδεση του GUI με την κλάση πρέπει να γίνει μέσα στην παρένθεση List<String> allModels = cbl.getAllModels(brand); // Πρέπει να περάσουμε τα μοντέλα στο GUI στο radiogroup rg.removeAllViews(); // το αδειάζουμε // Κατασκευή του radiobutton for(int i=0;i<allModels.size();i++) { RadioButton rb = new RadioButton(this);// Φτιάχνω ένα radio button ανάλογα με τι μέγεθος θα έχει η λίστα rb.setText(allModels.get(i)); // Προσθέτων το κείμενο που πήρα από την λίστα ως κείμενο σε radiobutton rb.setId(100+i); // Βάζω ένα id γιατί πιθανό να το ψάξω με το id rg.addView(rb); // Το προσθέτω στο radiogroup } // Φτιάχνω έναν Listener που θα τον υλοποιήσω εδώ μέσα rg.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() { /* αυτός ο κώδικα χειρίζεται το συμβάν όταν επιλέγεται ένα κουμπί επιλογής σε ένα radiogroup. Ανακτά το επιλεγμένο κουμπί επιλογής, κατασκευάζει μια συμβολοσειρά URL με την επιλεγμένη επωνυμία, μοντέλο και χρονική σήμανση, καλεί ένα αίτημα HTTP για να καταγράψει την επιλογή χρησιμοποιώντας το OkHttp και εμφανίζει ένα μήνυμα toast για να ειδοποιήσει τον χρήστη για την επιτυχή καταγραφή. */ @Override public void onCheckedChanged(RadioGroup radioGroup, int checkedId) { // Ανακτά το επιλεγμένο RadioButton από το RadioGroup με βάση την παράμετρο checkedId, // η οποία αντιπροσωπεύει το αναγνωριστικό του επιλεγμένου κουμπιού επιλογής. RadioButton rb = (RadioButton) findViewById(checkedId); // κατασκευάζει μια συμβολοσειρά URL για ένα τελικό σημείο υπηρεσίας ιστού, // το οποίο περιλαμβάνει παραμέτρους για την επωνυμία, το μοντέλο και τη χρονική σήμανση. // Η τιμή της επωνυμίας θεωρείται ότι ορίζεται αλλού και η rb.getText().toString() ανακτά το κείμενο // του επιλεγμένου κουμπιού επιλογής, που αντιπροσωπεύει το μοντέλο. // Η χρονική σήμανση δημιουργείται χρησιμοποιώντας τη νέα Date(System.currentTimeMillis()) // και μετατρέπεται σε συμβολοσειρά. String url= "http://"+myIP+"/carsDBServices/logHistory.php?brand=" + brand + "&model=" + rb.getText().toString() + "&timestamp=" + new Date(System.currentTimeMillis()).toString(); try { // Δημιουργεί αντικείμενο μιας προσαρμοσμένης κλάσης OkHttpHandler, // η οποία φαίνεται να χειρίζεται αιτήματα HTTP χρησιμοποιώντας τη βιβλιοθήκη OkHttp. OkHttpHandler okHttpHandler = new OkHttpHandler(); // Επικαλείται τη μέθοδο logHistory του αντικειμένου OkHttpHandler, // περνώντας τη συμβολοσειρά URL που δημιουργήθηκε ως παράμετρο. // Αυτό υποδηλώνει ότι η μέθοδος logHistory είναι υπεύθυνη για την αποστολή ενός αιτήματος // HTTP στην καθορισμένη διεύθυνση URL, πιθανόν για την καταγραφή της επιλεγμένης // επωνυμίας, μοντέλου και χρονικής σφραγίδας. okHttpHandler.logHistory(url); // Εμφανίζει ένα μήνυμα toast μικρής διάρκειας που υποδεικνύει ότι η επιλογή καταγράφηκε // με επιτυχία. Toast.makeText(getApplicationContext(), "Selection Logged", Toast.LENGTH_SHORT).show(); } catch (Exception e) { e.printStackTrace(); } } }); } /* Παρακάτω ο κώδικας αρχικοποιεί μια CarBrandList, ορίζει την προβολή περιεχομένου της δραστηριότητας, δημιουργεί ένα Spinner, το συμπληρώνει με επωνυμίες χρησιμοποιώντας έναν ArrayAdapter και προετοιμάζει μια RadioGroup. Αυτό ρυθμίζει τα στοιχεία διεπαφής χρήστη για τη δραστηριότητα, επιτρέποντας στον χρήστη να επιλέξει μια μάρκα αυτοκινήτου από το Spinner και να αλληλεπιδράσει με το RadioGroup. */ @Override protected void onCreate(Bundle savedInstanceState) { // Στο αντικείμενο cbl περνάω το αρχείο με τα brands με την getAssets() cbl = new CarBrandList(myIP); super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); //Δημιουργούμε το Spinner και το γεμίζουμε με τα brands Spinner dropDown = (Spinner) findViewById(R.id.cars); // Δημιουργεί έναν ArrayAdapter που θα χρησιμοποιηθεί για τη συμπλήρωση του Spinner με δεδομένα. // Ο ArrayAdapter αρχικοποιείται με την τρέχουσα δραστηριότητα (this), τον πόρο διάταξης // για κάθε στοιχείο Spinner και τη λίστα των brands που ελήφθησαν // από το CarBrandList cbl χρησιμοποιώντας τη μέθοδο getAllBrands. ArrayAdapter<String> arrayAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_dropdown_item, cbl.getAllBrands()); dropDown.setAdapter(arrayAdapter); // Αρχικοποιεί ένα γραφικό στοιχείο RadioGroup που ονομάζεται rg // βρίσκοντας την προβολή με το αναγνωριστικό rg από τη διάταξη της δραστηριότητας rg = (RadioGroup) findViewById(R.id.rg); } }
iosifidis/UoM-Applied-Informatics
s6/Mobile Application Developement/Java-XML-files/08-CarPicker-DB/MainActivity.java
1,049
package gr.aueb.cf.ch4; /** Ένας μικρός βάτραχος θέλει να περάσει ένα ποτάμι. Ο frog βρίσκεται στη θέση Χ και θέλει να φτάσει στη θέση γ (ή σε θέση > Υ). Ο frog Jumps a fixed distance, D. βρίσκει τον ελάχιστο αριθμό jumps που ο small frog πρέπει να κάνει ώστε να φτάσει (ή να ξεπεράσει) τον στόχο. Για παράδειγμα, αν έχουμε Χ = 10 Y = 85 D= 30, τότε ο shall frog θα χρειαστεί ο αυτός, γιατί Starts at 10, και μετά το 1ο jump πάει στη θέση 10 Στο 2ο jump, πάει 40 + 30 = 70 και στο 3ο jump, πάει 70 + 30 = 100 */ public class FrogApp { public static void main(String[] args) { int x = 0; int y = 100; int d = 5; int jumps = 0; jumps = (int) Math.ceil((y - x) / (double) d); System.out.println("jumps: " + jumps); } }
th-am/codingfactory23
src/gr/aueb/cf/ch4/FrogApp.java
1,051
package sample; import javafx.animation.*; import javafx.fxml.FXML; import javafx.fxml.FXMLLoader; import javafx.scene.Parent; import javafx.scene.control.Button; import javafx.scene.control.Label; import javafx.scene.image.Image; import javafx.scene.image.ImageView; import javafx.scene.layout.GridPane; import javafx.scene.media.Media; import javafx.scene.media.MediaPlayer; import javafx.stage.Stage; import javafx.util.Duration; import java.io.*; import java.util.*; /** * Η κλάση του Multiplayer */ public class Multiplayer extends Game { private int clicks,random1,random2,random3,wins1,wins2,wins3; @FXML private GridPane grid,gridTable; @FXML private Button back,next; @FXML private Label turn,nextTurn,player1,player2,player3,player4,winLabel; private String t,nt,p1,p2,p3,p4; private String pl1,pl2,pl3,pl4,you; private String playerTurn1,playerTurn2,playerTurn3,playerTurn4,youWin,botWin; private ImageView clickedImageView; private int[] scoreBots = new int[3]; private Properties properties = new Properties(); private Properties properties2 = new Properties(); private InputStream input = null; private OutputStream output = null; private MediaPlayer mediaPlayer; /** * Ο κατασκευαστής της κλάσης */ public Multiplayer(){ clicks = 0; clickedImageView = null; Media buttonSound = new Media(getClass().getClassLoader().getResource("Sounds/buttonSound.wav").toExternalForm()); mediaPlayer = new MediaPlayer(buttonSound); } /** * Φορτώνει τις τιμές απο το αρχείο * @throws IOException εάν αποτύχει να φορτώσει το αρχείο */ public void initialize()throws IOException{ File f =new File("score.properties"); File f2 =new File("config.properties"); if(f2.exists()) { input = new FileInputStream("config.properties"); properties.load(input); String lang = properties.getProperty("flag"); loadLang(lang); } if(f.exists()){ InputStream input2 = new FileInputStream("score.properties"); properties2.load(input2); wins1 = Integer.parseInt(properties2.getProperty("MultiplayerWins1")); wins2 = Integer.parseInt(properties2.getProperty("MultiplayerWins2")); wins3 = Integer.parseInt(properties2.getProperty("MultiplayerWins3")); } } /** * Θέτει το GameMode και το θέμα του παιχνιδιού. * @param gameMode {@code GameMode} * @param theme {@code Image} φόντο της κάρτας * @throws IOException - */ @Override public void setMode(GameMode gameMode, Image theme) throws IOException { super.setMode(gameMode, theme); } /** * Διορθώνει την γλώσσα στα Label των παιχτών. * @throws IOException - */ public void fixLang() throws IOException{ playersLang(); } /** * Δημιουργεί τα ImageView , τις εικόνες και τις τοποθετεί στο GridPane */ public void multiplayerStart(){ createImageViews(grid,imageViews); createImages(cards); shuffleCards(imageViews); setImages(imageViews,cards); player(); turn.setText(t + playerTurn1 + you); nextTurn.setText(nt + playerTurn2 + "(" + p2 + ")"); } /** * O Event Handler για τα ImageView */ @Override public void player() { super.player(); } /** * Καθορίζει τις κινήσεις του χρήστη και γυρίζει ανάλογα τις κάρτες που αυτός θα επιλέξει. * @param imageView {@code ImageView} το ImageView που φαίνεται στην οθόνη * @param card {@code Card} κάρτα */ @Override public void clickEvent(ImageView imageView, Card card) { super.clickEvent(imageView,card); if(foundCards.size() == gameMode.getSize()) { findWinner(); return; } player1.setText(pl1+score.getFoundCards()); clickedImageView = imageView; clicks++; if(gameMode.getMode()!= 3) { if (clicks == 2 && cardsMatch) { clicks = 0; // enableAll(); } if (clicks == 2 && foundCards.size() == gameMode.getSize()) return; if (gameMode.getRivalsNumber() == 1 && clicks == 4) { clicks = 0; } if (gameMode.getRivalsNumber() == 2 && clicks == 6) { clicks = 0; } if (gameMode.getRivalsNumber() == 3 && clicks == 8) { clicks = 0; } if (clicks == 0) { Timeline playAgain = new Timeline(new KeyFrame(Duration.seconds(1.5), event -> enableAll())); playAgain.play(); } } else{ System.out.println(clicks); if (clicks == 3 && cardsMatch) { clicks = 0; // enableAll(); } if (clicks == 3 && foundCards.size() == gameMode.getSize()) return; if (gameMode.getRivalsNumber() == 1 && clicks == 6) { clicks = 0; } if (gameMode.getRivalsNumber() == 2 && clicks == 9) { clicks = 0; } if (gameMode.getRivalsNumber() == 3 && clicks == 12) { clicks = 0; } if (clicks == 0) { Timeline playAgain = new Timeline(new KeyFrame(Duration.seconds(1.5), event -> enableAll())); playAgain.play(); } } } /** * Το μποτάκι GoldFish που σηκώνει δυο τυχαίες κάρτες. */ public void goldfish(){ if(foundCards.size() == gameMode.getSize()) { findWinner(); return; } disableAll(); Random random = new Random(); random1 = random.nextInt(imageViews.size()); random2 = random.nextInt(imageViews.size()); while ((foundCards.contains(imageViews.get(random1)) || foundCards.contains(imageViews.get(random2)) || random1 == random2) && foundCards.size() != gameMode.getSize()) { random1 = random.nextInt(imageViews.size()); random2 = random.nextInt(imageViews.size()); } final ImageView imageView1 = imageViews.get(random1); final ImageView imageView2 = imageViews.get(random2); final Card card1 = cards.get(random1); final Card card2 = cards.get(random2); if(!seenImageViewsElephant.contains(imageView1)){ seenImageViewsElephant.add(imageView1); seenCardsElephant.add(card1); } if(!seenImageViewsElephant.contains(imageView2)){ seenImageViewsElephant.add(imageView2); seenCardsElephant.add(card2); } if(!seenImageViewsKangaroo.contains(imageView1)){ seenImageViewsKangaroo.add(imageView1); seenCardsKangaroo.add(card1); } ScaleTransition scale1 = new ScaleTransition(Duration.seconds(0.5),imageView1); scale1.setFromX(1); scale1.setToX(-1); scale1.play(); scale1.setOnFinished(event -> {imageView1.setScaleX(1); imageView1.setImage(card1.getValue());}); ScaleTransition scale2 = new ScaleTransition(Duration.seconds(0.5),imageView2); scale2.setFromX(1); scale2.setToX(-1); scale2.play(); scale2.setOnFinished(event -> {imageView2.setScaleX(1); imageView2.setImage(card2.getValue());}); if (cards.get(random1).getId() == cards.get(random2).getId()) { botUpdateScore1_2(); foundCards.add(imageView1); foundCards.add(imageView2); seenImageViewsElephant.remove(imageView1); seenImageViewsElephant.remove(imageView2); seenCardsElephant.remove(card1); seenCardsElephant.remove(card2); Timeline timeline = new Timeline(new KeyFrame(Duration.seconds(0.6), event -> { imageView1.setDisable(true); imageView2.setDisable(true); imageView1.setOpacity(0.6); imageView2.setOpacity(0.6); })); timeline.play(); timeline.setOnFinished(event -> { new Timeline(new KeyFrame(Duration.seconds(3), event1 -> goldfish())).play(); }); } else { new Timeline(new KeyFrame(Duration.seconds(1.5), event -> { imageView1.setImage(card1.getBackground()); imageView2.setImage(card2.getBackground()); // imageView1.setDisable(false); // imageView2.setDisable(false); })).play(); } } /** * Το μποτάκι Goldfish που σηκώνεις τρείς τυχαίες κάρτες. */ public void goldfish3(){ if(foundCards.size() == gameMode.getSize()) { findWinner(); return; } disableAll(); Random random = new Random(); random1 = random.nextInt(imageViews.size()); random2 = random.nextInt(imageViews.size()); random3 = random.nextInt(imageViews.size()); while (((foundCards.contains(imageViews.get(random1)) || foundCards.contains(imageViews.get(random2)) || foundCards.contains(imageViews.get(random3)) || random1 == random2 || random2 == random3 || random1 == random3)) && foundCards.size() != gameMode.getSize()) { random1 = random.nextInt(imageViews.size()); random2 = random.nextInt(imageViews.size()); random3 = random.nextInt(imageViews.size()); } final ImageView imageView1 = imageViews.get(random1); final ImageView imageView2 = imageViews.get(random2); final ImageView imageView3 = imageViews.get(random3); final Card card1 = cards.get(random1); final Card card2 = cards.get(random2); final Card card3 = cards.get(random3); if(!seenImageViewsElephant.contains(imageView1)){ seenImageViewsElephant.add(imageView1); seenCardsElephant.add(card1); } if(!seenImageViewsElephant.contains(imageView2)){ seenImageViewsElephant.add(imageView2); seenCardsElephant.add(card2); } if(!seenImageViewsElephant.contains(imageView3)){ seenImageViewsElephant.add(imageView3); seenCardsElephant.add(card3); } if(!seenImageViewsKangaroo.contains(imageView1)){ seenImageViewsKangaroo.add(imageView1); seenCardsKangaroo.add(card1); } ScaleTransition scale1 = new ScaleTransition(Duration.seconds(0.5),imageView1); scale1.setFromX(1); scale1.setToX(-1); scale1.play(); scale1.setOnFinished(event -> {imageView1.setScaleX(1); imageView1.setImage(card1.getValue());}); ScaleTransition scale2 = new ScaleTransition(Duration.seconds(0.5),imageView2); scale2.setFromX(1); scale2.setToX(-1); scale2.play(); scale2.setOnFinished(event -> {imageView2.setScaleX(1); imageView2.setImage(card2.getValue());}); ScaleTransition scale3 = new ScaleTransition(Duration.seconds(0.5),imageView3); scale3.setFromX(1); scale3.setToX(-1); scale3.play(); scale3.setOnFinished(event -> {imageView3.setScaleX(1); imageView3.setImage(card3.getValue());}); if (cards.get(random1).getId() == cards.get(random2).getId() && cards.get(random2).getId() == cards.get(random3).getId()) { botUpdateScore3(); foundCards.add(imageView1); foundCards.add(imageView2); foundCards.add(imageView3); seenImageViewsElephant.remove(imageView1); seenImageViewsElephant.remove(imageView2); seenImageViewsElephant.remove(imageView3); seenCardsElephant.remove(card1); seenCardsElephant.remove(card2); seenCardsElephant.remove(card3); Timeline timeline = new Timeline(new KeyFrame(Duration.seconds(0.6), event -> { imageView1.setDisable(true); imageView2.setDisable(true); imageView3.setDisable(true); imageView1.setOpacity(0.6); imageView2.setOpacity(0.6); imageView3.setOpacity(0.6); })); timeline.play(); timeline.setOnFinished(event -> { new Timeline(new KeyFrame(Duration.seconds(3), event1 -> goldfish3())).play(); }); } else { new Timeline(new KeyFrame(Duration.seconds(1.5), event -> { imageView1.setImage(card1.getBackground()); imageView2.setImage(card2.getBackground()); imageView3.setImage(card3.getBackground()); // imageView1.setDisable(false); // imageView2.setDisable(false); })).play(); } } /** * Το μποτάκι Kangaroo που σηκώνει δυο τυχαίες κάρτες. */ public void kangaroo(){ if(foundCards.size() == gameMode.getSize()) { findWinner(); return; } disableAll(); boolean flag = false; ImageView seenImageView1 = imageViews.get(0); ImageView seenImageView2 = imageViews.get(0); Card seenCard1 = cards.get(0); Card seenCard2 = cards.get(0); for(int i =0; i<seenCardsKangaroo.size();i++){ for(int j = 0; j< seenCardsKangaroo.size();j++){ if(j!=i && seenCardsKangaroo.get(i).getId() == seenCardsKangaroo.get(j).getId()){ seenImageView1 = seenImageViewsKangaroo.get(i); seenImageView2 = seenImageViewsKangaroo.get(j); seenCard1 = seenCardsKangaroo.get(i); seenCard2 = seenCardsKangaroo.get(j); flag = true; break; } } } final ImageView i1 = seenImageView1; final ImageView i2 = seenImageView2; final Card c1 = seenCard1; final Card c2 = seenCard2; if(flag){ if(gameMode.getRival1().equals("Kangaroo") && (clicks == 4 || clicks == 0)){ scoreBots[0]++; player2.setText(pl2+scoreBots[0]); } else if(gameMode.getRival2().equals("Kangaroo") && (clicks == 6 || gameMode.getRivalsNumber() == 2)){ scoreBots[1]++; player3.setText(pl3+scoreBots[1]); } else if(gameMode.getRival3().equals("Kangaroo") && clicks == 0){ scoreBots[2]++; player4.setText(pl4+scoreBots[2]); } seenImageViewsElephant.remove(i1); seenImageViewsElephant.remove(i2); seenCardsElephant.remove(c1); seenCardsElephant.remove(c2); seenImageViewsKangaroo.remove(i1); seenImageViewsKangaroo.remove(i2); seenCardsKangaroo.remove(c1); seenCardsKangaroo.remove(c2); Timeline timeline = new Timeline(new KeyFrame(Duration.seconds(0.6),event -> { findAnimation(i1, i2, c1, c2); foundCards.add(i1); foundCards.add(i2); })); timeline.play(); timeline.setOnFinished(event -> { new Timeline(new KeyFrame(Duration.seconds(2.5),event2 -> { kangaroo(); })).play(); }); } else{ new Timeline(new KeyFrame(Duration.seconds(1),event -> goldfish())).play(); } } /** * Το μποτάκι Kangaroo που σηκώνει τρείς τυχαίες κάρτες. */ public void kangaroo3(){ if(foundCards.size() == gameMode.getSize()) { findWinner(); return; } disableAll(); boolean flag = false; ImageView seenImageView1 = imageViews.get(0); ImageView seenImageView2 = imageViews.get(0); ImageView seenImageView3 = imageViews.get(0); Card seenCard1 = cards.get(0); Card seenCard2 = cards.get(0); Card seenCard3 = cards.get(0); for(int i =0; i<seenCardsKangaroo.size();i++){ for(int j = i+1; j< seenCardsKangaroo.size();j++){ for(int z = j+1;z<seenCardsKangaroo.size();z++) { if (seenCardsKangaroo.get(i).getId() == seenCardsKangaroo.get(j).getId() && seenCardsKangaroo.get(i).getId() == seenCardsKangaroo.get(z).getId() ) { seenImageView1 = seenImageViewsKangaroo.get(i); seenImageView2 = seenImageViewsKangaroo.get(j); seenImageView3 = seenImageViewsKangaroo.get(z); seenCard1 = seenCardsKangaroo.get(i); seenCard2 = seenCardsKangaroo.get(j); seenCard3 = seenCardsKangaroo.get(z); flag = true; break; } } } } final ImageView i1 = seenImageView1; final ImageView i2 = seenImageView2; final ImageView i3 = seenImageView3; final Card c1 = seenCard1; final Card c2 = seenCard2; final Card c3 = seenCard3; if(flag){ if(gameMode.getRival1().equals("Kangaroo") && (clicks == 6 ||gameMode.getRivalsNumber()==1)){ scoreBots[0]++; player2.setText(pl2+scoreBots[0]); } else if(gameMode.getRival2().equals("Kangaroo") && (clicks == 9 ||gameMode.getRivalsNumber()==2)){ scoreBots[1]++; player3.setText(pl3+scoreBots[1]); } else if(gameMode.getRival3().equals("Kangaroo") && clicks == 0){ scoreBots[2]++; player4.setText(pl4+scoreBots[2]); } seenImageViewsElephant.remove(i1); seenImageViewsElephant.remove(i2); seenImageViewsElephant.remove(i3); seenCardsElephant.remove(c1); seenCardsElephant.remove(c2); seenCardsElephant.remove(c3); seenImageViewsKangaroo.remove(i1); seenImageViewsKangaroo.remove(i2); seenImageViewsKangaroo.remove(i3); seenCardsKangaroo.remove(c1); seenCardsKangaroo.remove(c2); seenCardsKangaroo.remove(c3); Timeline timeline = new Timeline(new KeyFrame(Duration.seconds(0.6),event -> { findAnimation3(i1, i2,i3, c1, c2,c3); foundCards.add(i1); foundCards.add(i2); foundCards.add(i3); })); timeline.play(); timeline.setOnFinished(event -> { new Timeline(new KeyFrame(Duration.seconds(2.5),event2 -> { kangaroo3(); })).play(); }); } else{ new Timeline(new KeyFrame(Duration.seconds(1),event -> goldfish3())).play(); } } /** * Το μποτάκι Elephant που σηκώνει δυο τυχαίες κάρτες. */ public void elephant(){ if(foundCards.size() == gameMode.getSize()) { findWinner(); return; } disableAll(); boolean flag = false; ImageView seenImageView1 = imageViews.get(0); ImageView seenImageView2 = imageViews.get(0); Card seenCard1 = cards.get(0); Card seenCard2 = cards.get(0); for(int i =0; i<seenCardsElephant.size();i++){ for(int j = 0; j< seenCardsElephant.size();j++){ if(j!=i && seenCardsElephant.get(i).getId() == seenCardsElephant.get(j).getId()){ seenImageView1 = seenImageViewsElephant.get(i); seenImageView2 = seenImageViewsElephant.get(j); seenCard1 = seenCardsElephant.get(i); seenCard2 = seenCardsElephant.get(j); flag = true; break; } } } final ImageView i1 = seenImageView1; final ImageView i2 = seenImageView2; final Card c1 = seenCard1; final Card c2 = seenCard2; if(flag){ if(gameMode.getRival1().equals("Elephant") && (clicks == 4 || gameMode.getRivalsNumber() == 1)){ scoreBots[0]++; player2.setText(pl2+scoreBots[0]); } else if(gameMode.getRival2().equals("Elephant") && (clicks == 6 || gameMode.getRivalsNumber() == 2)){ scoreBots[1]++; player3.setText(pl3+scoreBots[1]); } else if(gameMode.getRival3().equals("Elephant") && clicks == 0){ scoreBots[2]++; player4.setText(pl4+scoreBots[2]); } seenImageViewsElephant.remove(i1); seenImageViewsElephant.remove(i2); seenCardsElephant.remove(c1); seenCardsElephant.remove(c2); seenImageViewsKangaroo.remove(i1); seenCardsKangaroo.remove(c1); Timeline timeline = new Timeline(new KeyFrame(Duration.seconds(0.6),event -> { findAnimation(i1, i2, c1, c2); foundCards.add(i1); foundCards.add(i2); })); timeline.play(); timeline.setOnFinished(event -> { new Timeline(new KeyFrame(Duration.seconds(2.5),event2 -> { elephant(); })).play(); }); } else{ new Timeline(new KeyFrame(Duration.seconds(1),event -> goldfish())).play(); } } /** * Το μποτάκι Elephant που σηκώνει τρείς τυχαίες κάρτες. */ public void elephant3(){ if(foundCards.size() == gameMode.getSize()) { findWinner(); return; } disableAll(); boolean flag = false; ImageView seenImageView1 = imageViews.get(0); ImageView seenImageView2 = imageViews.get(0); ImageView seenImageView3 = imageViews.get(0); Card seenCard1 = cards.get(0); Card seenCard2 = cards.get(0); Card seenCard3 = cards.get(0); for(int i =0; i<seenCardsElephant.size();i++){ for(int j = i+1; j< seenCardsElephant.size();j++){ for(int z = j+1;z<seenCardsElephant.size();z++) { if (seenCardsElephant.get(i).getId() == seenCardsElephant.get(j).getId() && seenCardsElephant.get(i).getId() == seenCardsElephant.get(z).getId() ) { seenImageView1 = seenImageViewsElephant.get(i); seenImageView2 = seenImageViewsElephant.get(j); seenImageView3 = seenImageViewsElephant.get(z); seenCard1 = seenCardsElephant.get(i); seenCard2 = seenCardsElephant.get(j); seenCard3 = seenCardsElephant.get(z); flag = true; break; } } } } final ImageView i1 = seenImageView1; final ImageView i2 = seenImageView2; final ImageView i3 = seenImageView3; final Card c1 = seenCard1; final Card c2 = seenCard2; final Card c3 = seenCard3; if(flag){ if(gameMode.getRival1().equals("Elephant") && (clicks == 6 ||gameMode.getRivalsNumber()==1)){ scoreBots[0]++; player2.setText(pl2+scoreBots[0]); } else if(gameMode.getRival2().equals("Elephant") && (clicks == 9 ||gameMode.getRivalsNumber()==2)){ scoreBots[1]++; player3.setText(pl3+scoreBots[1]); } else if(gameMode.getRival3().equals("Elephant") && clicks == 0){ scoreBots[2]++; player4.setText(pl4+scoreBots[2]); } seenImageViewsElephant.remove(i1); seenImageViewsElephant.remove(i2); seenImageViewsElephant.remove(i3); seenCardsElephant.remove(c1); seenCardsElephant.remove(c2); seenCardsElephant.remove(c3); seenImageViewsKangaroo.remove(i1); seenCardsKangaroo.remove(c1); Timeline timeline = new Timeline(new KeyFrame(Duration.seconds(0.6),event -> { findAnimation3(i1, i2,i3, c1, c2,c3); foundCards.add(i1); foundCards.add(i2); foundCards.add(i3); })); timeline.play(); timeline.setOnFinished(event -> { new Timeline(new KeyFrame(Duration.seconds(2.5),event2 -> { elephant3(); })).play(); }); } else{ new Timeline(new KeyFrame(Duration.seconds(1),event -> goldfish3())).play(); } } /** * Ένα ScaleTransition για το animation, όταν δύο κάρτες βρίσκονται */ private void findAnimation(ImageView imageView1,ImageView imageView2,Card card1,Card card2){ ScaleTransition scaleTransition = new ScaleTransition(Duration.seconds(0.5),imageView1); scaleTransition.setFromX(1); scaleTransition.setToX(-1); scaleTransition.play(); scaleTransition.setOnFinished(event -> { imageView1.setScaleX(1); imageView1.setImage(card1.getValue()); imageView1.setDisable(true); imageView1.setOpacity(0.6); }); ScaleTransition scaleTransition2 = new ScaleTransition(Duration.seconds(0.5),imageView2); scaleTransition2.setFromX(1); scaleTransition2.setToX(-1); scaleTransition2.play(); scaleTransition2.setOnFinished(event -> { imageView2.setScaleX(1); imageView2.setImage(card2.getValue()); imageView2.setDisable(true); imageView2.setOpacity(0.6); }); } /** * Ένα ScaleTransition για το animation, όταν τρείς κάρτες βρίσκονται */ private void findAnimation3(ImageView imageView1,ImageView imageView2,ImageView imageView3,Card card1,Card card2,Card card3){ ScaleTransition scaleTransition = new ScaleTransition(Duration.seconds(0.5),imageView1); scaleTransition.setFromX(1); scaleTransition.setToX(-1); scaleTransition.play(); scaleTransition.setOnFinished(event -> { imageView1.setScaleX(1); imageView1.setImage(card1.getValue()); imageView1.setDisable(true); imageView1.setOpacity(0.6); }); ScaleTransition scaleTransition2 = new ScaleTransition(Duration.seconds(0.5),imageView2); scaleTransition2.setFromX(1); scaleTransition2.setToX(-1); scaleTransition2.play(); scaleTransition2.setOnFinished(event -> { imageView2.setScaleX(1); imageView2.setImage(card2.getValue()); imageView2.setDisable(true); imageView2.setOpacity(0.6); }); ScaleTransition scaleTransition3 = new ScaleTransition(Duration.seconds(0.5),imageView3); scaleTransition3.setFromX(1); scaleTransition3.setToX(-1); scaleTransition3.play(); scaleTransition3.setOnFinished(event -> { imageView3.setScaleX(1); imageView3.setImage(card3.getValue()); imageView3.setDisable(true); imageView3.setOpacity(0.6); }); } /** * Απενεργοποιεί τις κάρτες οταν το κλίκ του παίχτη είναι ένα * @param imageView {@code ImageView} */ private void enable(ImageView imageView){ super.enableAll(); imageView.setDisable(true); } /** * O Event handler που πηγαίνει στην προηγούμενη σκηνή * @throws IOException εάν αποτύχει να φορτώσει το FXML */ @Override public void backClicked() throws IOException { mediaPlayer.seek(Duration.ZERO); mediaPlayer.setVolume(0.3f); mediaPlayer.play(); clicks = 0; Parent root = FXMLLoader.load(getClass().getClassLoader().getResource("fxml/MultiplayerSettings.fxml")); Stage stage = (Stage) back.getScene().getWindow(); stage.getScene().setRoot(root); } /** * Καθορίζει την σειρά των μποτ και ανάλογα αυτή εκτελεί το μποτ που έχει την σειρά, όταν το παιχνίδι παίζεται με δύο κάρτες */ private void multiplayerInitialize1_2(){ if(foundCards.size() == gameMode.getSize()) { System.out.println("STOPPED"); return; } if(clicks == 0){ turn.setText(t + playerTurn1 + you); nextTurn.setText(nt + playerTurn2 + "(" + p2 + ")"); enableAll(); player(); } else if(clicks == 1) enable(clickedImageView); else if(clicks == 2){ turn.setText(t + playerTurn2 + "(" + p2 + ")"); nextTurn.setText(nt + playerTurn3 + "(" + p3 + ")"); if(gameMode.getRival1().equals("Goldfish")){ Timeline bot = new Timeline(new KeyFrame(Duration.seconds(1.5),event1 -> { goldfish(); })); bot.play(); clicks = clicks +2; if(gameMode.getRivalsNumber() == 1){ nextTurn.setText(nt + playerTurn1 + you); clicks = 0; } } else if(gameMode.getRival1().equals("Elephant")){ Timeline bot = new Timeline(new KeyFrame(Duration.seconds(1.5),event1 -> { elephant(); })); bot.play(); clicks = clicks +2; if(gameMode.getRivalsNumber() == 1){ nextTurn.setText(nt + playerTurn1 + you); clicks = 0; } } else if(gameMode.getRival1().equals("Kangaroo")){ Timeline bot = new Timeline(new KeyFrame(Duration.seconds(1.5),event1 -> {kangaroo();})); bot.play(); clicks = clicks +2; if(gameMode.getRivalsNumber() == 1){ nextTurn.setText(nt + playerTurn1 + you); clicks = 0; } } } else if(clicks == 4){ turn.setText(t + playerTurn3 + "(" + p3 + ")"); nextTurn.setText(nt + playerTurn4 + "(" + p4 + ")"); if(gameMode.getRival2().equals("Goldfish")){ Timeline bot = new Timeline(new KeyFrame(Duration.seconds(1.5),event1 -> {goldfish();})); bot.play(); clicks = clicks +2; if(gameMode.getRivalsNumber() == 2){ nextTurn.setText(nt + playerTurn1 + you); clicks = 0; } } else if(gameMode.getRival2().equals("Elephant")){ Timeline bot = new Timeline(new KeyFrame(Duration.seconds(1.5),event1 -> {elephant();})); bot.play(); clicks = clicks +2; if(gameMode.getRivalsNumber() == 2){ nextTurn.setText(nt + playerTurn1 + you); clicks = 0; } } else if(gameMode.getRival2().equals("Kangaroo")){ Timeline bot = new Timeline(new KeyFrame(Duration.seconds(1.5),event1 -> {kangaroo();})); bot.play(); clicks = clicks +2; if(gameMode.getRivalsNumber() == 2){ nextTurn.setText(nt + playerTurn1 + you); clicks = 0; } } } else if(clicks == 6){ turn.setText(t + playerTurn4 + "(" + p4 + ")"); nextTurn.setText(nt + playerTurn1 + you); if(gameMode.getRival3().equals("Goldfish")){ Timeline bot = new Timeline(new KeyFrame(Duration.seconds(1.5),event1 -> goldfish())); bot.play(); clicks = clicks +2; if(gameMode.getRivalsNumber() == 3){ clicks = 0; } } else if(gameMode.getRival3().equals("Elephant")){ Timeline bot = new Timeline(new KeyFrame(Duration.seconds(1.5),event1 -> elephant())); bot.play(); clicks = clicks +2; if(gameMode.getRivalsNumber() == 3){ clicks = 0; } } else if(gameMode.getRival3().equals("Kangaroo")){ Timeline bot = new Timeline(new KeyFrame(Duration.seconds(1.5),event1 -> kangaroo())); bot.play(); clicks = clicks +2; if(gameMode.getRivalsNumber() == 3){ clicks = 0; } } } } /** * Καθορίζει την σειρά των μποτ και ανάλογα αυτή εκτελεί το μποτ που έχει την σειρά, όταν το παιχνίδι παίζεται με τρείς κάρτες */ private void multiplayerInitialize3(){ if(foundCards.size() == gameMode.getSize()) { System.out.println("STOPPED"); return; } if(clicks == 0){ turn.setText(t + playerTurn1 + you); nextTurn.setText(nt + playerTurn2 + "(" + p2 + ")"); enableAll(); player(); } else if(clicks == 1) enable(clickedImageView); else if(clicks == 3){ turn.setText(t + playerTurn2 + "(" + p2 + ")"); nextTurn.setText(nt + playerTurn3 + "(" + p3 + ")"); if(gameMode.getRival1().equals("Goldfish")){ Timeline bot = new Timeline(new KeyFrame(Duration.seconds(1.5),event1 -> { goldfish3(); })); bot.play(); clicks = clicks +3; if(gameMode.getRivalsNumber() == 1){ nextTurn.setText(nt + playerTurn1 + you); clicks = 0; } } else if(gameMode.getRival1().equals("Elephant")){ Timeline bot = new Timeline(new KeyFrame(Duration.seconds(1.5),event1 -> {elephant3();})); bot.play(); clicks = clicks +3; if(gameMode.getRivalsNumber() == 1){ nextTurn.setText(nt + playerTurn1 + you); clicks = 0; } } else if(gameMode.getRival1().equals("Kangaroo")){ Timeline bot = new Timeline(new KeyFrame(Duration.seconds(1.5),event1 -> {kangaroo3();})); bot.play(); clicks = clicks +3; if(gameMode.getRivalsNumber() == 1){ nextTurn.setText(nt + playerTurn1 + you); clicks = 0; } } } else if(clicks == 6){ turn.setText(t + playerTurn3 + "(" + p3 + ")"); nextTurn.setText(nt + playerTurn4 + "(" + p4 + ")"); if(gameMode.getRival2().equals("Goldfish")){ Timeline bot = new Timeline(new KeyFrame(Duration.seconds(1.5),event1 -> {goldfish3();})); bot.play(); clicks = clicks +3; if(gameMode.getRivalsNumber() == 2){ nextTurn.setText(nt + playerTurn1 + you); clicks = 0; } } else if(gameMode.getRival2().equals("Elephant")){ Timeline bot = new Timeline(new KeyFrame(Duration.seconds(1.5),event1 -> {elephant3();})); bot.play(); clicks = clicks +3; if(gameMode.getRivalsNumber() == 2){ nextTurn.setText(nt + playerTurn1 + you); clicks = 0; } } else if(gameMode.getRival2().equals("Kangaroo")){ Timeline bot = new Timeline(new KeyFrame(Duration.seconds(1.5),event1 -> {kangaroo3();})); bot.play(); clicks = clicks +3; if(gameMode.getRivalsNumber() == 2){ nextTurn.setText(nt + playerTurn1 + you); clicks = 0; } } } else if(clicks == 9){ turn.setText(t + playerTurn4 + "(" + p4 + ")"); nextTurn.setText(nt + playerTurn1 + you); if(gameMode.getRival3().equals("Goldfish")){ Timeline bot = new Timeline(new KeyFrame(Duration.seconds(1.5),event1 -> goldfish3())); bot.play(); clicks = clicks +3; if(gameMode.getRivalsNumber() == 3){ clicks = 0; } } else if(gameMode.getRival3().equals("Elephant")){ Timeline bot = new Timeline(new KeyFrame(Duration.seconds(1.5),event1 -> elephant3())); bot.play(); clicks = clicks +3; if(gameMode.getRivalsNumber() == 3){ clicks = 0; } } else if(gameMode.getRival3().equals("Kangaroo")){ Timeline bot = new Timeline(new KeyFrame(Duration.seconds(1.5),event1 -> kangaroo3())); bot.play(); clicks = clicks +3; if(gameMode.getRivalsNumber() == 3){ clicks = 0; } } } } /** * Αυξάνει το σκόρ όταν παίζουν τα μποτάκια με δύο κάρτες, αυξάνοντας όμως και το σκόρ αυτών οταν δεν θυμούνται την κάρτα και παίζουν σαν Goldfish */ private void botUpdateScore1_2(){ if(gameMode.getRival1().equals("Goldfish") && (clicks == 4 || gameMode.getRivalsNumber() == 1)){ scoreBots[0]++; player2.setText(pl2+scoreBots[0]); } else if(gameMode.getRival2().equals("Goldfish") && (clicks == 6 || gameMode.getRivalsNumber() ==2)){ scoreBots[1]++; player3.setText(pl3+scoreBots[1]); } else if(gameMode.getRival3().equals("Goldfish") && clicks == 0){ scoreBots[2]++; player4.setText(pl4+scoreBots[2]); } else if(gameMode.getRival1().equals("Kangaroo") && (clicks == 4 || gameMode.getRivalsNumber() == 1)){ scoreBots[0]++; player2.setText(pl2+scoreBots[0]); } else if(gameMode.getRival2().equals("Kangaroo") && (clicks == 6 || gameMode.getRivalsNumber() ==2)){ scoreBots[1]++; player3.setText(pl3+scoreBots[1]); } else if(gameMode.getRival3().equals("Kangaroo") && clicks == 0){ scoreBots[2]++; player4.setText(pl4+scoreBots[2]); } else if(gameMode.getRival1().equals("Elephant") && (clicks == 4 || gameMode.getRivalsNumber() == 1)){ scoreBots[0]++; player2.setText(pl2+scoreBots[0]); } else if(gameMode.getRival2().equals("Elephant") && (clicks == 6 || gameMode.getRivalsNumber() ==2)){ scoreBots[1]++; player3.setText(pl3+scoreBots[1]); } else if(gameMode.getRival3().equals("Elephant") && clicks == 0){ scoreBots[2]++; player4.setText(pl4+scoreBots[2]); } } /** * Αυξάνει το σκόρ όταν παίζουν τα μποτάκια με τρείς κάρτες, αυξάνοντας όμως και το σκόρ αυτών οταν δεν θυμούνται την κάρτα και παίζουν σαν Goldfish */ private void botUpdateScore3(){ if(gameMode.getRival1().equals("Goldfish") && (clicks == 6 || gameMode.getRivalsNumber()==1)){ scoreBots[0]++; player2.setText(pl2+scoreBots[0]); } else if(gameMode.getRival2().equals("Goldfish") && (clicks == 9 ||gameMode.getRivalsNumber()==2)){ scoreBots[1]++; player3.setText(pl3+scoreBots[1]); } else if(gameMode.getRival3().equals("Goldfish") && clicks == 0){ scoreBots[2]++; player4.setText(pl4+scoreBots[2]); } else if(gameMode.getRival1().equals("Kangaroo") && (clicks == 6 || gameMode.getRivalsNumber()==1)){ scoreBots[0]++; player2.setText(pl2+scoreBots[0]); } else if(gameMode.getRival2().equals("Kangaroo") && (clicks == 9||gameMode.getRivalsNumber()==2)){ scoreBots[1]++; player3.setText(pl3+scoreBots[1]); } else if(gameMode.getRival3().equals("Kangaroo") && clicks == 0){ scoreBots[2]++; player4.setText(pl4+scoreBots[2]); } else if(gameMode.getRival1().equals("Elephant") && (clicks == 6 || gameMode.getRivalsNumber()==1)){ scoreBots[0]++; player2.setText(pl2+scoreBots[0]); } else if(gameMode.getRival2().equals("Elephant") && (clicks == 9 || gameMode.getRivalsNumber()==2)){ scoreBots[1]++; player3.setText(pl3+scoreBots[1]); } else if(gameMode.getRival3().equals("Elephant") && clicks == 0){ scoreBots[2]++; player4.setText(pl4+scoreBots[2]); } } /** * Ο Event Handler που ελέγχει ποιανού σειρά είναι και εκτελεί τις κατάλληλες μεθόδους. */ @FXML private void nextClicked(){ if(gameMode.getMode()!=3) multiplayerInitialize1_2(); else multiplayerInitialize3(); } /** * Ελέγχει ποιος έχει νικήσει και αντίστοιχα εμφανίζει στην οθόνη */ private void findWinner(){ int count = 0; boolean playerWon = false; for(int i = 0;i<scoreBots.length;i++){ if(score.getFoundCards()> scoreBots[i]){ count++; } } if(count == 3){ playerWon = true; if(gameMode.getMode() == 1){ wins1++; properties2.setProperty("MultiplayerWins1",Integer.toString(wins1)); } else if(gameMode.getMode() == 2){ wins2++; properties2.setProperty("MultiplayerWins2",Integer.toString(wins2)); } else if(gameMode.getMode() == 3){ wins3++; properties2.setProperty("MultiplayerWins3",Integer.toString(wins3)); } try { output = new FileOutputStream("score.properties"); } catch (FileNotFoundException e) { e.printStackTrace(); } try { properties2.store(output,null); } catch (IOException e) { e.printStackTrace(); } winLabel.setText(youWin); } else{ int max = scoreBots[0],pos = 0; for(int i = 0;i<scoreBots.length;i++){ if(max<scoreBots[i]){ pos = i; max = scoreBots[i]; } } if(pos == 0){ winLabel.setText(playerTurn2 +" " +botWin); } else if(pos ==1){ winLabel.setText(playerTurn3 +" "+ botWin); } else if(pos == 2){ winLabel.setText(playerTurn4 +" "+ botWin); } } } /** * Φορτώνει την γλώσσα του FXML. * @param lang {@code String} */ private void loadLang(String lang) { Locale locale = new Locale(lang); ResourceBundle bundle = ResourceBundle.getBundle("lang", locale); next.setText(bundle.getString("next")); turn.setText(bundle.getString("turn")); t = (bundle.getString("turn")); nextTurn.setText(bundle.getString("nextTurn")); nt = bundle.getString("nextTurn"); player1.setText(bundle.getString("player1") + "0"); player2.setText(bundle.getString("player2")+ "0"); player3.setText(bundle.getString("player3")+ "0"); player4.setText(bundle.getString("player4")+ "0"); pl1 = bundle.getString("player1"); pl2 = bundle.getString("player2"); pl3 = bundle.getString("player3"); pl4 = bundle.getString("player4"); playerTurn1 = bundle.getString("player1T"); playerTurn2 = bundle.getString("player2T"); playerTurn3 = bundle.getString("player3T"); playerTurn4 = bundle.getString("player4T"); you = bundle.getString("you"); youWin = bundle.getString("win"); botWin = bundle.getString("botWin"); } /** * Διορθώνει την γλώσσα των παιχτών στα Labels * @throws IOException εάν αποτύχει να φορτώσει το αρχείο. */ private void playersLang() throws IOException{ File f2 =new File("config.properties"); if(f2.exists()) { input = new FileInputStream("config.properties"); properties.load(input); String lang = properties.getProperty("flag"); loadLang(lang); if (lang.equals("el")) { if(gameMode.getRival1().equals("Goldfish")){ p2 = "Χρυσόψαρο"; } else if(gameMode.getRival1().equals("Kangaroo")){ p2 = "Καγκουρό"; } else if(gameMode.getRival1().equals("Elephant")){ p2 = "Ελέφαντας"; } if(gameMode.getRival2().equals("Goldfish")){ p3 = "Χρυσόψαρο"; } else if(gameMode.getRival2().equals("Kangaroo")){ p3 = "Καγκουρό"; } else if(gameMode.getRival2().equals("Elephant")){ p3 = "Ελέφαντας"; } if(gameMode.getRival3().equals("Goldfish")){ p4 = "Χρυσόψαρο"; } else if(gameMode.getRival3().equals("Kangaroo")){ p4 = "Καγκουρό"; } else if(gameMode.getRival3().equals("Elephant")){ p4 = "Ελέφαντας"; } } else if (lang.equals("en")) { if(gameMode.getRival1().equals("Goldfish")){ p2 = "Goldfish"; } else if(gameMode.getRival1().equals("Kangaroo")){ p2 = "Kangaroo"; } else if(gameMode.getRival1().equals("Elephant")){ p2 = "Elephant"; } if(gameMode.getRival2().equals("Goldfish")){ p3 = "Goldfish"; } else if(gameMode.getRival2().equals("Kangaroo")){ p3 = "Kangaroo"; } else if(gameMode.getRival2().equals("Elephant")){ p3 = "Elephant"; } if(gameMode.getRival3().equals("Goldfish")){ p4 = "Goldfish"; } else if(gameMode.getRival3().equals("Kangaroo")){ p4 = "Kangaroo"; } else if(gameMode.getRival3().equals("Elephant")){ p4 = "Elephant"; } } } } }
TommysG/memory-card-game
src/main/java/sample/Multiplayer.java
1,052
package com.nicktz.boat; /** * Βοηθητική κλάση που χρησιμοποιείται για την αποθήκευση των ερωτήσεων και των * απαντήσεων του χρήστη σε αυτές, κάθε φορά που αυτός ολοκληρώνει ένα τεστ. */ public class TriesDB { private final int _id; private final int testId; private final int questionId; private int answer; private final int increasing; public TriesDB(int _id, int testId, int questionId, int answer, int increasing){ this._id = _id; this.testId = testId; this.questionId = questionId; this.answer = answer; this.increasing = increasing; } public int get_id() { return _id; } public int getTestId() { return testId; } public int getQuestionId() { return questionId; } public int getAnswer() { return answer; } public void setAnswer(int answer) { this.answer = answer; } public int getIncreasing() { return increasing; } }
nttzamos/boating-license-exam
app/src/main/java/com/nicktz/boat/TriesDB.java
1,054
import java.util.concurrent.ThreadLocalRandom; /** * Η κλάση υλοποιεί το κανάλι θορύβου. * * @author Δημήτριος Παντελεήμων Γιακάτος * @version 1.0.0 */ public class BitErrorRate { private double possibility; private String data; /** * Η μέθοδος είναι ο constructor. */ public BitErrorRate() {} /** * H μέθοδος αποθηκεύει το μήνυμα T στη μεταβλητή data. * @param data Μία συμβολοσειρά που περιλαμβάνει το μήνυμα T. */ public void setData(String data) {this.data = data;} /** * Η μέθοδος αποθηκεύει τη πιθανότητα σφάλματος στη μεταβλητή possibility. * @param possibility Η πιθανότητα σφάλματος. */ public void setPossibility(double possibility) {this.possibility = possibility;} /** * Η μέθοδος είναι ο εκκινητής της διαδικασίας για το κανάλι θορύβου. * @return Επιστρέφει το μήνυμα T το οποίο πιθανό να έχει αλλοιωθεί από το κανάλι θορύβου. */ public String start() { generateBitErrorRate(); return data; } /** * Η μέθοδος ανάλογα με την πιθανότητα σφάλματος που έχει δώσει ο χρήστης αλλοιώνει κάθε bit του μηνύματος T που * είναι στη μεταβλητή data. Με λίγα λόγια η κλάση δημιουργεί για κάθε ένα bit του T ένα αριθμό από το 0.0 μέχρι * και το 1.0 και αν αυτός ο αριθμός είναι μικρότερος ή ίσος με τη πιθανότητα σφάλματος τότε αλλάζει το bit του * μηνύματος από 0 σε 1 και από 1 σε 0. */ private void generateBitErrorRate() { double randomError; for (int i=0; i<data.length(); i++) { randomError = ThreadLocalRandom.current().nextDouble(0.0, 1.0); if (possibility>=randomError) { if (data.charAt(i)=='0') { data = data.substring(0, i) + "1" + data.substring(i+1); } else { data = data.substring(0, i) + "0" + data.substring(i+1); } } } } }
dpgiakatos/CRC
src/BitErrorRate.java
1,056
package gr.northdigital.gdpr; import javax.ws.rs.ApplicationPath; import gr.northdigital.gdpr.models.GSession; import org.bouncycastle.jce.provider.BouncyCastleProvider; import org.glassfish.jersey.server.ResourceConfig; import java.security.Security; import java.util.ArrayList; import java.util.Collections; import java.util.List; @ApplicationPath("/") public class AppConfig extends ResourceConfig { private static ArrayList<GSession> _sessions = new ArrayList<>(); /** * Κάθε πρόσβαση στην list πρέπει να γίνεται με κλήση μεθόδων της sessions για να είναι thread safe h list. * Σε κάθε άλλη περίπτωση πρέπει να γίνει χρήση της syncronize. * Ας πούμε αν χρησιμοποιήσουμε έναν iterator αυτός δεν συγχρονίζεται οπότε ενώ είμαστε σε κάποιο node μπορεί * να τον πειράξει και κάποιο άλλο thread οπότε πρέπει να συγχρονίσουμε την πρόσβαση με χρήση της syncronize. */ public static List<GSession> sessions = Collections.synchronizedList(_sessions); public AppConfig() { Security.addProvider(new BouncyCastleProvider()); } }
northdigital/GDPRAppServer
src/main/java/gr/northdigital/gdpr/AppConfig.java
1,057
package com.example.androidergasia; public class Reservation { private int placeId; private String date; private String dateTime; private int numberOfPeople; private String nameOfPlace; private int reservationID; public String getNameOfPlace() { return nameOfPlace; } public int getReservationID() { return reservationID; } public Reservation(int placeId, String date, String dateTime, int numberOfPeople) { this.placeId = placeId; this.date = date; this.dateTime = dateTime; this.numberOfPeople = numberOfPeople; } /** * Αυτός ο constructor χρημιμοποιείται απο την κλάση reservationsRecyclerAdapter */ public Reservation(String date, String time, String nameOfPlace, int numberOfPeople,int reservationID) { this.date = date; this.dateTime = time; this.nameOfPlace = nameOfPlace; this.numberOfPeople = numberOfPeople; this.reservationID = reservationID; } public int getPlaceId(){ return placeId; } public String getDate(){ return date; } public String getDateTime(){ return dateTime; } public int getNumberOfPeople(){ return numberOfPeople; } }
StylianosBairamis/ReserveIT
app/src/main/java/com/example/androidergasia/Reservation.java
1,058
package gui; import api.AllUsers; import api.CurrentUser; import api.User; import javax.swing.*; import java.awt.*; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.WindowAdapter; import java.awt.event.WindowEvent; import java.util.Objects; public class SignInFrame { private JFrame frame; private JPanel panel; private JLabel userLab,passLab; private JTextField userText; private JPasswordField passText; private JButton buttonSignUp,buttonSignIn,buttonDelete; public SignInFrame(AllUsers users,MainFrame mainFrame){ frame = new JFrame("Σύνδεση"); frame.setDefaultCloseOperation(JFrame.HIDE_ON_CLOSE); frame.addWindowListener(new WindowAdapter() { @Override public void windowClosing(WindowEvent e) { Main.onExit(); } }); frame.setSize(450,300); frame.setResizable(false); Toolkit t = Toolkit.getDefaultToolkit(); Dimension d = t.getScreenSize(); frame.setLocation((d.width - frame.getWidth()) / 2, (d.height - frame.getHeight()) / 2); panel = new JPanel(); GridLayout gridLayout = new GridLayout(4,2,10,10); panel.setLayout(gridLayout); panel.setBackground(new Color(188,184,185)); panel.setBorder(BorderFactory.createEmptyBorder(20,20,20,20)); userLab = new JLabel("Όνομα χρήστη"); passLab = new JLabel("Κωδικός"); userText = new JTextField(""); passText = new JPasswordField(""); JLabel empty = new JLabel(""); buttonSignIn = new JButton("Είσοδος"); buttonSignIn.setBackground(new Color(144,144,144)); buttonSignIn.setPreferredSize(new Dimension(100,30)); buttonSignIn.addActionListener(new AbstractAction() { @Override public void actionPerformed(ActionEvent actionEvent) { String username = userText.getText(); String password = passText.getText(); User user = users.searchUserByUsername(username); if(user != null){ if(Objects.equals(user.getPassword(), password)){ // Connect setVisible(false); mainFrame.setVisible(true); userText.setText(""); passText.setText(""); CurrentUser.setCurrentUser(user); } } else{ JOptionPane.showMessageDialog(frame, "Ο χρήστης δεν υπάρχει. Προσπαθήστε ξανά."); } } }); buttonSignIn.setFont(new Font("Serif",Font.BOLD,22)); buttonSignUp = new JButton("Εγγραφή"); buttonSignUp.setBackground(new Color(144,144,144)); buttonSignUp.setPreferredSize(new Dimension(100,30)); buttonSignUp.addActionListener(new AbstractAction() { @Override public void actionPerformed(ActionEvent actionEvent) { JFrame signUp = new JFrame("Εγγραφή"); signUp.setDefaultCloseOperation(JFrame.HIDE_ON_CLOSE); signUp.addWindowListener(new WindowAdapter() { @Override public void windowClosing(WindowEvent e) { Main.onExit(); } }); signUp.setSize(450,300); signUp.setResizable(false); Toolkit t = Toolkit.getDefaultToolkit(); Dimension d = t.getScreenSize(); signUp.setLocation((d.width - frame.getWidth()) / 2, (d.height - frame.getHeight()) / 2); JLabel nameLab,surnameLab,userlab,passlab,pass2Lab; JTextField nameText,surnameText,usertext,passtext; JPasswordField pass2Text; JLabel emptyLab = new JLabel(""); JCheckBox bx1 = new JCheckBox("Πάροχος"); JCheckBox bx2 = new JCheckBox("Χρήστης"); nameLab = new JLabel("Όνομα"); surnameLab = new JLabel("Επίθετο"); userlab = new JLabel("Όνομα χρήστη"); passlab = new JLabel("Κωδικός"); pass2Lab = new JLabel("Επαλήθευση"); nameText = new JTextField(""); surnameText = new JTextField(""); usertext = new JTextField(""); passtext = new JTextField(""); pass2Text = new JPasswordField(""); JButton sign = new JButton("Εγγραφή"); sign.setBackground(new Color(144,144,144)); sign.setFont(new Font("Serif",Font.BOLD,22)); sign.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent actionEvent) { String temp1,temp2,temp3,temp4,temp5; temp1 = nameText.getText(); temp2 = surnameText.getText(); temp3 = usertext.getText(); temp4 = passtext.getText(); char[] temp = pass2Text.getPassword(); temp5 = String.valueOf(temp); if(temp1.isEmpty() || temp2.isEmpty() || temp3.isEmpty() || temp4.isEmpty() || temp5.isEmpty() || (!bx1.isSelected() && !bx2.isSelected())){ JOptionPane.showMessageDialog(frame, "Κάποιο από τα πεδία είναι κενό. Προσπαθήστε ξανά."); } else if(!temp4.equals(temp5)){ JOptionPane.showMessageDialog(frame, "Ο κωδικός πρέπει να είναι ίδιος. Προσπαθήστε ξανά."); } else{ User us; if(bx1.isSelected()) { us = new User(temp1,temp2,temp3,temp4,"provider"); } else{ us = new User(temp1,temp2,temp3,temp4,"user"); } for(User user : Main.users.getAllUsers()){ if(temp3.equals(user.getUsername())){ JOptionPane.showMessageDialog(frame, "Το συγκεκριμένο όνομα χρήστη δεν είναι διαθέσιμο. Επιλέξτε ένα διαφορετικό."); return; } } JOptionPane.showMessageDialog(frame, "Επιτυχής εγγραφή."); signUp.setVisible(false); frame.setVisible(true); // Add the new user to the AllUsers object Main.users.addUser(us); } } }); JPanel pan = new JPanel(); GridLayout grid = new GridLayout(7,2,10,10); pan.setLayout(grid); pan.setBackground(new Color(188,184,185)); pan.setBorder(BorderFactory.createEmptyBorder(20,20,20,20)); pan.add(nameLab); pan.add(nameText); pan.add(surnameLab); pan.add(surnameText); pan.add(userlab); pan.add(usertext); pan.add(passlab); pan.add(passtext); pan.add(pass2Lab); pan.add(pass2Text); ButtonGroup bg = new ButtonGroup(); bg.add(bx1); bg.add(bx2); pan.add(bx1); pan.add(emptyLab); pan.add(bx2); pan.add(sign); signUp.add(pan); setVisible(false); signUp.setVisible(true); } }); buttonSignUp.setFont(new Font("Serif",Font.BOLD,22)); buttonDelete = new JButton("Διαγραφή Λογαριασμού"); buttonDelete.setBackground(new Color(144,144,144)); buttonDelete.setPreferredSize(new Dimension(100,30)); buttonDelete.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent actionEvent) { JFrame fr = new JFrame("Διαγραφή Λογαριασμού"); fr.setDefaultCloseOperation(JFrame.HIDE_ON_CLOSE); fr.addWindowListener(new WindowAdapter() { @Override public void windowClosing(WindowEvent e) { Main.onExit(); } }); fr.setSize(400,250); fr.setResizable(false); Toolkit t = Toolkit.getDefaultToolkit(); Dimension d = t.getScreenSize(); fr.setLocation((d.width - frame.getWidth()) / 2, (d.height - frame.getHeight()) / 2); JPanel pane1 = new JPanel(); GridLayout gridLayout = new GridLayout(3,2,10,10); pane1.setLayout(gridLayout); pane1.setBackground(new Color(188,184,185)); pane1.setBorder(BorderFactory.createEmptyBorder(20,20,20,20)); JLabel user2 = new JLabel("Όνομα χρήστη"); JLabel pass2 = new JLabel("Κωδικός"); JTextField userText2 = new JTextField(""); JTextField passText2 = new JPasswordField(""); //JLabel empty2 = new JLabel(""); JButton butt1 = new JButton("Διαγραφή"); butt1.setBackground(new Color(144,144,144)); butt1.setFont(new Font("Serif",Font.BOLD,22)); butt1.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent actionEvent) { User u; String name = userText2.getText(); String password = passText2.getText(); if(!name.isEmpty() && !password.isEmpty()) { u = Main.users.searchUserByUsername(name); if(u != null){ if(Objects.equals(u.getPassword(), password)){ Main.users.removeUser(u); JOptionPane.showMessageDialog(frame, "Ο χρήστης διαγράφηκε με επιτυχία."); fr.setVisible(false); setVisible(true); } else{ JOptionPane.showMessageDialog(frame, "Λάθος κωδικός."); } } else{ JOptionPane.showMessageDialog(frame, "Ο χρήστης αυτός δεν υπάρχει."); } } else{ JOptionPane.showMessageDialog(frame, "Το πεδίο είναι κενό. Προσπαθήστε ξανά."); } } }); JButton butt2 = new JButton("Πίσω"); butt2.setBackground(new Color(144,144,144)); butt2.setFont(new Font("Serif",Font.BOLD,22)); butt2.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent actionEvent) { fr.setVisible(false); setVisible(true); } }); pane1.add(user2); pane1.add(userText2); pane1.add(pass2); pane1.add(passText2); pane1.add(butt2); pane1.add(butt1); fr.add(pane1); setVisible(false); fr.setVisible(true); } }); panel.add(userLab); panel.add(userText); panel.add(passLab); panel.add(passText); panel.add(buttonDelete); panel.add(empty); panel.add(buttonSignUp); panel.add(buttonSignIn); frame.add(panel); } public void setVisible(boolean b){ frame.setVisible(b); } }
AnestisZotos/Accommodations-rating-platform
gui/SignInFrame.java
1,060
import java.io.IOException; import java.util.*; /** * Βοηθητική κλάση που χειρίζεται τις ημερομηνίες κράτησης στο πρόγραμμα. * Αποτελείται από μία βάση δεδομένων για την αποθήκευση των κρατήσεων, αλλά και απο αντικείμενα Date * που δημιουργήθηκαν για πιο εύκολη σύγκριση χρονικών περιόδων */ public class Date { /** * Η βάση δεδομένων που αποθηκεύει τις ημερομηνίες κρατήσεων */ public static Database dateabase; public int year; public int month; public int day; //Θεωρούμε πως κάθε μήνας έχει 30 ημέρες //Basic Methods //---------------------------------------------------------------------------------------------------------------------- /** * Αυτός ο constructor δημιουργεί ημερομηνίες με συγκεκριμένες τιμές για το έτος το μήνα και τη μέρα * @param day * @param month * @param year */ public Date(int day, int month, int year) { if (day < 0 || day > 30) { System.out.println("Day must be between 1 and 30"); return; } if (month < 0 || month > 12) { System.out.println("Month must be between 1 and 12"); return; } if (year < 2021) { System.out.println("Year must be after 2021"); return; } this.day = day; this.month = month; this.year = year; } /** *Αυτός ο constructor δημιουργεί ημερομηνίες απο String το οποίο διαβάζει και μεταφράζει *(Αρκεί το String αυτό να δημιουργήθηκε από την Date.toString()) */ public Date(String dateString) { Scanner parser = new Scanner(dateString); int day = parser.nextInt(); int month = parser.nextInt(); int year = parser.nextInt(); parser.close(); if (day < 0 || day > 30) { System.out.println("Day must be between 1 and 30"); return; } if (month < 0 || month > 12) { System.out.println("Month must be between 1 and 12"); return; } if (year < 2021) { System.out.println("Year must be after 2021"); return; } this.day = day; this.month = month; this.year = year; } /** * Προσθέτει μία κράτηση στο database * @param id το id του καταλύματος που θα κρατηθεί * @param user το username του χρήστη που κάνει την κράτηση * @param date η ημερομηνία της κράτησης * @return τη θέση του database που μπήκε η ημερομηνία */ public static int addDate(String id, String user, Date date) { return dateabase.add(id, user, date.toString()); } /** * Διαγράφει μία κράτηση από το database * @param id το id του καταλύματος * @param user το username του χρήστη που είχε κάνει την κράτηση * @param date η ημερομηνία της κράτησης * @return τη θέση του database από όπου διαγράφτηκε η ημερομηνία */ public static int removeDate(String id, String user, Date date) { return dateabase.remove(id, user, date.toString()); } //Comparative Methods (Methods that handle two dates and the ones in between) //---------------------------------------------------------------------------------------------------------------------- /** * Συγκρίνει δύο Date και μας λέει αν είναι ίδια ή όχι */ @Override public boolean equals(Object other) { if (!(other instanceof Date)) { return false; } if (other == this) { return true; } if (this.day == ((Date) other).day && this.month == ((Date) other).month && this.year == ((Date) other).year) { return true; } else return false; } /** * Συγκρίνει δύο ημερομηνίες * * @param date1 * @param date2 * @return <p>1 αν η πρώτη είναι μετά από τη δεύτερη</p> * <p>-1 αν η δεύτερη είναι μετά από την πρώτη</p> * <p>0 αν είναι η ίδια ημερομηνία</p> */ public static int compare(Date date1, Date date2) { if (date1.equals(date2)) { return 0; } if (date1.year > date2.year) { return 1; } else if (date1.year < date2.year) { return -1; } else { if (date1.month > date2.month) { return 1; } else if (date1.month < date2.month) { return -1; } else { if (date1.day > date2.day) { return 1; } else { return -1; } } } } /** * @return Ένα ArrayList με όλες τις ημερομηνίες ανάμεσα στην πρώτη και τη δεύτερη */ public static ArrayList<Date> getBetween(Date date1, Date date2) { ArrayList<Date> betweens = new ArrayList<>(); if (compare(date1, date2) == 0) return null; if (compare(date1, date2) == 1) { Date temp = new Date(date1.day, date1.month, date1.year); date1 = date2; date2 = temp; } int y, m, d; for (y = date1.year; y <= date2.year; y++) //start at the first year and finish in the last { int startMonth = 1; int endMonth = 12; if (y == date1.year) //if this is the first loop we should only add the months after the first date { startMonth = date1.month; } if (y == date2.year)//if this is the last loop we should only add the months before the last date { endMonth = date2.month; } for (m = startMonth; m <= endMonth; m++) { int startDay = 1; int endDay = 30; if (y == date1.year && m == date1.month) //if this is the first loop we should only add the dates after the first date { startDay = date1.day + 1; } if (y == date2.year && m == date2.month) //if this is the last loop we should only add the dates before the last date { endDay = date2.day - 1; } for (d = startDay; d <= endDay; d++) { betweens.add(new Date(d, m, y)); } } } return betweens; } /** * @return Ένα HashSet με τα ids όλων των καταλυμάτων που δεν είναι κρατημένα σε αυτό το χρονικό διάστημα */ public static HashSet<String> getAvailableBetween(Date date1,Date date2) { HashSet<String> ids = new HashSet<>(); ArrayList<Date> inbetweens = getBetween(date1,date2); for (String tId: dateabase.getCategorySet()) { int from = dateabase.search(tId,SearchType.first); int to = dateabase.search(tId,SearchType.last); boolean available = true; for (int i = from ; i <= to ; i++) { Date tDate = new Date(dateabase.get(2,i)); for (Date date:inbetweens) { if (date.equals(tDate)) { available = false; break; } } } if (available) { ids.add(tId); } } return ids; } //Holistic Methods (work with all the data in the database) //---------------------------------------------------------------------------------------------------------------------- /** * Φορτίζει τις αλλαγές που έγιναν κατά την εκτέλεση του προγράμματος στο εξωτερικό μέρος του dateabase (το αρχείο .txt) * ΠΡΟΣΟΧΗ: Πρέπει να καλείται πάντα στο τέλος του προγράμματος */ public static void updateDatabase() throws IOException { dateabase.update(); } /** * Δημιουργεί καινούργιο database με το όνομα που του δίνεται για τις ημερομηνίες κράτησης ΟΛΩΝ των καταλυμάτων * (και αυτόματα φορτίζει και τα δεδομένα της) * ΠΡΟΣΟΧΗ: Πρέπει να καλείται στην αρχή κάθε προγράμματος * * @param filename Το όνομα του φακέλου που θα εμπεριέχει το dateabase */ public static void initializeDatabase(String filename) throws IOException { dateabase = new Database(filename); } //Helper methods (Help with other methods and smaller stuff) //---------------------------------------------------------------------------------------------------------------------- /** * Μετατρέπει μία ημερομηνία σε (δυσανάγνωστο) String για την μετάφραση απο και προς το database */ @Override public String toString() { StringBuilder dateString = new StringBuilder(); dateString.append(day); dateString.append(" "); dateString.append(month); dateString.append(" "); dateString.append(year); return dateString.toString(); } /** * Όπως το toString() αλλά πιο ευανάγνωστο */ public String toHumanString() { StringBuilder dateString = new StringBuilder(); dateString.append(day); dateString.append("/"); dateString.append(month); dateString.append("/"); dateString.append(year); return dateString.toString(); } /** * Γράφει την ημερομηνία σε ευανάγνωστη μορφή στο terminal */ public void print() { System.out.println(this.day + "/" + this.month + "/" + this.year); } /** * @param dates ένα σύνολο από ημερομηνίες * @return την πρώτη (χρονολογικά) από τις ημερομηνίες που δόθηκαν */ public static Date getFirst(HashSet<Date> dates) { Date min = new Date(12,12,3000); for (Date date:dates) { if(Date.compare(date,min) == -1) { min = date; } } return min; } /** * @param dates ένα σύνολο από ημερομηνίες * @return την τελευτάια (χρονολογικά) από τις ημερομηνίες που δόθηκαν */ public static Date getLast(HashSet<Date> dates) { Date max = new Date(1,1,2021); for (Date date:dates) { if(Date.compare(date,max) == 1) { max = date; } } return max; } /** * @param id ενός καταλύματος * @param username ενός χρήστη * @return Όλες τις ημερομηνίες για τις οποίες ο χρήστης αυτός έχει κάνει κράτηση σε ένα κατάλυμα */ public static HashSet<Date> getDatesFor(String id,String username) { HashSet<Date> dates = new HashSet<>(); Date nullDate = new Date(1,1,2021); int from = dateabase.search(id,username,SearchType.first); int to = dateabase.search(id,username,SearchType.last); if (from == -1) return dates; for (int i = from;i<=to;i++) { Date tDate = new Date(dateabase.get(2,i)); if(!tDate.equals(nullDate)) { dates.add(tDate); } } return dates; } }
KonnosBaz/AUTh_CSD_Projects
Object Oriented Programming (2021)/src/Date.java
1,061
/* * Copyright 2007,2016 EUROPEAN UNION * Licensed under the EUPL, Version 1.2 or - as soon they will be approved by * the European Commission - subsequent versions of the EUPL (the "Licence"); * You may not use this work except in compliance with the Licence. * You may obtain a copy of the Licence at: * * https://ec.europa.eu/isa2/solutions/european-union-public-licence-eupl_en * * Unless required by applicable law or agreed to in writing, software * distributed under the Licence is distributed on an "AS IS" basis, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the Licence for the specific language governing permissions and * limitations under the Licence. * * Date: 2020/05/11 * Authors: * European Commission, Joint Research Centre - [email protected] * * This work was supported by the Interoperability solutions for public * administrations, businesses and citizens programme (http://ec.europa.eu/isa2) * through Action 2016.10: European Location Interoperability Solutions for e-Government (ELISE) */ package eu.europa.ec.re3gistry2.migration.manager; import eu.europa.ec.re3gistry2.base.utility.BaseConstants; import eu.europa.ec.re3gistry2.crudimplementation.RegFieldManager; import eu.europa.ec.re3gistry2.crudimplementation.RegGroupManager; import eu.europa.ec.re3gistry2.crudimplementation.RegItemManager; import eu.europa.ec.re3gistry2.crudimplementation.RegItemclassManager; import eu.europa.ec.re3gistry2.crudimplementation.RegItemclasstypeManager; import eu.europa.ec.re3gistry2.javaapi.handler.RegInstallationHandler; import eu.europa.ec.re3gistry2.javaapi.solr.SolrHandler; import eu.europa.ec.re3gistry2.migration.migrationmodel.Registry; import eu.europa.ec.re3gistry2.model.RegField; import eu.europa.ec.re3gistry2.model.RegGroup; import eu.europa.ec.re3gistry2.model.RegItem; import eu.europa.ec.re3gistry2.model.RegItemclass; import eu.europa.ec.re3gistry2.model.RegItemclasstype; import eu.europa.ec.re3gistry2.model.uuidhandlers.RegItemclassUuidHelper; import java.util.ArrayList; import javax.persistence.EntityManager; import javax.persistence.Query; import org.apache.logging.log4j.Logger; public class MigrateExtensiblityAndGovernanceLevel { private final EntityManager entityManagerRe3gistry2; private final EntityManager entityManagerRe3gistry2Migration; private final Logger logger; private final MigrationManager migrationManager; private final String QUERY_ITEMCLASS_1 = "INSERT INTO public.reg_itemclass VALUES ('09f068599d89407a4fd5b48d8ad58061', 'governance-level', 'BASE_URI_REGISTRY', true, true, 'REGISTRY_ITEMCLASS_UUID', '2', '1', 'DATAPROCEDUREORDER', '2019-07-19 15:56:43.784', NULL);"; private final String QUERY_ITEMCLASS_2 = "INSERT INTO public.reg_itemclass VALUES ('233b80ac5ad1731cb789f3dbf33811b7', 'governance-level-item', NULL, false, true, '09f068599d89407a4fd5b48d8ad58061', '3', '1', 'DATAPROCEDUREORDER', '2019-07-19 15:56:43.838', NULL);"; private final String QUERY_ITEMCLASS_3 = "INSERT INTO public.reg_itemclass VALUES ('4d843e0e6ac86113f543de29b0c8e81d', 'extensibility', 'BASE_URI_REGISTRY', true, true, 'REGISTRY_ITEMCLASS_UUID', '2', '1', 'DATAPROCEDUREORDER', '2019-07-30 09:30:44.656', NULL);"; private final String QUERY_ITEMCLASS_4 = "INSERT INTO public.reg_itemclass VALUES ('1053ab3f4a9e29a3d6d24d1ac5125667', 'extensibility-item', NULL, false, true, '4d843e0e6ac86113f543de29b0c8e81d', '3', '1', 'DATAPROCEDUREORDER', '2019-07-30 09:30:44.765', NULL);"; private final String QUERY_FIELDMAPPING = "INSERT INTO public.reg_fieldmapping VALUES ('549ffecfbf23afd16ac4ccf2fbb8179c', 'FIELD_CONTENTBODY_UUID', '09f068599d89407a4fd5b48d8ad58061', 5, false, '1', true, false, false, '2019-07-19 15:56:43.801', NULL, false);\n" + "INSERT INTO public.reg_fieldmapping VALUES ('0fb4ae52510a5df95fada92f2c52c79b', 'FIELD_REGISTERMANAGER_UUID', '09f068599d89407a4fd5b48d8ad58061', 3, false, '1', true, false, false, '2019-07-19 15:56:43.801', NULL, false);\n" + "INSERT INTO public.reg_fieldmapping VALUES ('f5c840d507b4e3b2559715458d2ec5e9', 'FIELD_SUBMITTINGORGANIZATION_UUID', '09f068599d89407a4fd5b48d8ad58061', 6, false, '1', true, false, true, '2019-07-19 15:56:43.801', NULL, false);\n" + "INSERT INTO public.reg_fieldmapping VALUES ('189e1b8132d0efcd414d52f68f1deb58', 'FIELD_CONTENTSUMMARY_UUID', '09f068599d89407a4fd5b48d8ad58061', 1, true, '1', true, false, false, '2019-07-19 15:56:43.801', NULL, false);\n" + "INSERT INTO public.reg_fieldmapping VALUES ('6d488bd3698fc50a23f6fe32391e0b4c', 'FIELD_LABEL_UUID', '09f068599d89407a4fd5b48d8ad58061', 0, true, '1', true, false, false, '2019-07-19 15:56:43.801', NULL, false);\n" + "INSERT INTO public.reg_fieldmapping VALUES ('617f610e036020b86dfa7d20c5394c9e', 'FIELD_STATUS_UUID', '09f068599d89407a4fd5b48d8ad58061', 2, true, '1', true, false, false, '2019-07-19 15:56:43.801', NULL, false);\n" + "INSERT INTO public.reg_fieldmapping VALUES ('5e63e42ebdf0f501692f736c9765d5bf', 'FIELD_REGISTEROWNER_UUID', '09f068599d89407a4fd5b48d8ad58061', 4, false, '1', true, false, false, '2019-07-19 15:56:43.801', NULL, false);\n" + "INSERT INTO public.reg_fieldmapping VALUES ('c61b272097d17e920244d60a855649ed', 'FIELD_DEFINITION_UUID', '233b80ac5ad1731cb789f3dbf33811b7', 1, true, '1', true, false, false, '2019-07-19 15:56:43.849', NULL, false);\n" + "INSERT INTO public.reg_fieldmapping VALUES ('e6be9e7bf3984c9cb149816ea5532a57', 'FIELD_STATUS_UUID', '233b80ac5ad1731cb789f3dbf33811b7', 2, true, '1', true, false, false, '2019-07-19 15:56:43.849', NULL, false);\n" + "INSERT INTO public.reg_fieldmapping VALUES ('819e2d846d6d64d7e5a4f87fc26b9996', 'FIELD_LABEL_UUID', '233b80ac5ad1731cb789f3dbf33811b7', 0, true, '1', true, false, false, '2019-07-19 15:56:43.849', NULL, false);\n" + "INSERT INTO public.reg_fieldmapping VALUES ('25d75c262d052475cc7ae86f439364b6', 'FIELD_CONTENTBODY_UUID', '4d843e0e6ac86113f543de29b0c8e81d', 5, false, '1', true, false, false, '2019-07-30 09:30:44.703', NULL, false);\n" + "INSERT INTO public.reg_fieldmapping VALUES ('407b742be797baad13c0c4a804fada78', 'FIELD_REGISTERMANAGER_UUID', '4d843e0e6ac86113f543de29b0c8e81d', 3, false, '1', true, false, false, '2019-07-30 09:30:44.703', NULL, false);\n" + "INSERT INTO public.reg_fieldmapping VALUES ('92ffa2daab988bf7776fc32a656b2053', 'FIELD_CONTENTSUMMARY_UUID', '4d843e0e6ac86113f543de29b0c8e81d', 1, true, '1', true, false, false, '2019-07-30 09:30:44.703', NULL, false);\n" + "INSERT INTO public.reg_fieldmapping VALUES ('c6d88350c419c13485dcdcff25ba464b', 'FIELD_SUBMITTINGORGANIZATION_UUID', '4d843e0e6ac86113f543de29b0c8e81d', 6, false, '1', true, false, true, '2019-07-30 09:30:44.703', NULL, false);\n" + "INSERT INTO public.reg_fieldmapping VALUES ('5584f27e4c31661f6ddd24da9f177ee1', 'FIELD_LABEL_UUID', '4d843e0e6ac86113f543de29b0c8e81d', 0, true, '1', true, false, false, '2019-07-30 09:30:44.703', NULL, false);\n" + "INSERT INTO public.reg_fieldmapping VALUES ('a9d437f0709767f5be3d1d68815fee5b', 'FIELD_STATUS_UUID', '4d843e0e6ac86113f543de29b0c8e81d', 2, true, '1', true, false, false, '2019-07-30 09:30:44.703', NULL, false);\n" + "INSERT INTO public.reg_fieldmapping VALUES ('e20e8c3c1b4a0d61cc1a914533167930', 'FIELD_REGISTEROWNER_UUID', '4d843e0e6ac86113f543de29b0c8e81d', 4, false, '1', true, false, false, '2019-07-30 09:30:44.703', NULL, false);\n" + "INSERT INTO public.reg_fieldmapping VALUES ('48ec9ccd0fa7e98fd6a374ff9c39409f', 'FIELD_DEFINITION_UUID', '1053ab3f4a9e29a3d6d24d1ac5125667', 1, true, '1', true, false, false, '2019-07-30 09:30:44.765', NULL, false);\n" + "INSERT INTO public.reg_fieldmapping VALUES ('5430d51618a0be29084b5745c63fa83d', 'FIELD_STATUS_UUID', '1053ab3f4a9e29a3d6d24d1ac5125667', 2, true, '1', true, false, false, '2019-07-30 09:30:44.765', NULL, false);\n" + "INSERT INTO public.reg_fieldmapping VALUES ('44877fee54e2c8e153aeff694de6e3e9', 'FIELD_LABEL_UUID', '1053ab3f4a9e29a3d6d24d1ac5125667', 0, true, '1', true, false, false, '2019-07-30 09:30:44.765', NULL, false);"; private final String QUERY_ITEM = "INSERT INTO public.reg_item VALUES ('050ef0d0e3bb244923bd94c183852445', 'governance-level', '09f068599d89407a4fd5b48d8ad58061', '1', NULL, false, 0, '2019-07-19 15:57:31.852', NULL, 'USERMIGRATION_UUID', true);\n" + "INSERT INTO public.reg_item VALUES ('5247138f69b59f59ddacf742cdb5b448', 'eu-legal', '233b80ac5ad1731cb789f3dbf33811b7', '1', NULL, false, 0, '2019-07-30 09:25:06.544', '2019-07-29 17:09:47.852', 'USERMIGRATION_UUID', false);\n" + "INSERT INTO public.reg_item VALUES ('24bb2984999c116018d3ba95c1aa3082', 'eu-technical', '233b80ac5ad1731cb789f3dbf33811b7', '1', NULL, false, 0, '2019-07-31 11:07:50.016', '2019-07-31 11:07:50.011398', 'USERMIGRATION_UUID', false);\n" + "INSERT INTO public.reg_item VALUES ('e7462cf53d17f16c4c0f8e48d40055a7', 'eu-good-practice', '233b80ac5ad1731cb789f3dbf33811b7', '1', NULL, false, 0, '2021-04-15 11:07:50.016', '2021-04-15 11:07:50.011398', 'USERMIGRATION_UUID', false);\n" + "INSERT INTO public.reg_item VALUES ('a2290d202bbd591377234ce2eee350df', 'extensibility', '4d843e0e6ac86113f543de29b0c8e81d', '1', NULL, false, 0, '2019-07-30 10:56:01.607', '2019-07-30 10:56:01.548234', 'USERMIGRATION_UUID', false);\n" + "INSERT INTO public.reg_item VALUES ('aad13ff0ff9fb151cb8410801e4eeb0a', 'open', '1053ab3f4a9e29a3d6d24d1ac5125667', '1', NULL, false, 0, '2019-07-30 14:33:39.699', '2019-07-30 14:33:39.601507', 'USERMIGRATION_UUID', false);\n" + "INSERT INTO public.reg_item VALUES ('31082311814c08a2ae0e5e647669c73f', 'none', '1053ab3f4a9e29a3d6d24d1ac5125667', '1', NULL, false, 0, '2019-07-30 14:33:47.792', '2019-07-30 14:33:47.695846', 'USERMIGRATION_UUID', false);\n" + "INSERT INTO public.reg_item VALUES ('088f861f19d356685c0da1916fbb260a', 'any', '1053ab3f4a9e29a3d6d24d1ac5125667', '1', NULL, false, 0, '2019-07-30 14:34:09.993', '2019-07-30 14:34:09.90134', 'USERMIGRATION_UUID', false);\n" + "INSERT INTO public.reg_item VALUES ('91e00e7f8d73c54fa2f80c67d3d9d5b0', 'narrower', '1053ab3f4a9e29a3d6d24d1ac5125667', '1', NULL, false, 0, '2019-07-30 14:35:08.175', '2019-07-30 14:35:08.09368', 'USERMIGRATION_UUID', false);"; String[] itemsUUID = { "050ef0d0e3bb244923bd94c183852445", "5247138f69b59f59ddacf742cdb5b448", "24bb2984999c116018d3ba95c1aa3082", "e7462cf53d17f16c4c0f8e48d40055a7", "a2290d202bbd591377234ce2eee350df", "aad13ff0ff9fb151cb8410801e4eeb0a", "31082311814c08a2ae0e5e647669c73f", "088f861f19d356685c0da1916fbb260a", "91e00e7f8d73c54fa2f80c67d3d9d5b0"}; private final String QUERY_ITEM_GROUP_ROLE = "INSERT INTO public.reg_item_reg_group_reg_role_mapping VALUES ('690a97c469c9979230df939d5b3f3ae5', '050ef0d0e3bb244923bd94c183852445', 'GROUP_REGISTERMANAGER_UUID', '2', '2019-07-19 15:57:31.899', NULL);\n" + "INSERT INTO public.reg_item_reg_group_reg_role_mapping VALUES ('f6d77d88d315b56005bd04e1e1e3634e', '050ef0d0e3bb244923bd94c183852445', 'GROUP_CONTENTBODY_UUID', '4', '2019-07-19 15:57:31.904', NULL);\n" + "INSERT INTO public.reg_item_reg_group_reg_role_mapping VALUES ('3ab3f7c6738165d1f1c26dba97c3063e', '050ef0d0e3bb244923bd94c183852445', 'GROUP_SUBMITTINGORGANIZATION_UUID', '5', '2019-07-19 15:57:31.908', NULL);\n" + "INSERT INTO public.reg_item_reg_group_reg_role_mapping VALUES ('eb04b2c72c9d80b77e2f1e872b600464', 'a2290d202bbd591377234ce2eee350df', 'GROUP_REGISTEROWNER_UUID', '3', '2019-07-30 10:34:07.426', NULL);\n" + "INSERT INTO public.reg_item_reg_group_reg_role_mapping VALUES ('02fbd1b2b20bbc6027b6ae27f8c4c638', 'a2290d202bbd591377234ce2eee350df', 'GROUP_REGISTERMANAGER_UUID', '2', '2019-07-30 10:34:07.442', NULL);\n" + "INSERT INTO public.reg_item_reg_group_reg_role_mapping VALUES ('21863b78bcbe549879778f5b6197cc28', 'a2290d202bbd591377234ce2eee350df', 'GROUP_CONTENTBODY_UUID', '4', '2019-07-30 10:34:07.446', NULL);\n" + "INSERT INTO public.reg_item_reg_group_reg_role_mapping VALUES ('6caf0d9f6da96458c1db9a5e44f7a380', 'a2290d202bbd591377234ce2eee350df', 'GROUP_SUBMITTINGORGANIZATION_UUID', '5', '2019-07-30 10:34:07.449', NULL);"; private final String QUERY_RELATION = "INSERT INTO public.reg_relation VALUES ('3d342b5c93bbc62011c5ee983b59e4d6', '050ef0d0e3bb244923bd94c183852445', '1', 'REGISTRY_UUID', '2019-07-19 15:57:31.861', NULL);\n" + "INSERT INTO public.reg_relation VALUES ('9a774ff38b9efe06876169cf5ec80ba1', '5247138f69b59f59ddacf742cdb5b448', '1', 'REGISTRY_UUID', '2019-07-30 09:25:06.591', NULL);\n" + "INSERT INTO public.reg_relation VALUES ('a92761d17cc0630afb859df3c59985df', '5247138f69b59f59ddacf742cdb5b448', '2', '050ef0d0e3bb244923bd94c183852445', '2019-07-30 09:25:06.591', NULL);\n" + "INSERT INTO public.reg_relation VALUES ('dddfb7c954965948bd515f542f15f5ed', 'a2290d202bbd591377234ce2eee350df', '1', 'REGISTRY_UUID', '2019-07-30 10:34:07.396', NULL);\n" + "INSERT INTO public.reg_relation VALUES ('99beb008e7755f6991a01214f9e8c53b', '91e00e7f8d73c54fa2f80c67d3d9d5b0', '1', 'REGISTRY_UUID', '2019-07-30 10:41:43.879', NULL);\n" + "INSERT INTO public.reg_relation VALUES ('9f3b664331a45827a1d9f2b87f3987d7', '91e00e7f8d73c54fa2f80c67d3d9d5b0', '2', 'a2290d202bbd591377234ce2eee350df', '2019-07-30 10:41:43.879', NULL);\n" + "INSERT INTO public.reg_relation VALUES ('519e987ebea57b8399b7413168dc41c7', '088f861f19d356685c0da1916fbb260a', '1', 'REGISTRY_UUID', '2019-07-30 10:45:49.888', NULL);\n" + "INSERT INTO public.reg_relation VALUES ('9e147ef61e15460d6e3f12ba681e75b6', '088f861f19d356685c0da1916fbb260a', '2', 'a2290d202bbd591377234ce2eee350df', '2019-07-30 10:45:49.888', NULL);\n" + "INSERT INTO public.reg_relation VALUES ('2fbc99dbf6f7564f8e6323d124d270f8', 'aad13ff0ff9fb151cb8410801e4eeb0a', '1', 'REGISTRY_UUID', '2019-07-30 10:45:51.981', NULL);\n" + "INSERT INTO public.reg_relation VALUES ('b8e6350c84fd8d646471ca53c7a2b8e9', 'aad13ff0ff9fb151cb8410801e4eeb0a', '2', 'a2290d202bbd591377234ce2eee350df', '2019-07-30 10:45:51.981', NULL);\n" + "INSERT INTO public.reg_relation VALUES ('cdbafce40ef0bd588686e936eee8a30d', '31082311814c08a2ae0e5e647669c73f', '2', 'a2290d202bbd591377234ce2eee350df', '2019-07-30 10:46:04.223', NULL);\n" + "INSERT INTO public.reg_relation VALUES ('9499c1e96e073a939393ecd3b6b33508', '31082311814c08a2ae0e5e647669c73f', '1', 'REGISTRY_UUID', '2019-07-30 10:46:04.223', NULL);\n" + "INSERT INTO public.reg_relation VALUES ('20edf377e7c22992aff2102ecc7a3a63', '24bb2984999c116018d3ba95c1aa3082', '1', 'REGISTRY_UUID', '2019-07-31 11:05:04.812', NULL);\n" + "INSERT INTO public.reg_relation VALUES ('e0670112b1d4ee26027689d8c625a5ac', '24bb2984999c116018d3ba95c1aa3082', '2', '050ef0d0e3bb244923bd94c183852445', '2019-07-31 11:05:04.812', NULL);" + "INSERT INTO public.reg_relation VALUES ('2fda34c09e874729192fb35a8f9a8dda', 'e7462cf53d17f16c4c0f8e48d40055a7', '1', 'REGISTRY_UUID', '2019-07-31 11:05:04.812', NULL);\n" + "INSERT INTO public.reg_relation VALUES ('a3cd7b9f291cf9851971f4c47509a501', 'e7462cf53d17f16c4c0f8e48d40055a7', '2', '050ef0d0e3bb244923bd94c183852445', '2019-07-31 11:05:04.812', NULL);"; private final String QUERY_GOVERNANCELEVEL = "INSERT INTO public.reg_localization VALUES ('a7a42f83dff18daf47035605d1e1d6e8', 'en', '050ef0d0e3bb244923bd94c183852445', 'FIELD_LABEL_UUID', 0, 'Governance level', NULL, NULL, NULL, '2019-07-19 15:57:31.872', NULL);\n" + "INSERT INTO public.reg_localization VALUES ('c82a9a1a2ca98853cb96c512db7f2766', 'en', '050ef0d0e3bb244923bd94c183852445', 'FIELD_CONTENTSUMMARY_UUID', 0, '<p>Level at which the item is governed.</p>', NULL, NULL, NULL, '2019-07-19 15:57:31.88', NULL);\n" + "INSERT INTO public.reg_localization VALUES ('6120284b40977e32ebee3f707db03123', 'it', '050ef0d0e3bb244923bd94c183852445', 'FIELD_LABEL_UUID', 0, 'Ambito', NULL, NULL, NULL, '2019-07-31 11:03:36.926', NULL);\n" + "INSERT INTO public.reg_localization VALUES ('6e5cb090baecd581dc81b30a215f28eb', 'it', '050ef0d0e3bb244923bd94c183852445', 'FIELD_CONTENTSUMMARY_UUID', 0, '<p>L''Ambito degli articoli del registro di INSPIRE basati sul modello concettuale generico di INSPIRE, le Direttive tecniche - specifica dei dati e del regolamento UE n 1253/2012 &amp; 1205/2008.</p>', NULL, NULL, NULL, '2019-07-31 11:03:36.926', NULL);\n" + "INSERT INTO public.reg_localization VALUES ('598bf3c8ddcfe0fe2566984f659b6a34', 'de', '050ef0d0e3bb244923bd94c183852445', 'FIELD_LABEL_UUID', 0, 'Regelungsebene', NULL, NULL, NULL, '2019-07-31 11:03:36.926', NULL);\n" + "INSERT INTO public.reg_localization VALUES ('0f30e0871fe84fa1bb5cb33cfc24b735', 'de', '050ef0d0e3bb244923bd94c183852445', 'FIELD_CONTENTSUMMARY_UUID', 0, '<p>Ebene, bei denen das Element geregelt wird.</p>', NULL, NULL, NULL, '2019-07-31 11:03:36.941', NULL);\n" + "INSERT INTO public.reg_localization VALUES ('78363d6193e8ba2e9045f9ad9bd45be2', 'el', '050ef0d0e3bb244923bd94c183852445', 'FIELD_LABEL_UUID', 0, 'Επίπεδο διαχείρισης', NULL, NULL, NULL, '2019-07-31 11:03:36.941', NULL);\n" + "INSERT INTO public.reg_localization VALUES ('f1abe5114e92844d603b9cb857e36dc4', 'el', '050ef0d0e3bb244923bd94c183852445', 'FIELD_CONTENTSUMMARY_UUID', 0, '<p>Επίπεδο κατα το οποίο το στοιχείο διαχείριζεται</p>', NULL, NULL, NULL, '2019-07-31 11:03:36.941', NULL);\n" + "INSERT INTO public.reg_localization VALUES ('a7a31b1b2f365312f834503dea826e4e', 'es', '050ef0d0e3bb244923bd94c183852445', 'FIELD_LABEL_UUID', 0, 'Nivel de gobernanza', NULL, NULL, NULL, '2019-07-31 11:03:36.941', NULL);\n" + "INSERT INTO public.reg_localization VALUES ('b66fafe6024bbc997cfc4eb62f399ddd', 'es', '050ef0d0e3bb244923bd94c183852445', 'FIELD_CONTENTSUMMARY_UUID', 0, '<p>Nivel por el que se rige el elemento</p>', NULL, NULL, NULL, '2019-07-31 11:03:36.941', NULL);\n" + "INSERT INTO public.reg_localization VALUES ('7e94620ce19eb4cb48cd62168a77907b', 'hr', '050ef0d0e3bb244923bd94c183852445', 'FIELD_LABEL_UUID', 0, 'Razina upravljanja', NULL, NULL, NULL, '2019-07-31 11:03:36.972', NULL);\n" + "INSERT INTO public.reg_localization VALUES ('9c0c9fbfce1d72f8ace5dcda23035741', 'hr', '050ef0d0e3bb244923bd94c183852445', 'FIELD_CONTENTSUMMARY_UUID', 0, '<p>Razina na kojoj se upravlja stavkom</p>', NULL, NULL, NULL, '2019-07-31 11:03:36.972', NULL);\n" + "INSERT INTO public.reg_localization VALUES ('97b329892ecae60f9a638e6ca05e3e84', 'ro', '050ef0d0e3bb244923bd94c183852445', 'FIELD_LABEL_UUID', 0, 'Nivel de guvernare', NULL, NULL, NULL, '2019-07-31 11:03:36.988', NULL);\n" + "INSERT INTO public.reg_localization VALUES ('7c5b9e9840fc9fe636684a2264d221f7', 'ro', '050ef0d0e3bb244923bd94c183852445', 'FIELD_CONTENTSUMMARY_UUID', 0, '<p>Nivelul la care elementul este reglementat.</p>', NULL, NULL, NULL, '2019-07-31 11:03:36.988', NULL);\n" + "INSERT INTO public.reg_localization VALUES ('18bef825e80b386a1635d6593d63110f', 'en', '5247138f69b59f59ddacf742cdb5b448', 'FIELD_LABEL_UUID', 0, 'Legal (EU)', NULL, NULL, NULL, '2019-07-30 09:25:06.622', NULL);\n" + "INSERT INTO public.reg_localization VALUES ('a9deff255400ff0676ca06884c9f837c', 'en', '5247138f69b59f59ddacf742cdb5b448', 'FIELD_DEFINITION_UUID', 0, '<p>The item is governed at the level of INSPIRE legal acts, including the INSPIRE Directive and Implementing Rules.</p>', NULL, NULL, NULL, '2019-07-30 09:25:06.638', NULL);\n" + "INSERT INTO public.reg_localization VALUES ('3a1c46b2a8574a31b4e25438aa988b08', 'it', '5247138f69b59f59ddacf742cdb5b448', 'FIELD_LABEL_UUID', 0, 'Linee guida tecniche sulla specifica dei dati', NULL, NULL, NULL, '2019-07-30 09:25:06.638', '2019-07-29 16:45:03.384');\n" + "INSERT INTO public.reg_localization VALUES ('cbd323257278c63b8b3f2ed2ab68415c', 'it', '5247138f69b59f59ddacf742cdb5b448', 'FIELD_DEFINITION_UUID', 0, '<p>Il contenuto del registro include ulteriori valori raccomandati dalle linee guida tecniche INSPIRE - specifiche dei dati.</p>', NULL, NULL, NULL, '2019-07-30 09:25:06.638', '2019-07-29 16:45:03.384');\n" + "INSERT INTO public.reg_localization VALUES ('86b2704624dcb7347fcc214db3543048', 'de', '5247138f69b59f59ddacf742cdb5b448', 'FIELD_LABEL_UUID', 0, 'Rechtsgültig (EU)', NULL, NULL, NULL, '2019-07-30 09:25:06.653', '2019-07-29 16:40:36.561');\n" + "INSERT INTO public.reg_localization VALUES ('6179688e29afaf463dfdd2362686cff4', 'de', '5247138f69b59f59ddacf742cdb5b448', 'FIELD_DEFINITION_UUID', 0, '<p>Das Element ist durch gesetzliche INSPIRE Bestimmungen einschließlich der INSPIRE-Richtlinie und Durchführungsbestimmungen geregelt.</p>', NULL, NULL, NULL, '2019-07-30 09:25:06.653', '2019-07-29 16:35:47.121');\n" + "INSERT INTO public.reg_localization VALUES ('5f031c642a675a0240427c9805d2a769', 'el', '5247138f69b59f59ddacf742cdb5b448', 'FIELD_LABEL_UUID', 0, 'Νομικό (ΕΕ)', NULL, NULL, NULL, '2019-07-30 09:25:06.653', '2019-07-29 16:40:36.563');\n" + "INSERT INTO public.reg_localization VALUES ('fb463530f9a2a5d8ff9a091ca02d908e', 'el', '5247138f69b59f59ddacf742cdb5b448', 'FIELD_DEFINITION_UUID', 0, '<p>Το στοιχείο διαχειριζεται στο επίπεδο των νομικώς πράξεων INSPIRE, συμπεριλαμβανομένης της οδηγίας INSPIRE και τους κανόνες εφαρμογής.</p>', NULL, NULL, NULL, '2019-07-30 09:25:06.669', '2019-07-29 16:36:23.213');\n" + "INSERT INTO public.reg_localization VALUES ('ca76242aeaf5959992d7df19a91f7dd1', 'es', '5247138f69b59f59ddacf742cdb5b448', 'FIELD_LABEL_UUID', 0, 'Legal (UE)', NULL, NULL, NULL, '2019-07-30 09:25:06.653', '2019-07-29 16:43:12.635');\n" + "INSERT INTO public.reg_localization VALUES ('42776f16401990212f7eb3d891f9d949', 'es', '5247138f69b59f59ddacf742cdb5b448', 'FIELD_DEFINITION_UUID', 0, '<p>El elemento se rige por la regulación INSPIRE, incluyendo la Directiva INSPIRE y sus reglamentos.</p>', NULL, NULL, NULL, '2019-07-30 09:25:06.669', '2019-07-29 16:43:12.635');\n" + "INSERT INTO public.reg_localization VALUES ('192de7ef7a44c56d831c03cd7f7b0c50', 'hr', '5247138f69b59f59ddacf742cdb5b448', 'FIELD_LABEL_UUID', 0, 'Pravni (EU)', NULL, NULL, NULL, '2019-07-30 09:25:06.669', '2019-07-29 16:44:41.928');\n" + "INSERT INTO public.reg_localization VALUES ('3541b84bdc50ad42181ec27279779eff', 'hr', '5247138f69b59f59ddacf742cdb5b448', 'FIELD_DEFINITION_UUID', 0, '', NULL, NULL, NULL, '2019-07-30 09:25:06.669', '2019-07-29 16:44:41.928');\n" + "INSERT INTO public.reg_localization VALUES ('94174d6b7307a13e848616096051b301', 'ro', '5247138f69b59f59ddacf742cdb5b448', 'FIELD_LABEL_UUID', 0, 'Legal (EU)', NULL, NULL, NULL, '2019-07-30 09:25:06.653', '2019-07-29 16:43:40.026');\n" + "INSERT INTO public.reg_localization VALUES ('d769687f216ff29b2ca40fd4a2b14676', 'ro', '5247138f69b59f59ddacf742cdb5b448', 'FIELD_DEFINITION_UUID', 0, '<p>Elementul este reglementat la nivelul actelor juridice INSPIRE, inclusiv Directiva INSPIRE și normele de aplicare.</p>', NULL, NULL, NULL, '2019-07-30 09:25:06.669', '2019-07-29 17:08:56.442');\n" + "INSERT INTO public.reg_localization VALUES ('0b1e284c746dd880ab92d12d2f62ed6c', 'en', '24bb2984999c116018d3ba95c1aa3082', 'FIELD_LABEL_UUID', 0, 'Technical (EU)', NULL, NULL, NULL, '2019-07-31 11:05:04.812', NULL);\n" + "INSERT INTO public.reg_localization VALUES ('82f6cf74d357265d46dad08ccb1b7c17', 'en', '24bb2984999c116018d3ba95c1aa3082', 'FIELD_DEFINITION_UUID', 0, '<p>The item is governed at the level of INSPIRE Technical Guidelines.</p>', NULL, NULL, NULL, '2019-07-31 11:05:04.828', NULL);\n" + "INSERT INTO public.reg_localization VALUES ('60f5acc564659da7c39833519653b77c', 'it', '24bb2984999c116018d3ba95c1aa3082', 'FIELD_LABEL_UUID', 0, 'Norme di attuazione EU1253/2013', NULL, NULL, NULL, '2019-07-31 11:07:50.016', NULL);\n" + "INSERT INTO public.reg_localization VALUES ('b47e79f525ecda87ab65b1b6f92851a7', 'it', '24bb2984999c116018d3ba95c1aa3082', 'FIELD_DEFINITION_UUID', 0, '<p>I valori sono il contenuto giuridicamente vincolante delle norme di attuazione ISDSS (UE N. 1253/2013 dal 21 ottobre 2013).</p>', NULL, NULL, NULL, '2019-07-31 11:07:50.032', NULL);\n" + "INSERT INTO public.reg_localization VALUES ('18f46d46d877c133365b420495f745ce', 'de', '24bb2984999c116018d3ba95c1aa3082', 'FIELD_LABEL_UUID', 0, 'Technisch (EU)', NULL, NULL, NULL, '2019-07-31 11:07:50.032', NULL);\n" + "INSERT INTO public.reg_localization VALUES ('9944681a9d8a80a1108c83c5d777c8ea', 'de', '24bb2984999c116018d3ba95c1aa3082', 'FIELD_DEFINITION_UUID', 0, '<p>Das Element wird auf der Ebene der INSPIRE Technischen Dokuments geregelt.</p>', NULL, NULL, NULL, '2019-07-31 11:07:50.032', NULL);\n" + "INSERT INTO public.reg_localization VALUES ('bae71270630e200bda121ff1f86f123c', 'el', '24bb2984999c116018d3ba95c1aa3082', 'FIELD_LABEL_UUID', 0, 'Τεχνικό (ΕΕ)', NULL, NULL, NULL, '2019-07-31 11:07:50.048', NULL);\n" + "INSERT INTO public.reg_localization VALUES ('77bc5eb2d4017a05d9e0b98dce373f00', 'el', '24bb2984999c116018d3ba95c1aa3082', 'FIELD_DEFINITION_UUID', 0, '<p>Το στοιχείο διαχειριζεται στο επίπεδο των τεχνικών οδηγιών INSPIRE.</p>', NULL, NULL, NULL, '2019-07-31 11:07:50.048', NULL);\n" + "INSERT INTO public.reg_localization VALUES ('d9097d14aefab3399cdcbfb76be33505', 'es', '24bb2984999c116018d3ba95c1aa3082', 'FIELD_LABEL_UUID', 0, 'Técnico (UE)', NULL, NULL, NULL, '2019-07-31 11:07:50.048', NULL);\n" + "INSERT INTO public.reg_localization VALUES ('b9954d57960f7142f2ffc992093dd95f', 'es', '24bb2984999c116018d3ba95c1aa3082', 'FIELD_DEFINITION_UUID', 0, '<p>El elemento se rige las Guías Técnicas INSPIRE</p>', NULL, NULL, NULL, '2019-07-31 11:07:50.048', NULL);\n" + "INSERT INTO public.reg_localization VALUES ('4f880ab0108e593197b1d10bf310a781', 'hr', '24bb2984999c116018d3ba95c1aa3082', 'FIELD_LABEL_UUID', 0, 'Tehnički (EU)', NULL, NULL, NULL, '2019-07-31 11:07:50.048', NULL);\n" + "INSERT INTO public.reg_localization VALUES ('754e7c3e91dc60f25736dd8ad29033f3', 'hr', '24bb2984999c116018d3ba95c1aa3082', 'FIELD_DEFINITION_UUID', 0, '<p>Stavkom se upravlja na razini Tehničkih naputaka INSPIRE-a</p>', NULL, NULL, NULL, '2019-07-31 11:07:50.063', NULL);\n" + "INSERT INTO public.reg_localization VALUES ('40c9d2c3bad430b9509e7a511a7cd37b', 'ro', '24bb2984999c116018d3ba95c1aa3082', 'FIELD_LABEL_UUID', 0, 'Tehnic (EU)', NULL, NULL, NULL, '2019-07-31 11:07:50.063', NULL);\n" + "INSERT INTO public.reg_localization VALUES ('f6bfb1b041ca41bf92bae2581898465d', 'ro', '24bb2984999c116018d3ba95c1aa3082', 'FIELD_DEFINITION_UUID', 0, '<p>Elementul este reglementat la nivelul Ghidului Tehnic INSPIRE.</p>', NULL, NULL, NULL, '2019-07-31 11:07:50.063', NULL);" + "INSERT INTO public.reg_localization VALUES ('d3b65ef302fdf442030063604b5786fd', 'en', 'e7462cf53d17f16c4c0f8e48d40055a7', 'FIELD_LABEL_UUID', 0, 'Good Pranctice (EU)', NULL, NULL, NULL, '2021-04-15 11:05:04.812', NULL);\n" + "INSERT INTO public.reg_localization VALUES ('31fa9b5a822ffec25e86a77775403a7d', 'en', 'e7462cf53d17f16c4c0f8e48d40055a7', 'FIELD_DEFINITION_UUID', 0, '<p>The item is governed at the level of INSPIRE Good Practice.</p>', NULL, NULL, NULL, '2019-07-31 11:05:04.828', NULL);\n"; private final String QUERY_EXTENSIBILITY = "INSERT INTO public.reg_localization VALUES ('e3bdb192afe7e9c9f1d77270d87adf7d', 'en', 'a2290d202bbd591377234ce2eee350df', 'FIELD_LABEL_UUID', 0, 'Extensibility', NULL, NULL, NULL, '2019-07-30 10:34:07.401', NULL);\n" + "INSERT INTO public.reg_localization VALUES ('3ebfd81f0dd3109bf86fa60f994e28af', 'bg', 'a2290d202bbd591377234ce2eee350df', 'FIELD_LABEL_UUID', 0, 'Разширяемост', NULL, NULL, NULL, '2019-07-30 10:56:01.617', NULL);\n" + "INSERT INTO public.reg_localization VALUES ('667e53d2cfaf9b103490a6f3b339e6d5', 'bg', 'a2290d202bbd591377234ce2eee350df', 'FIELD_CONTENTSUMMARY_UUID', 0, '', NULL, NULL, NULL, '2019-07-30 10:56:01.62', NULL);\n" + "INSERT INTO public.reg_localization VALUES ('8b890ec36809112032dfeb80adccf0f7', 'cs', 'a2290d202bbd591377234ce2eee350df', 'FIELD_LABEL_UUID', 0, 'Rozšiřitelnost', NULL, NULL, NULL, '2019-07-30 10:56:01.623', NULL);\n" + "INSERT INTO public.reg_localization VALUES ('93e824ca8a54b549b47b117410535b60', 'cs', 'a2290d202bbd591377234ce2eee350df', 'FIELD_CONTENTSUMMARY_UUID', 0, '', NULL, NULL, NULL, '2019-07-30 10:56:01.627', NULL);\n" + "INSERT INTO public.reg_localization VALUES ('297fdd354aff9b34f79d035b83546641', 'da', 'a2290d202bbd591377234ce2eee350df', 'FIELD_LABEL_UUID', 0, 'Udvidelsesmuligheder', NULL, NULL, NULL, '2019-07-30 10:56:01.63', NULL);\n" + "INSERT INTO public.reg_localization VALUES ('5670c7b9594df418ddc5bcd69348b652', 'da', 'a2290d202bbd591377234ce2eee350df', 'FIELD_CONTENTSUMMARY_UUID', 0, '', NULL, NULL, NULL, '2019-07-30 10:56:01.633', NULL);\n" + "INSERT INTO public.reg_localization VALUES ('38cef7ba2b15c14a46ab3912540abf0c', 'de', 'a2290d202bbd591377234ce2eee350df', 'FIELD_LABEL_UUID', 0, 'Erweiterbarkeit', NULL, NULL, NULL, '2019-07-30 10:56:01.637', NULL);\n" + "INSERT INTO public.reg_localization VALUES ('6b218568ba0b3368d67ad45ec60e069c', 'de', 'a2290d202bbd591377234ce2eee350df', 'FIELD_CONTENTSUMMARY_UUID', 0, '', NULL, NULL, NULL, '2019-07-30 10:56:01.64', NULL);\n" + "INSERT INTO public.reg_localization VALUES ('ee4c4817ff90a8435a873141153bc63d', 'et', 'a2290d202bbd591377234ce2eee350df', 'FIELD_LABEL_UUID', 0, 'Laiendatavus', NULL, NULL, NULL, '2019-07-30 10:56:01.644', NULL);\n" + "INSERT INTO public.reg_localization VALUES ('8de15d517f7cf68d431da443a973caed', 'et', 'a2290d202bbd591377234ce2eee350df', 'FIELD_CONTENTSUMMARY_UUID', 0, '', NULL, NULL, NULL, '2019-07-30 10:56:01.647', NULL);\n" + "INSERT INTO public.reg_localization VALUES ('2061f9f779758b540642718daed3dea2', 'el', 'a2290d202bbd591377234ce2eee350df', 'FIELD_LABEL_UUID', 0, 'Επεκτασιμότητα', NULL, NULL, NULL, '2019-07-30 10:56:01.65', NULL);\n" + "INSERT INTO public.reg_localization VALUES ('bf48404b8d9abc4ddeaed0c9c242d8eb', 'el', 'a2290d202bbd591377234ce2eee350df', 'FIELD_CONTENTSUMMARY_UUID', 0, '', NULL, NULL, NULL, '2019-07-30 10:56:01.653', NULL);\n" + "INSERT INTO public.reg_localization VALUES ('137680360b3cb05c9ef2236aafb99be1', 'es', 'a2290d202bbd591377234ce2eee350df', 'FIELD_LABEL_UUID', 0, 'Extensibilidad', NULL, NULL, NULL, '2019-07-30 10:56:01.658', NULL);\n" + "INSERT INTO public.reg_localization VALUES ('5134d03b0bcffebc448591300eaf5462', 'es', 'a2290d202bbd591377234ce2eee350df', 'FIELD_CONTENTSUMMARY_UUID', 0, '', NULL, NULL, NULL, '2019-07-30 10:56:01.663', NULL);\n" + "INSERT INTO public.reg_localization VALUES ('52c98d148187b1fd6712c7036431edfd', 'fr', 'a2290d202bbd591377234ce2eee350df', 'FIELD_LABEL_UUID', 0, 'Extensibilité', NULL, NULL, NULL, '2019-07-30 10:56:01.667', NULL);\n" + "INSERT INTO public.reg_localization VALUES ('dfd72fd55b61fe679d61366a49d7ab37', 'fr', 'a2290d202bbd591377234ce2eee350df', 'FIELD_CONTENTSUMMARY_UUID', 0, '', NULL, NULL, NULL, '2019-07-30 10:56:01.671', NULL);\n" + "INSERT INTO public.reg_localization VALUES ('ea748cb80f69dc729e340ff504b1376b', 'hr', 'a2290d202bbd591377234ce2eee350df', 'FIELD_LABEL_UUID', 0, 'Proširivost', NULL, NULL, NULL, '2019-07-30 10:56:01.675', NULL);\n" + "INSERT INTO public.reg_localization VALUES ('4de8855439e8df8bb955a5e0dc6f9f75', 'hr', 'a2290d202bbd591377234ce2eee350df', 'FIELD_CONTENTSUMMARY_UUID', 0, '', NULL, NULL, NULL, '2019-07-30 10:56:01.678', NULL);\n" + "INSERT INTO public.reg_localization VALUES ('d12b968cfe441ad3f557f2e45fca4784', 'it', 'a2290d202bbd591377234ce2eee350df', 'FIELD_LABEL_UUID', 0, 'Estendibilità', NULL, NULL, NULL, '2019-07-30 10:56:01.682', NULL);\n" + "INSERT INTO public.reg_localization VALUES ('e8321a59a35cbaec6fffe39df9daa11b', 'it', 'a2290d202bbd591377234ce2eee350df', 'FIELD_CONTENTSUMMARY_UUID', 0, '', NULL, NULL, NULL, '2019-07-30 10:56:01.686', NULL);\n" + "INSERT INTO public.reg_localization VALUES ('e7171646bb2e05e8ecb87edf33a50d27', 'lv', 'a2290d202bbd591377234ce2eee350df', 'FIELD_LABEL_UUID', 0, 'Paplašināmība', NULL, NULL, NULL, '2019-07-30 10:56:01.69', NULL);\n" + "INSERT INTO public.reg_localization VALUES ('bb579d5d252e580c1ca877c77996b705', 'lv', 'a2290d202bbd591377234ce2eee350df', 'FIELD_CONTENTSUMMARY_UUID', 0, '', NULL, NULL, NULL, '2019-07-30 10:56:01.693', NULL);\n" + "INSERT INTO public.reg_localization VALUES ('1c21a86ad29829a40757dd03cc9aef83', 'lt', 'a2290d202bbd591377234ce2eee350df', 'FIELD_LABEL_UUID', 0, 'Plečiamumas', NULL, NULL, NULL, '2019-07-30 10:56:01.696', NULL);\n" + "INSERT INTO public.reg_localization VALUES ('357dec0654a04d99b593e4a5166a867a', 'lt', 'a2290d202bbd591377234ce2eee350df', 'FIELD_CONTENTSUMMARY_UUID', 0, '', NULL, NULL, NULL, '2019-07-30 10:56:01.699', NULL);\n" + "INSERT INTO public.reg_localization VALUES ('04c4a19ee9ae9e3bcf6edcdbc83f4eaf', 'hu', 'a2290d202bbd591377234ce2eee350df', 'FIELD_LABEL_UUID', 0, 'Bővíthetőség', NULL, NULL, NULL, '2019-07-30 10:56:01.703', NULL);\n" + "INSERT INTO public.reg_localization VALUES ('4f67fc9d49fed35d734bd370ae908259', 'hu', 'a2290d202bbd591377234ce2eee350df', 'FIELD_CONTENTSUMMARY_UUID', 0, '', NULL, NULL, NULL, '2019-07-30 10:56:01.707', NULL);\n" + "INSERT INTO public.reg_localization VALUES ('2a76915b91c3f67ec29eb2a20be4c851', 'mt', 'a2290d202bbd591377234ce2eee350df', 'FIELD_LABEL_UUID', 0, 'Estensibbiltà', NULL, NULL, NULL, '2019-07-30 10:56:01.711', NULL);\n" + "INSERT INTO public.reg_localization VALUES ('1d9ca98e41cf489a0185083045a0e7bc', 'mt', 'a2290d202bbd591377234ce2eee350df', 'FIELD_CONTENTSUMMARY_UUID', 0, '', NULL, NULL, NULL, '2019-07-30 10:56:01.715', NULL);\n" + "INSERT INTO public.reg_localization VALUES ('6a1d0f380fe5a5017891fbeb77ee9957', 'nl', 'a2290d202bbd591377234ce2eee350df', 'FIELD_LABEL_UUID', 0, 'Uitbreidbaarheid', NULL, NULL, NULL, '2019-07-30 10:56:01.718', NULL);\n" + "INSERT INTO public.reg_localization VALUES ('90c69388a5b4c9f0b2272feabd85b5b7', 'nl', 'a2290d202bbd591377234ce2eee350df', 'FIELD_CONTENTSUMMARY_UUID', 0, '', NULL, NULL, NULL, '2019-07-30 10:56:01.721', NULL);\n" + "INSERT INTO public.reg_localization VALUES ('23834a39e4ab7056d21789d2a4a2fa68', 'fi', 'a2290d202bbd591377234ce2eee350df', 'FIELD_LABEL_UUID', 0, 'Laajennettavuus', NULL, NULL, NULL, '2019-07-30 10:56:01.725', NULL);\n" + "INSERT INTO public.reg_localization VALUES ('6c682c03b35686438999a651eee700bd', 'fi', 'a2290d202bbd591377234ce2eee350df', 'FIELD_CONTENTSUMMARY_UUID', 0, '', NULL, NULL, NULL, '2019-07-30 10:56:01.728', NULL);\n" + "INSERT INTO public.reg_localization VALUES ('573385d80c2bbe3f3558b1969465605f', 'pl', 'a2290d202bbd591377234ce2eee350df', 'FIELD_LABEL_UUID', 0, 'Rozszerzalność', NULL, NULL, NULL, '2019-07-30 10:56:01.732', NULL);\n" + "INSERT INTO public.reg_localization VALUES ('beb03caca0ff77661552a36d6add096b', 'pl', 'a2290d202bbd591377234ce2eee350df', 'FIELD_CONTENTSUMMARY_UUID', 0, '', NULL, NULL, NULL, '2019-07-30 10:56:01.735', NULL);\n" + "INSERT INTO public.reg_localization VALUES ('a000eb19b4dfd649645f1588453172b7', 'pt', 'a2290d202bbd591377234ce2eee350df', 'FIELD_LABEL_UUID', 0, 'Extensibilidade', NULL, NULL, NULL, '2019-07-30 10:56:01.738', NULL);\n" + "INSERT INTO public.reg_localization VALUES ('fc94ad8070e5529e643f076b692226ac', 'pt', 'a2290d202bbd591377234ce2eee350df', 'FIELD_CONTENTSUMMARY_UUID', 0, '', NULL, NULL, NULL, '2019-07-30 10:56:01.742', NULL);\n" + "INSERT INTO public.reg_localization VALUES ('df8f69e3fe4677f793fa644b7ce30685', 'ro', 'a2290d202bbd591377234ce2eee350df', 'FIELD_LABEL_UUID', 0, 'Extensibilitate', NULL, NULL, NULL, '2019-07-30 10:56:01.745', NULL);\n" + "INSERT INTO public.reg_localization VALUES ('26f86a6aa272ce44e1fd5e8476c9aec9', 'ro', 'a2290d202bbd591377234ce2eee350df', 'FIELD_CONTENTSUMMARY_UUID', 0, '', NULL, NULL, NULL, '2019-07-30 10:56:01.749', NULL);\n" + "INSERT INTO public.reg_localization VALUES ('0f908e5e5ed3c578015f27ee9706fe0e', 'sk', 'a2290d202bbd591377234ce2eee350df', 'FIELD_LABEL_UUID', 0, 'Rozšíriteľnosť', NULL, NULL, NULL, '2019-07-30 10:56:01.752', NULL);\n" + "INSERT INTO public.reg_localization VALUES ('0ccae549d758323cb171f3e27aa7dd8a', 'sk', 'a2290d202bbd591377234ce2eee350df', 'FIELD_CONTENTSUMMARY_UUID', 0, '', NULL, NULL, NULL, '2019-07-30 10:56:01.756', NULL);\n" + "INSERT INTO public.reg_localization VALUES ('f64d8d3eaa8f10c63035724db2367eaf', 'sl', 'a2290d202bbd591377234ce2eee350df', 'FIELD_LABEL_UUID', 0, 'Dopolnjevanje', NULL, NULL, NULL, '2019-07-30 10:56:01.759', NULL);\n" + "INSERT INTO public.reg_localization VALUES ('4136380d844979721fc9970367946a27', 'sl', 'a2290d202bbd591377234ce2eee350df', 'FIELD_CONTENTSUMMARY_UUID', 0, '', NULL, NULL, NULL, '2019-07-30 10:56:01.763', NULL);\n" + "INSERT INTO public.reg_localization VALUES ('21a4f04d85b84ef7855436d7a14d865e', 'sv', 'a2290d202bbd591377234ce2eee350df', 'FIELD_LABEL_UUID', 0, 'Utökningsbarhet', NULL, NULL, NULL, '2019-07-30 10:56:01.766', NULL);\n" + "INSERT INTO public.reg_localization VALUES ('1e535d8f874f8ac242c073fbfb51d02b', 'sv', 'a2290d202bbd591377234ce2eee350df', 'FIELD_CONTENTSUMMARY_UUID', 0, '', NULL, NULL, NULL, '2019-07-30 10:56:01.77', NULL);\n" + "INSERT INTO public.reg_localization VALUES ('eb676958fb0c246eb54ef4c53749bb50', 'en', 'aad13ff0ff9fb151cb8410801e4eeb0a', 'FIELD_LABEL_UUID', 0, 'Extensible with values at any level', NULL, NULL, NULL, '2019-07-30 10:45:51.988', NULL);\n" + "INSERT INTO public.reg_localization VALUES ('128b89cd6585c8822da2ac4180faca2e', 'en', 'aad13ff0ff9fb151cb8410801e4eeb0a', 'FIELD_DEFINITION_UUID', 0, '<p>The code list can be extended with additional values at any level, i.e. its allowed values comprise the values specified in this register and additional values at any level defined by data providers.</p>', NULL, NULL, NULL, '2019-07-30 10:45:51.993', NULL);\n" + "INSERT INTO public.reg_localization VALUES ('57a0a3dd49a30c049a9974ba5af5edbd', 'bg', 'aad13ff0ff9fb151cb8410801e4eeb0a', 'FIELD_LABEL_UUID', 0, 'Разширяем със стойности на всяко ниво', NULL, NULL, NULL, '2019-07-30 14:33:39.707', NULL);\n" + "INSERT INTO public.reg_localization VALUES ('e9255ef68df5ff7e7db40deedec1c20b', 'bg', 'aad13ff0ff9fb151cb8410801e4eeb0a', 'FIELD_DEFINITION_UUID', 0, '<p>Списъкът на кодовете може да бъде разширяван с допълнителни стойности от всяко ниво, т.е. допустимите стойности обхващат стойности, посочени в този регистър, и допълнителни стойности от всяко ниво в йерархията, дефинирани от доставчиците на данни.</p>', NULL, NULL, NULL, '2019-07-30 14:33:39.715', NULL);\n" + "INSERT INTO public.reg_localization VALUES ('f30d2d57ed8a14ceb775cda1d3319629', 'cs', 'aad13ff0ff9fb151cb8410801e4eeb0a', 'FIELD_LABEL_UUID', 0, 'Libovolně rozšiřitelný', NULL, NULL, NULL, '2019-07-30 14:33:39.717', NULL);\n" + "INSERT INTO public.reg_localization VALUES ('c1df8811df064cbac6199f629851c938', 'cs', 'aad13ff0ff9fb151cb8410801e4eeb0a', 'FIELD_DEFINITION_UUID', 0, '<p>Číselník může být rozšířen o další libovolné hodnoty, tj. povolené hodnoty zahrnují hodnoty specifikované v registru a dodatečné hodnoty libovolně definované poskytovatelem dat.</p>', NULL, NULL, NULL, '2019-07-30 14:33:39.72', NULL);\n" + "INSERT INTO public.reg_localization VALUES ('1c185abd5f1e28e92f4997bb2b035e16', 'da', 'aad13ff0ff9fb151cb8410801e4eeb0a', 'FIELD_LABEL_UUID', 0, 'Kan udvides med værdier på alle niveauer', NULL, NULL, NULL, '2019-07-30 14:33:39.723', NULL);\n" + "INSERT INTO public.reg_localization VALUES ('15bccf2658334ce80fb7d249c5c4d760', 'da', 'aad13ff0ff9fb151cb8410801e4eeb0a', 'FIELD_DEFINITION_UUID', 0, '<p>Kodelisten kan udvides med værdier på ethvert niveau, dvs. tilladte værdier udgøres af værdier i dette register samt yderligere værdier på alle niveauer.</p>', NULL, NULL, NULL, '2019-07-30 14:33:39.73', NULL);\n" + "INSERT INTO public.reg_localization VALUES ('e882ba334a4d8eca9f22bb48d519e75b', 'de', 'aad13ff0ff9fb151cb8410801e4eeb0a', 'FIELD_LABEL_UUID', 0, 'Erweiterbar um beliebige Werte', NULL, NULL, NULL, '2019-07-30 14:33:39.733', NULL);\n" + "INSERT INTO public.reg_localization VALUES ('570421313624e1b2bbd7cf8644bfe47e', 'de', 'aad13ff0ff9fb151cb8410801e4eeb0a', 'FIELD_DEFINITION_UUID', 0, '<p>Die Codeliste darf um beliebige Werte erweitert werden, d.h. ihre erlaubten Werte umfassen die Werte, die in diesem Register enthalten sind, und zusätzlich beliebige von Datenanbietern definierte Werte.</p>', NULL, NULL, NULL, '2019-07-30 14:33:39.736', NULL);\n" + "INSERT INTO public.reg_localization VALUES ('5d675a8b28e7d98786ccbb6a80121a5b', 'et', 'aad13ff0ff9fb151cb8410801e4eeb0a', 'FIELD_LABEL_UUID', 0, 'Laiendatav väärtustega suvalisel tasemel', NULL, NULL, NULL, '2019-07-30 14:33:39.739', NULL);\n" + "INSERT INTO public.reg_localization VALUES ('242bab4c16a3e14a50d2950dcb6797c1', 'et', 'aad13ff0ff9fb151cb8410801e4eeb0a', 'FIELD_DEFINITION_UUID', 0, '<p>Koodiloendit saab laiendada lisaväärtustega igal tasemel, st selle lubatavad väärtused hõlmavad väärtusi, mis on määratletud selles registris ja andmete tarnijate poolt määratletud lisaväärtused suvalisel tasemel.</p>', NULL, NULL, NULL, '2019-07-30 14:33:39.745', NULL);\n" + "INSERT INTO public.reg_localization VALUES ('40f8951f290c4a5c92f931ab71ad265b', 'el', 'aad13ff0ff9fb151cb8410801e4eeb0a', 'FIELD_LABEL_UUID', 0, 'επεκτάσιμο με τιμές σε οποιοδήποτε επίπεδο', NULL, NULL, NULL, '2019-07-30 14:33:39.749', NULL);\n" + "INSERT INTO public.reg_localization VALUES ('78f76bd95d4c5dd9e5d230368ca13921', 'el', 'aad13ff0ff9fb151cb8410801e4eeb0a', 'FIELD_DEFINITION_UUID', 0, '<p>Αυτός ο κωδικός λίστας μπορεί να επεκταθεί με επιπλέον τιμές σε οποιοδήποτε επίπεδο, οι επιτρεπόμενες τιμές του αποτελούν τις τιμές που ορίζονται από στο καταχωρητή και επιπλέον τιμές σε οποιοδήποτε επίπεδο όπως ορίζονται από παρόχους δεδομένων</p>', NULL, NULL, NULL, '2019-07-30 14:33:39.753', NULL);\n" + "INSERT INTO public.reg_localization VALUES ('f2027e006a93a892da0dd7fca087e6c6', 'es', 'aad13ff0ff9fb151cb8410801e4eeb0a', 'FIELD_LABEL_UUID', 0, 'Extensible con valores a cualquier nivel', NULL, NULL, NULL, '2019-07-30 14:33:39.755', NULL);\n" + "INSERT INTO public.reg_localization VALUES ('eca9600c953c9e8b99cc936291c04a5c', 'es', 'aad13ff0ff9fb151cb8410801e4eeb0a', 'FIELD_DEFINITION_UUID', 0, '<p>Se puede extender la lista de códigos con valores a cualquier nivel; es decir, los valores permitidos son los valores especificados en el registro y cualquier otro definido por el proveedor de datos a cualquier nivel</p>', NULL, NULL, NULL, '2019-07-30 14:33:39.758', NULL);\n" + "INSERT INTO public.reg_localization VALUES ('2b61800ce3d3f534b860e42edda78233', 'fr', 'aad13ff0ff9fb151cb8410801e4eeb0a', 'FIELD_LABEL_UUID', 0, 'Extensible avec des valeurs à tout niveau', NULL, NULL, NULL, '2019-07-30 14:33:39.765', NULL);\n" + "INSERT INTO public.reg_localization VALUES ('0f5c39443a476f8594370b3808c3c266', 'fr', 'aad13ff0ff9fb151cb8410801e4eeb0a', 'FIELD_DEFINITION_UUID', 0, '<p>La liste de codes peut être étendue avec des valeurs à tout niveau: les codes autorisés sont les codes existants et de nouvelles valeurs définies à tout niveau par des fournisseurs de données.</p>', NULL, NULL, NULL, '2019-07-30 14:33:39.768', NULL);\n" + "INSERT INTO public.reg_localization VALUES ('6e8fcaea7e6aa6d567f9a84a4c52ead3', 'hr', 'aad13ff0ff9fb151cb8410801e4eeb0a', 'FIELD_LABEL_UUID', 0, 'Proširivo vrijednostima na svim razinama', NULL, NULL, NULL, '2019-07-30 14:33:39.771', NULL);\n" + "INSERT INTO public.reg_localization VALUES ('1d0b19bfb293f26ed8dc7e262b4a8360', 'hr', 'aad13ff0ff9fb151cb8410801e4eeb0a', 'FIELD_DEFINITION_UUID', 0, '<p>Kodna lista je proširiva dodatnim vrijednostima na svim razinama tj. dozvoljene vrijednosti obuhvaćaju one specificirane u ovom registru kao i dodatne vrijednosti na svim razinama definirane od strane pružatelja podataka</p>', NULL, NULL, NULL, '2019-07-30 14:33:39.773', NULL);\n" + "INSERT INTO public.reg_localization VALUES ('d68410d0e828e1a1c283b4477631b5b7', 'it', 'aad13ff0ff9fb151cb8410801e4eeb0a', 'FIELD_LABEL_UUID', 0, 'Estendibile con valori a qualsiasi livello', NULL, NULL, NULL, '2019-07-30 14:33:39.781', NULL);\n" + "INSERT INTO public.reg_localization VALUES ('08122fd34aa01b3bf3ceafc8f1d2abc6', 'it', 'aad13ff0ff9fb151cb8410801e4eeb0a', 'FIELD_DEFINITION_UUID', 0, '<p>L''elenco dei codici può essere esteso con valori aggiuntivi a qualsiasi livello, vale a dire i suoi valori consentiti comprendono i valori indicati in questo registro e valori aggiuntivi a qualsiasi livello definito dal provider di dati.</p>', NULL, NULL, NULL, '2019-07-30 14:33:39.785', NULL);\n" + "INSERT INTO public.reg_localization VALUES ('b7980e7644e5c453d87cba3d5c91bff7', 'lv', 'aad13ff0ff9fb151cb8410801e4eeb0a', 'FIELD_LABEL_UUID', 0, 'Paplašināms ar jebkura līmeņa vērtībām', NULL, NULL, NULL, '2019-07-30 14:33:39.788', NULL);\n" + "INSERT INTO public.reg_localization VALUES ('48246ee0e2d706544fa489277fcab351', 'lv', 'aad13ff0ff9fb151cb8410801e4eeb0a', 'FIELD_DEFINITION_UUID', 0, '<p>Kodu sarakstu var paplašināt ar jebkura līmeņa papildu vērtībām, t.i., tā atļautās vērtības aptver šajā reģistrā iekļautās vērtības un papildu vērtības, ko jebkurā līmenī ir definējis datu sniedzējs.</p>', NULL, NULL, NULL, '2019-07-30 14:33:39.791', NULL);\n" + "INSERT INTO public.reg_localization VALUES ('5140aa533eedf6dcf134f335a8513753', 'lt', 'aad13ff0ff9fb151cb8410801e4eeb0a', 'FIELD_LABEL_UUID', 0, 'Plečiamas visais lygmenimis', NULL, NULL, NULL, '2019-07-30 14:33:39.795', NULL);\n" + "INSERT INTO public.reg_localization VALUES ('b9cab08c37c9470035fc914dadbe2c54', 'lt', 'aad13ff0ff9fb151cb8410801e4eeb0a', 'FIELD_DEFINITION_UUID', 0, '<p>Kodų sąrašas gali būti papildytas bet kurio lygmens reikšmėmis, t.y., leidžiamos reikšmės apima registre esančias ir duomenų teikėjo nurodytas bet kurio lygmens reikšmes.</p>', NULL, NULL, NULL, '2019-07-30 14:33:39.797', NULL);\n" + "INSERT INTO public.reg_localization VALUES ('3a0697dcc1f4869d3896fc6b555e27a5', 'hu', 'aad13ff0ff9fb151cb8410801e4eeb0a', 'FIELD_LABEL_UUID', 0, 'Az értékek bármely szinten bővíthetők', NULL, NULL, NULL, '2019-07-30 14:33:39.8', NULL);\n" + "INSERT INTO public.reg_localization VALUES ('e99307bf132c85ff1594a4333ee8e66d', 'hu', 'aad13ff0ff9fb151cb8410801e4eeb0a', 'FIELD_DEFINITION_UUID', 0, '<p>A kódlista akármelyik szintjét bármilyen értékekkel lehet bővíteni. A teljes lista magába foglalja az itt meghatározott értékeket és az adatszolgáltató által hozzáadott értékeket.</p>', NULL, NULL, NULL, '2019-07-30 14:33:39.803', NULL);\n" + "INSERT INTO public.reg_localization VALUES ('73c701507e9a5e43c5f648e8f9a12438', 'mt', 'aad13ff0ff9fb151cb8410801e4eeb0a', 'FIELD_LABEL_UUID', 0, 'Estensibbli b''valuri f''kull livell', NULL, NULL, NULL, '2019-07-30 14:33:39.805', NULL);\n" + "INSERT INTO public.reg_localization VALUES ('888a55859421c7861960b1d9d986643e', 'mt', 'aad13ff0ff9fb151cb8410801e4eeb0a', 'FIELD_DEFINITION_UUID', 0, '<p>Il-lista ta'' kodiċi tista'' tiġi estiża b''valuri addizzjonali f''kull livell, jiġifieri l-valuri permessi tagħha jinkludu l-valuri speċifikati fir-reġistru u valuri addizzjonali f''kull livell definiti mill-fornituri tad-dejta</p>', NULL, NULL, NULL, '2019-07-30 14:33:39.808', NULL);\n" + "INSERT INTO public.reg_localization VALUES ('a2f26c4c902dbf9f6461e91af261de09', 'nl', 'aad13ff0ff9fb151cb8410801e4eeb0a', 'FIELD_LABEL_UUID', 0, 'Uitbreidbaar met waarden op elk niveau', NULL, NULL, NULL, '2019-07-30 14:33:39.811', NULL);\n" + "INSERT INTO public.reg_localization VALUES ('8a168f48d0230c95550c4858c7465c8f', 'nl', 'aad13ff0ff9fb151cb8410801e4eeb0a', 'FIELD_DEFINITION_UUID', 0, '<p>De codelijst kan uitgebreid worden met extra additionele waarden op alle niveaus, met andere woorden de toegestane waarden zijn deze gespecifieerd in dit register plus extra additionele waarden op om het even welk niveau gedefinieerd door gegevens beheerders.</p>', NULL, NULL, NULL, '2019-07-30 14:33:39.814', NULL);\n" + "INSERT INTO public.reg_localization VALUES ('2bda61b7b139b90965127c5c097e8ef8', 'pl', 'aad13ff0ff9fb151cb8410801e4eeb0a', 'FIELD_LABEL_UUID', 0, 'Rozszerzalny z wartościami na każdym poziomie', NULL, NULL, NULL, '2019-07-30 14:33:39.816', NULL);\n" + "INSERT INTO public.reg_localization VALUES ('72a9bb81fb3bc1d2b9ae553f87197533', 'pl', 'aad13ff0ff9fb151cb8410801e4eeb0a', 'FIELD_DEFINITION_UUID', 0, '<p>Lista kodów może zostać rozszerzona dodatkowymi wartościami na każdym poziomie, to znaczy, że dozwolone wartości zawierają wartości określone w tym wykazie oraz dodatkowe wartości na każdym poziomie zdefiniowane przez dostawców danych.</p>', NULL, NULL, NULL, '2019-07-30 14:33:39.819', NULL);\n" + "INSERT INTO public.reg_localization VALUES ('2e2ada23dda76a17e65350a92f4ba12c', 'pt', 'aad13ff0ff9fb151cb8410801e4eeb0a', 'FIELD_LABEL_UUID', 0, 'Extensível com valores de qualquer nível', NULL, NULL, NULL, '2019-07-30 14:33:39.822', NULL);\n" + "INSERT INTO public.reg_localization VALUES ('4c6518c40b96aa1e53de1cee83e92983', 'pt', 'aad13ff0ff9fb151cb8410801e4eeb0a', 'FIELD_DEFINITION_UUID', 0, '<p>A lista de códigos pode ser alargada com valores adicionais de qualquer nível, ou seja, são permitidos os valores que compreendem os valores especificados neste registo e os valores adicionais de qualquer nível definido por fornecedores de dados.</p>', NULL, NULL, NULL, '2019-07-30 14:33:39.825', NULL);\n" + "INSERT INTO public.reg_localization VALUES ('52a1b52efe3f8e0dbd54c525d06be051', 'ro', 'aad13ff0ff9fb151cb8410801e4eeb0a', 'FIELD_LABEL_UUID', 0, 'Extensibilă cu valori de la orice nivel', NULL, NULL, NULL, '2019-07-30 14:33:39.828', NULL);\n" + "INSERT INTO public.reg_localization VALUES ('3670c3c02152e1170d8943507cf89f12', 'ro', 'aad13ff0ff9fb151cb8410801e4eeb0a', 'FIELD_DEFINITION_UUID', 0, '<p>Lista de coduri poate fi extinsă cu lavori suplimentare la orice nivel, adică valorile sale permise cuprind valorile specificate în acest registru și valori suplimentare la orice nivel definite de furnizorii de date.</p>', NULL, NULL, NULL, '2019-07-30 14:33:39.83', NULL);\n" + "INSERT INTO public.reg_localization VALUES ('146174cce3c4133cba9a4fd4f8b696ee', 'sk', 'aad13ff0ff9fb151cb8410801e4eeb0a', 'FIELD_LABEL_UUID', 0, 'Rozšíriteľný s hodnotami na akejkoľvek úrovni', NULL, NULL, NULL, '2019-07-30 14:33:39.833', NULL);\n" + "INSERT INTO public.reg_localization VALUES ('b9f4d1a8b0d1c2f438203e9c48afbdb3', 'sk', 'aad13ff0ff9fb151cb8410801e4eeb0a', 'FIELD_DEFINITION_UUID', 0, '<p>Zoznam kódov (číselník) je možné rozšíriť o ďalšie hodnoty na akejkoľvek úrovni, t.j. jeho povolené hodnoty zahŕňajú hodnoty uvedené v tomto registri a ďalšie hodnoty, na akejkoľvek úrovni definovanej poskytovateľom údajov.</p>', NULL, NULL, NULL, '2019-07-30 14:33:39.835', NULL);\n" + "INSERT INTO public.reg_localization VALUES ('a61d766296941f893e7a25d689b90002', 'sl', 'aad13ff0ff9fb151cb8410801e4eeb0a', 'FIELD_LABEL_UUID', 0, 'Dopolnjevanje je mogoče z vrednostmi vseh nivojev', NULL, NULL, NULL, '2019-07-30 14:33:39.838', NULL);\n" + "INSERT INTO public.reg_localization VALUES ('d0a6543333e659d3e392774349d6546f', 'sl', 'aad13ff0ff9fb151cb8410801e4eeb0a', 'FIELD_DEFINITION_UUID', 0, '<p>Dopolnjevanje seznama oznak je mogoče z vrednostmi vseh nivojev, t.j. dovoljene vrednosti so tiste navedene v registru in vrednosti vseh nivojev, ki jih opredeli ponudnik podatkov.</p>', NULL, NULL, NULL, '2019-07-30 14:33:39.841', NULL);\n" + "INSERT INTO public.reg_localization VALUES ('b45e07ccb68cea45934e4d67f36fe0da', 'fi', 'aad13ff0ff9fb151cb8410801e4eeb0a', 'FIELD_LABEL_UUID', 0, 'Laajennettavissa kaikilla tasoilla', NULL, NULL, NULL, '2019-07-30 14:33:39.844', NULL);\n" + "INSERT INTO public.reg_localization VALUES ('cd8f5aaef3c91496600f54148b87fad0', 'fi', 'aad13ff0ff9fb151cb8410801e4eeb0a', 'FIELD_DEFINITION_UUID', 0, '<p>Koodiluetteloa voidaan laajentaa minkä hyvänsä tason koodiarvoilla. Koodiluettelossa siis sallitaan tässä rekisterissä määritellyt arvot ja lisäksi tiedontuottajien määrittelemät minkä hyvänsä tason arvot.</p>', NULL, NULL, NULL, '2019-07-30 14:33:39.847', NULL);\n" + "INSERT INTO public.reg_localization VALUES ('97a7822e83b34c2b1ba455d16b42ba91', 'sv', 'aad13ff0ff9fb151cb8410801e4eeb0a', 'FIELD_LABEL_UUID', 0, 'Utökningbar med värden oavsett nivå', NULL, NULL, NULL, '2019-07-30 14:33:39.85', NULL);\n" + "INSERT INTO public.reg_localization VALUES ('d3635f6f4f33475871820baa93d6ac95', 'sv', 'aad13ff0ff9fb151cb8410801e4eeb0a', 'FIELD_DEFINITION_UUID', 0, '<p>Kodlistan kan utökas med ytterligare värden oavsett nivå, dvs. värden kan vara inom värdena tillåtna i detta register och ytterligare värden oavsett nivå definierade av dataleverantörerna</p>', NULL, NULL, NULL, '2019-07-30 14:33:39.852', NULL);\n" + "INSERT INTO public.reg_localization VALUES ('2882c3b11a46b35ff2dfe442b2dca405', 'en', '31082311814c08a2ae0e5e647669c73f', 'FIELD_LABEL_UUID', 0, 'Not extensible', NULL, NULL, NULL, '2019-07-30 10:46:04.229', NULL);\n" + "INSERT INTO public.reg_localization VALUES ('a9c5b6993903ee53302c1099cdb0cd12', 'en', '31082311814c08a2ae0e5e647669c73f', 'FIELD_DEFINITION_UUID', 0, '<p>The code list cannot be extended, i.e. its allowed values comprise only the values specified in this register.</p>', NULL, NULL, NULL, '2019-07-30 10:46:04.232', NULL);\n" + "INSERT INTO public.reg_localization VALUES ('19f94f75b47b1338106478199ea469e6', 'bg', '31082311814c08a2ae0e5e647669c73f', 'FIELD_LABEL_UUID', 0, 'Неразширяем', NULL, NULL, NULL, '2019-07-30 14:33:47.798', NULL);\n" + "INSERT INTO public.reg_localization VALUES ('8b93daa5b9652fdb13219aced95d0708', 'bg', '31082311814c08a2ae0e5e647669c73f', 'FIELD_DEFINITION_UUID', 0, '<p>Списъкът на кодовете не може да бъде разширяван, т.e. неговите разрешени стойности включват само стойностите, посочени в този регистър.</p>', NULL, NULL, NULL, '2019-07-30 14:33:47.801', NULL);\n" + "INSERT INTO public.reg_localization VALUES ('3c9ac7f2ceecfb7f5933f387a7a5b119', 'cs', '31082311814c08a2ae0e5e647669c73f', 'FIELD_LABEL_UUID', 0, 'Nerozšiřitelný', NULL, NULL, NULL, '2019-07-30 14:33:47.804', NULL);\n" + "INSERT INTO public.reg_localization VALUES ('4501bb57362d11ce25505f50612240db', 'cs', '31082311814c08a2ae0e5e647669c73f', 'FIELD_DEFINITION_UUID', 0, '<p>Číselník nemůže být rozšířen, tj. povolené hodnoty zahrnují pouze hodnoty specifikované v registru.</p>', NULL, NULL, NULL, '2019-07-30 14:33:47.807', NULL);\n" + "INSERT INTO public.reg_localization VALUES ('82eacab03a303f16fd576b56c08cf9c1', 'da', '31082311814c08a2ae0e5e647669c73f', 'FIELD_LABEL_UUID', 0, 'Kan ikke udvides', NULL, NULL, NULL, '2019-07-30 14:33:47.809', NULL);\n" + "INSERT INTO public.reg_localization VALUES ('a0f99e1950c8fe2ecee8d82c775e0521', 'da', '31082311814c08a2ae0e5e647669c73f', 'FIELD_DEFINITION_UUID', 0, '<p>Kodelisten kan ikke udvides, dvs. tilladte værdier udgøres alene af værdier i dette register.</p>', NULL, NULL, NULL, '2019-07-30 14:33:47.812', NULL);\n" + "INSERT INTO public.reg_localization VALUES ('22683dff64920f55a0a9147cb8e615d7', 'de', '31082311814c08a2ae0e5e647669c73f', 'FIELD_LABEL_UUID', 0, 'Nicht erweiterbar', NULL, NULL, NULL, '2019-07-30 14:33:47.814', NULL);\n" + "INSERT INTO public.reg_localization VALUES ('c922cab709e74be3ab4b4ef68d883922', 'de', '31082311814c08a2ae0e5e647669c73f', 'FIELD_DEFINITION_UUID', 0, '<p>Die Codeliste darf nicht erweitert werden, d.h. ihre erlaubten Werte umfassen nur die Werte, die in diesem Register enthalten sind.</p>', NULL, NULL, NULL, '2019-07-30 14:33:47.816', NULL);\n" + "INSERT INTO public.reg_localization VALUES ('bec8bdbaffaddc1ac470d409891081c3', 'et', '31082311814c08a2ae0e5e647669c73f', 'FIELD_LABEL_UUID', 0, 'Mittelaiendatav', NULL, NULL, NULL, '2019-07-30 14:33:47.819', NULL);\n" + "INSERT INTO public.reg_localization VALUES ('23850e32954da7b2b5cd3eb30fbad198', 'et', '31082311814c08a2ae0e5e647669c73f', 'FIELD_DEFINITION_UUID', 0, '<p>Koodiloendit ei saa laiendada, st tema lubatavad väärtused saavad olla ainult sellised, mis on määratud selles registris.</p>', NULL, NULL, NULL, '2019-07-30 14:33:47.822', NULL);\n" + "INSERT INTO public.reg_localization VALUES ('15cd0617e83fa3720e2c60c9d60aa487', 'el', '31082311814c08a2ae0e5e647669c73f', 'FIELD_LABEL_UUID', 0, 'μη επεκτάσιμο', NULL, NULL, NULL, '2019-07-30 14:33:47.824', NULL);\n" + "INSERT INTO public.reg_localization VALUES ('6fd719cf0f7563f720335bd4efd46d12', 'el', '31082311814c08a2ae0e5e647669c73f', 'FIELD_DEFINITION_UUID', 0, '<p>Αυτός ο κωδικός λίστας δεν μπορεί να επεκταθεί, οι επιτρεπόμενες τιμές του αποτελούν τις τιμές που αναγράφονται στον παρόν καταχωρητής</p>', NULL, NULL, NULL, '2019-07-30 14:33:47.827', NULL);\n" + "INSERT INTO public.reg_localization VALUES ('3c7c42d66b04bb72cd184b53c9eea7de', 'es', '31082311814c08a2ae0e5e647669c73f', 'FIELD_LABEL_UUID', 0, 'No extensible', NULL, NULL, NULL, '2019-07-30 14:33:47.829', NULL);\n" + "INSERT INTO public.reg_localization VALUES ('4c1b1a7e7da8d4cec0c1fbf484b459a7', 'es', '31082311814c08a2ae0e5e647669c73f', 'FIELD_DEFINITION_UUID', 0, '<p>La lista de códigos no se puede extender; es decir, los valores permitidos son únicamente los valores especificados en el registro</p>', NULL, NULL, NULL, '2019-07-30 14:33:47.832', NULL);\n" + "INSERT INTO public.reg_localization VALUES ('ddee8f853fd39b4dc2670c950e959d21', 'fr', '31082311814c08a2ae0e5e647669c73f', 'FIELD_LABEL_UUID', 0, 'Non extensible', NULL, NULL, NULL, '2019-07-30 14:33:47.836', NULL);\n" + "INSERT INTO public.reg_localization VALUES ('a230591ad584f96be9d667f6599e3dbf', 'fr', '31082311814c08a2ae0e5e647669c73f', 'FIELD_DEFINITION_UUID', 0, '<p>La liste de codes ne peut pas être étendue: seuls les codes existants sont autorisés.</p>', NULL, NULL, NULL, '2019-07-30 14:33:47.839', NULL);\n" + "INSERT INTO public.reg_localization VALUES ('6f98438795d52f65f2085317586d6870', 'hr', '31082311814c08a2ae0e5e647669c73f', 'FIELD_LABEL_UUID', 0, 'Nije proširivo', NULL, NULL, NULL, '2019-07-30 14:33:47.841', NULL);\n" + "INSERT INTO public.reg_localization VALUES ('96cd193e555c8c52c112c664f1fc7018', 'hr', '31082311814c08a2ae0e5e647669c73f', 'FIELD_DEFINITION_UUID', 0, '<p>Kodna lista nije proširiva tj. dozvoljene su samo vrijednosti već specificirane u registru.</p>', NULL, NULL, NULL, '2019-07-30 14:33:47.844', NULL);\n" + "INSERT INTO public.reg_localization VALUES ('f2868836f1489193892e42fcb177dfde', 'it', '31082311814c08a2ae0e5e647669c73f', 'FIELD_LABEL_UUID', 0, 'Non estendibile', NULL, NULL, NULL, '2019-07-30 14:33:47.846', NULL);\n" + "INSERT INTO public.reg_localization VALUES ('dade25b2d63869c730b58e1448b51217', 'it', '31082311814c08a2ae0e5e647669c73f', 'FIELD_DEFINITION_UUID', 0, '<p>L''elenco di codici non può essere esteso, ossia i suoi valori consentiti comprendono solo i valori indicati in questo registro.</p>', NULL, NULL, NULL, '2019-07-30 14:33:47.849', NULL);\n" + "INSERT INTO public.reg_localization VALUES ('abdfded27d4f3107934f0ded9a003458', 'lv', '31082311814c08a2ae0e5e647669c73f', 'FIELD_LABEL_UUID', 0, 'Nav paplašināms', NULL, NULL, NULL, '2019-07-30 14:33:47.851', NULL);\n" + "INSERT INTO public.reg_localization VALUES ('5c8d065d5e6fb9c031a15fea151e05e4', 'lv', '31082311814c08a2ae0e5e647669c73f', 'FIELD_DEFINITION_UUID', 0, '<p>Kodu sarakstu nevar paplašināt, t.i., atļautās vērtības aptver tikai šajā reģistrā iekļautās vērtības.</p>', NULL, NULL, NULL, '2019-07-30 14:33:47.855', NULL);\n" + "INSERT INTO public.reg_localization VALUES ('f7d740cbda36f5868a49aca833c51a6a', 'lt', '31082311814c08a2ae0e5e647669c73f', 'FIELD_LABEL_UUID', 0, 'Neplečiamas', NULL, NULL, NULL, '2019-07-30 14:33:47.858', NULL);\n" + "INSERT INTO public.reg_localization VALUES ('fe31278bf26f848e4a736a6c9c934e50', 'lt', '31082311814c08a2ae0e5e647669c73f', 'FIELD_DEFINITION_UUID', 0, '<p>Kodų sąrašas negali būti papildytas, t.y. visos leidžiamos reikšmės jau nurodytos šiame registre.</p>', NULL, NULL, NULL, '2019-07-30 14:33:47.86', NULL);\n" + "INSERT INTO public.reg_localization VALUES ('b8cf703ff76e5d8528fdf9c289836c9a', 'hu', '31082311814c08a2ae0e5e647669c73f', 'FIELD_LABEL_UUID', 0, 'Nem bővíthető', NULL, NULL, NULL, '2019-07-30 14:33:47.863', NULL);\n" + "INSERT INTO public.reg_localization VALUES ('e4c1d272ee6c102258f5cc3f0a15b68c', 'hu', '31082311814c08a2ae0e5e647669c73f', 'FIELD_DEFINITION_UUID', 0, '<p>A kódlista nem bővíthető, vagyis a változók csak az itt szereplő értékeket vehetik fel.</p>', NULL, NULL, NULL, '2019-07-30 14:33:47.866', NULL);\n" + "INSERT INTO public.reg_localization VALUES ('ec2414ee59b84370678836290a254f21', 'mt', '31082311814c08a2ae0e5e647669c73f', 'FIELD_LABEL_UUID', 0, 'Mhux estensibbli', NULL, NULL, NULL, '2019-07-30 14:33:47.87', NULL);\n" + "INSERT INTO public.reg_localization VALUES ('f9a210c5002aee7d4ffecaf71de9e7cb', 'mt', '31082311814c08a2ae0e5e647669c73f', 'FIELD_DEFINITION_UUID', 0, '<p>Il-lista tal-kodiċi ma tistax tiġi estiża, jiġifieri l-valuri permessi tagħha jinkludu biss il-valuri speċifikati f''dan ir-reġistru.</p>', NULL, NULL, NULL, '2019-07-30 14:33:47.872', NULL);\n" + "INSERT INTO public.reg_localization VALUES ('fc000090126700c38af8dbe59896f7e2', 'nl', '31082311814c08a2ae0e5e647669c73f', 'FIELD_LABEL_UUID', 0, 'Niet uitbreidbaar', NULL, NULL, NULL, '2019-07-30 14:33:47.875', NULL);\n" + "INSERT INTO public.reg_localization VALUES ('d6f9ccea5406b89d352e22baca1b596b', 'nl', '31082311814c08a2ae0e5e647669c73f', 'FIELD_DEFINITION_UUID', 0, '<p>De codelijst kan niet worden uitgebreid, met andere woorden de toegestane waarden zijn beperkt tot de waarden in dit register.</p>', NULL, NULL, NULL, '2019-07-30 14:33:47.879', NULL);\n" + "INSERT INTO public.reg_localization VALUES ('11954c186c2d318d73b5494c1be2f744', 'pl', '31082311814c08a2ae0e5e647669c73f', 'FIELD_LABEL_UUID', 0, 'Nierozszerzalny', NULL, NULL, NULL, '2019-07-30 14:33:47.881', NULL);\n" + "INSERT INTO public.reg_localization VALUES ('49e692e17b9a4f1e0329dcb2ce3822b0', 'pl', '31082311814c08a2ae0e5e647669c73f', 'FIELD_DEFINITION_UUID', 0, '<p>Lista kodów nie może być rozszerzona, to znaczy, że dopuszczalne wartości zawierają tylko wartości określone w tym wykazie.</p>', NULL, NULL, NULL, '2019-07-30 14:33:47.885', NULL);\n" + "INSERT INTO public.reg_localization VALUES ('b036deb6283f8bd4e4c5f995770e7f3a', 'pt', '31082311814c08a2ae0e5e647669c73f', 'FIELD_LABEL_UUID', 0, 'Não extensível', NULL, NULL, NULL, '2019-07-30 14:33:47.888', NULL);\n" + "INSERT INTO public.reg_localization VALUES ('44742a895e420cf42b062120e643d298', 'pt', '31082311814c08a2ae0e5e647669c73f', 'FIELD_DEFINITION_UUID', 0, '<p>A lista de códigos não pode ser alargada, ou seja, os valores permitidos compreendem apenas os valores especificados deste registo</p>', NULL, NULL, NULL, '2019-07-30 14:33:47.891', NULL);\n" + "INSERT INTO public.reg_localization VALUES ('30fdd3b48e64288d3233a64d4a30fd8d', 'ro', '31082311814c08a2ae0e5e647669c73f', 'FIELD_LABEL_UUID', 0, 'Nu este extensibilă', NULL, NULL, NULL, '2019-07-30 14:33:47.894', NULL);\n" + "INSERT INTO public.reg_localization VALUES ('0b8ad4e5116f97ac18b1887759c4c131', 'ro', '31082311814c08a2ae0e5e647669c73f', 'FIELD_DEFINITION_UUID', 0, '<p>Lista de coduri nu poate fi extinsă, adică valorile sale permise cuprind numai valorile specificate în acest registru.</p>', NULL, NULL, NULL, '2019-07-30 14:33:47.897', NULL);\n" + "INSERT INTO public.reg_localization VALUES ('d67afd0baac8af8d04cd9ebdb8ed6299', 'sk', '31082311814c08a2ae0e5e647669c73f', 'FIELD_LABEL_UUID', 0, 'Nerozšíriteľný', NULL, NULL, NULL, '2019-07-30 14:33:47.901', NULL);\n" + "INSERT INTO public.reg_localization VALUES ('fccf95be67ee3f8ce8a01488d204ffdb', 'sk', '31082311814c08a2ae0e5e647669c73f', 'FIELD_DEFINITION_UUID', 0, '<p>Zoznam kódov (číselník) nemožno rozšíriť, t.j. jeho povolené hodnoty zahŕňajú iba hodnoty uvedené v tomto registri.</p>', NULL, NULL, NULL, '2019-07-30 14:33:47.903', NULL);\n" + "INSERT INTO public.reg_localization VALUES ('1b1fd27cfc55b4d563d26d5366f8d531', 'sl', '31082311814c08a2ae0e5e647669c73f', 'FIELD_LABEL_UUID', 0, 'Ni mogoče dopolnjevati', NULL, NULL, NULL, '2019-07-30 14:33:47.906', NULL);\n" + "INSERT INTO public.reg_localization VALUES ('341eae03dcf0692c458c13128cf0daa9', 'sl', '31082311814c08a2ae0e5e647669c73f', 'FIELD_DEFINITION_UUID', 0, '<p>Seznama oznak ni mogoče dopolnjevati, t.j. dovoljene vrednosti so le tiste navedne v registru.</p>', NULL, NULL, NULL, '2019-07-30 14:33:47.909', NULL);\n" + "INSERT INTO public.reg_localization VALUES ('902ed203157add38a4b9710628409fbd', 'fi', '31082311814c08a2ae0e5e647669c73f', 'FIELD_LABEL_UUID', 0, 'Ei laajennettavissa', NULL, NULL, NULL, '2019-07-30 14:33:47.912', NULL);\n" + "INSERT INTO public.reg_localization VALUES ('7d90a1607cf2a49433be91857c4ee0a6', 'fi', '31082311814c08a2ae0e5e647669c73f', 'FIELD_DEFINITION_UUID', 0, '<p>Koodiluetteloa ei voi laajentaa. Koodiluettelossa siis sallitaan ainoastaan tässä rekisterissä määritellyt arvot.</p>', NULL, NULL, NULL, '2019-07-30 14:33:47.914', NULL);\n" + "INSERT INTO public.reg_localization VALUES ('c576695c073fc4b5e07e402a512c2e4c', 'sv', '31082311814c08a2ae0e5e647669c73f', 'FIELD_LABEL_UUID', 0, 'Ej utökningsbar', NULL, NULL, NULL, '2019-07-30 14:33:47.917', NULL);\n" + "INSERT INTO public.reg_localization VALUES ('9654d18049d837e9158cee79808426e7', 'sv', '31082311814c08a2ae0e5e647669c73f', 'FIELD_DEFINITION_UUID', 0, '<p>Kodlistan kan inte utökas, dvs. dess tillåtna värden inkluderar bara de värden som är specificierade i denna lista.</p>', NULL, NULL, NULL, '2019-07-30 14:33:47.92', NULL);"; private final String QUERY_EXTENSIBILITY_1 = "INSERT INTO public.reg_localization VALUES ('dadcaab8a416afde92ec52e1b10efbd8', 'en', '088f861f19d356685c0da1916fbb260a', 'FIELD_LABEL_UUID', 0, 'Empty code list', NULL, NULL, NULL, '2019-07-30 10:45:49.895', NULL);\n" + "INSERT INTO public.reg_localization VALUES ('3c3b087f514ccd5b1f83a6d3fe5b7770', 'en', '088f861f19d356685c0da1916fbb260a', 'FIELD_DEFINITION_UUID', 0, '<p>No values are specified for this code list in this register, i.e. its allowed values comprise any values defined by data providers.</p>', NULL, NULL, NULL, '2019-07-30 10:45:49.9', NULL);\n" + "INSERT INTO public.reg_localization VALUES ('40ef168c0b003cdedc758193c71cb716', 'bg', '088f861f19d356685c0da1916fbb260a', 'FIELD_LABEL_UUID', 0, 'Празен списък на кодове', NULL, NULL, NULL, '2019-07-30 14:34:10', NULL);\n" + "INSERT INTO public.reg_localization VALUES ('b35647f0e49c3509094db5f73e2b65b9', 'bg', '088f861f19d356685c0da1916fbb260a', 'FIELD_DEFINITION_UUID', 0, '<p>За този списък на кодове в този регистър не са посочени никакви стойности, т.e. неговите допустими стойности обхващат всякакви стойности, дефинирани от доставчиците на данни</p>', NULL, NULL, NULL, '2019-07-30 14:34:10.002', NULL);\n" + "INSERT INTO public.reg_localization VALUES ('b91cd7a0d21079abe0d2482537b2e74e', 'cs', '088f861f19d356685c0da1916fbb260a', 'FIELD_LABEL_UUID', 0, 'Prázdný číselník', NULL, NULL, NULL, '2019-07-30 14:34:10.005', NULL);\n" + "INSERT INTO public.reg_localization VALUES ('fd8307fdd622ca56db9f0ac0d75071a6', 'cs', '088f861f19d356685c0da1916fbb260a', 'FIELD_DEFINITION_UUID', 0, '<p>Pro tento číselník nebyly definovány žádné hodnoty, tj. povolené hodnoty budou zahrnovat hodnoty definované poskytovatelem dat.</p>', NULL, NULL, NULL, '2019-07-30 14:34:10.007', NULL);\n" + "INSERT INTO public.reg_localization VALUES ('64fc41f43cc95f286987fedd73ebe76d', 'da', '088f861f19d356685c0da1916fbb260a', 'FIELD_LABEL_UUID', 0, 'Tom kodeliste', NULL, NULL, NULL, '2019-07-30 14:34:10.01', NULL);\n" + "INSERT INTO public.reg_localization VALUES ('e3ddf1dce47834f49224a0af159e5b08', 'da', '088f861f19d356685c0da1916fbb260a', 'FIELD_DEFINITION_UUID', 0, '<p>Ingen værdier er specificeret for denne kodeliste i dette register, dvs. tilladte værdier udgøres af alle værdier defineret af dataleverandører.</p>', NULL, NULL, NULL, '2019-07-30 14:34:10.012', NULL);\n" + "INSERT INTO public.reg_localization VALUES ('a3519a25500797957895c1026dd03d19', 'de', '088f861f19d356685c0da1916fbb260a', 'FIELD_LABEL_UUID', 0, 'Leere Codeliste', NULL, NULL, NULL, '2019-07-30 14:34:10.014', NULL);\n" + "INSERT INTO public.reg_localization VALUES ('63505bb8fa7fc6a46c000086ce0f6422', 'de', '088f861f19d356685c0da1916fbb260a', 'FIELD_DEFINITION_UUID', 0, '<p>Für die Codeliste sind in diesem Register keine Werte spezifiziert, d.h. ihre erlaubten Werte umfassen beliebige von Datenanbietern definierte Werte.</p>', NULL, NULL, NULL, '2019-07-30 14:34:10.016', NULL);\n" + "INSERT INTO public.reg_localization VALUES ('1b570544e95cd96bc083c22e7214f857', 'et', '088f861f19d356685c0da1916fbb260a', 'FIELD_LABEL_UUID', 0, 'Tühi koodiloend', NULL, NULL, NULL, '2019-07-30 14:34:10.019', NULL);\n" + "INSERT INTO public.reg_localization VALUES ('68da0415cce66f85f4009bbfa230ab95', 'et', '088f861f19d356685c0da1916fbb260a', 'FIELD_DEFINITION_UUID', 0, '<p>Selle registri koodiloendis ei ole määratletud väärtusi, st selle lubatud väärtused hõlmavad andmete tarnijate poolt määratletud suvalisi väärtusi.</p>', NULL, NULL, NULL, '2019-07-30 14:34:10.022', NULL);\n" + "INSERT INTO public.reg_localization VALUES ('c597d7be889c439e4ad5a794adc51556', 'el', '088f861f19d356685c0da1916fbb260a', 'FIELD_LABEL_UUID', 0, 'οποιοδήποτε (κενός κωδικός λίστας)', NULL, NULL, NULL, '2019-07-30 14:34:10.024', NULL);\n" + "INSERT INTO public.reg_localization VALUES ('3c49ad6817a227bd6ea5461881fa3c15', 'el', '088f861f19d356685c0da1916fbb260a', 'FIELD_DEFINITION_UUID', 0, '<p>Δεν ορίζονται τιμές για αυτόν τον κωδικό λίστας σε αυτό το καταχωρητή, οι επιτρεπόμενες τιμές αποτελούνται από τιμές όπως ορίζονται από παρόχους δεδομένων</p>', NULL, NULL, NULL, '2019-07-30 14:34:10.027', NULL);\n" + "INSERT INTO public.reg_localization VALUES ('9dc7d303fed4d3685a244baac946f237', 'es', '088f861f19d356685c0da1916fbb260a', 'FIELD_LABEL_UUID', 0, 'Lista de códigos vacía', NULL, NULL, NULL, '2019-07-30 14:34:10.03', NULL);\n" + "INSERT INTO public.reg_localization VALUES ('a8347b39bb1eab879af12ded0030f00c', 'es', '088f861f19d356685c0da1916fbb260a', 'FIELD_DEFINITION_UUID', 0, '<p>No se ha especificado ningún valor para esta lista de códigos en el registro; es decir. los valores permitidos incluyen cualquier valor especificado por el proveedor de datos</p>', NULL, NULL, NULL, '2019-07-30 14:34:10.032', NULL);\n" + "INSERT INTO public.reg_localization VALUES ('ea8a942fed6c9cb6c931255679746ba0', 'fr', '088f861f19d356685c0da1916fbb260a', 'FIELD_LABEL_UUID', 0, 'Liste de codes vide', NULL, NULL, NULL, '2019-07-30 14:34:10.034', NULL);\n" + "INSERT INTO public.reg_localization VALUES ('a01e8a742a45e967f28970c5e1dd9814', 'fr', '088f861f19d356685c0da1916fbb260a', 'FIELD_DEFINITION_UUID', 0, '<p>Aucune valeur n''est définie dans ce registre: toute valeur définie par un fournisseur de données est autorisé.</p>', NULL, NULL, NULL, '2019-07-30 14:34:10.037', NULL);\n" + "INSERT INTO public.reg_localization VALUES ('add0a2c95445547a9a487b5acb969b92', 'hr', '088f861f19d356685c0da1916fbb260a', 'FIELD_LABEL_UUID', 0, 'Prazna kodna lista', NULL, NULL, NULL, '2019-07-30 14:34:10.04', NULL);\n" + "INSERT INTO public.reg_localization VALUES ('d5d8a341f5bbd1c150e8c82eb944b1d6', 'hr', '088f861f19d356685c0da1916fbb260a', 'FIELD_DEFINITION_UUID', 0, '<p>Vrijednosti za ovu kodnu listu nisu specificirane u registru tj. dozvoljene su bilo koje vrijednosti definirane od strane pružatelja podataka</p>', NULL, NULL, NULL, '2019-07-30 14:34:10.043', NULL);\n" + "INSERT INTO public.reg_localization VALUES ('81e5af7ea5e5a354022aeb566a8d932f', 'it', '088f861f19d356685c0da1916fbb260a', 'FIELD_LABEL_UUID', 0, 'Lista dei codici vuota', NULL, NULL, NULL, '2019-07-30 14:34:10.046', NULL);\n" + "INSERT INTO public.reg_localization VALUES ('47cd056fe283daf04e4b0e13c57e1ffb', 'it', '088f861f19d356685c0da1916fbb260a', 'FIELD_DEFINITION_UUID', 0, '<p>Non sono specificati valori per tale lista di codici in questo registro, ossia i suoi valori consentiti comprendono i valori definiti dal provider di dati.</p>', NULL, NULL, NULL, '2019-07-30 14:34:10.048', NULL);\n" + "INSERT INTO public.reg_localization VALUES ('646460c83fdeabfe86fdf4b03177333a', 'lv', '088f861f19d356685c0da1916fbb260a', 'FIELD_LABEL_UUID', 0, 'Tukšs kodu saraksts', NULL, NULL, NULL, '2019-07-30 14:34:10.051', NULL);\n" + "INSERT INTO public.reg_localization VALUES ('ccc1366aec34f497c7671ccbcbd83cdc', 'lv', '088f861f19d356685c0da1916fbb260a', 'FIELD_DEFINITION_UUID', 0, '<p>Šim kodu sarakstam reģistrā nav norādīta neviena vērtība, proti, atļautās vērtības aptver jebkuru datu sniedzēja definēto vērtību.</p>', NULL, NULL, NULL, '2019-07-30 14:34:10.054', NULL);\n" + "INSERT INTO public.reg_localization VALUES ('f30e1ef9550587784ab60f0ff1871fce', 'lt', '088f861f19d356685c0da1916fbb260a', 'FIELD_LABEL_UUID', 0, 'Tuščias kodų sąrašas', NULL, NULL, NULL, '2019-07-30 14:34:10.056', NULL);\n" + "INSERT INTO public.reg_localization VALUES ('0cbac4b932c77eadbb13047c3919f4b0', 'lt', '088f861f19d356685c0da1916fbb260a', 'FIELD_DEFINITION_UUID', 0, '<p>Kodų sąrašas šiame registre neturi apibrėžtų reikšmių; leidžiamos bet kokios duomenų teikėjo nurodytos reikšmės.</p>', NULL, NULL, NULL, '2019-07-30 14:34:10.059', NULL);\n" + "INSERT INTO public.reg_localization VALUES ('39614b4fd78b73003e42a0d68c373970', 'hu', '088f861f19d356685c0da1916fbb260a', 'FIELD_LABEL_UUID', 0, 'Üres kódlista', NULL, NULL, NULL, '2019-07-30 14:34:10.061', NULL);\n" + "INSERT INTO public.reg_localization VALUES ('5d214a6a93bbd01be7e85d22057e318f', 'hu', '088f861f19d356685c0da1916fbb260a', 'FIELD_DEFINITION_UUID', 0, '<p>Ez a nyilvántartás nem határoz meg értékeket. Az adatszolgáltatók bármilyen értékeket hozzárendelhetnek.</p>', NULL, NULL, NULL, '2019-07-30 14:34:10.064', NULL);\n" + "INSERT INTO public.reg_localization VALUES ('7a0ddb6ed156cf3b0fd2a2a80fae3979', 'mt', '088f861f19d356685c0da1916fbb260a', 'FIELD_LABEL_UUID', 0, 'Lista tal-kodiċi vojta', NULL, NULL, NULL, '2019-07-30 14:34:10.066', NULL);\n" + "INSERT INTO public.reg_localization VALUES ('6023b071c443e5c5ad606ae5aef3c1bc', 'mt', '088f861f19d356685c0da1916fbb260a', 'FIELD_DEFINITION_UUID', 0, '<p>L-ebda valuri m'' huma speċifikati għal din il-lista ta'' kodiċi f''dan ir-reġistru, jiġifieri l-valuri permessi tagħha jinkludu kull valur definit mill-fornituri tad-dejta</p>', NULL, NULL, NULL, '2019-07-30 14:34:10.069', NULL);\n" + "INSERT INTO public.reg_localization VALUES ('a9a08fcfeaaed52d9a3677812637e135', 'nl', '088f861f19d356685c0da1916fbb260a', 'FIELD_LABEL_UUID', 0, 'Lege codelijst', NULL, NULL, NULL, '2019-07-30 14:34:10.072', NULL);\n" + "INSERT INTO public.reg_localization VALUES ('459201ac1b9dde97dde900f3b7919ce3', 'nl', '088f861f19d356685c0da1916fbb260a', 'FIELD_DEFINITION_UUID', 0, '<p>Er zijn geen waarden gespecifieerd voor de codelijst in dit register,met andere woorden alle waarden gedefinieerd door gegevensbeheerders zijn toegestaan.</p>', NULL, NULL, NULL, '2019-07-30 14:34:10.075', NULL);\n" + "INSERT INTO public.reg_localization VALUES ('cc507eda3145c3d5dadb824a8f40ae37', 'pl', '088f861f19d356685c0da1916fbb260a', 'FIELD_LABEL_UUID', 0, 'Pusta lista kodów', NULL, NULL, NULL, '2019-07-30 14:34:10.077', NULL);\n" + "INSERT INTO public.reg_localization VALUES ('54ed512665fee90b556a5825835a1a6b', 'pl', '088f861f19d356685c0da1916fbb260a', 'FIELD_DEFINITION_UUID', 0, '<p>Nie określono wartości dla tej listy kodów w tym rejestrze, to znaczy, że dozwolone wartości zawierają każde wartości zdefiniowane przez dostawców danych.</p>', NULL, NULL, NULL, '2019-07-30 14:34:10.08', NULL);\n" + "INSERT INTO public.reg_localization VALUES ('c0a3c9f7f3586f93406de9335d77c06f', 'pt', '088f861f19d356685c0da1916fbb260a', 'FIELD_LABEL_UUID', 0, 'Lista de códigos vazia', NULL, NULL, NULL, '2019-07-30 14:34:10.083', NULL);\n" + "INSERT INTO public.reg_localization VALUES ('694c2ab7f2bfd1cad1d528b198fa9f23', 'pt', '088f861f19d356685c0da1916fbb260a', 'FIELD_DEFINITION_UUID', 0, '<p>Não há valores especificados para esta lista de códigos deste registo, ou seja, os valores permitidos compreendem todos os valores definidos por provedores de dados</p>', NULL, NULL, NULL, '2019-07-30 14:34:10.084', NULL);\n" + "INSERT INTO public.reg_localization VALUES ('e88cc8388e9d0a4832d9eec4c26c0c0f', 'ro', '088f861f19d356685c0da1916fbb260a', 'FIELD_LABEL_UUID', 0, 'Listă de coduri fără elemente', NULL, NULL, NULL, '2019-07-30 14:34:10.087', NULL);\n" + "INSERT INTO public.reg_localization VALUES ('11349cd60e6ddf48ad408b7ab6696252', 'ro', '088f861f19d356685c0da1916fbb260a', 'FIELD_DEFINITION_UUID', 0, '<p>Nicio valoare nu este specificată pentru această listă de coduri în acest registru, adică cuprinde orice valoare definită de furnizorii de date.</p>', NULL, NULL, NULL, '2019-07-30 14:34:10.09', NULL);\n" + "INSERT INTO public.reg_localization VALUES ('638ea9485081607dc41d6363cb9490bb', 'sk', '088f861f19d356685c0da1916fbb260a', 'FIELD_LABEL_UUID', 0, 'Prázdny zoznam kódov', NULL, NULL, NULL, '2019-07-30 14:34:10.093', NULL);\n" + "INSERT INTO public.reg_localization VALUES ('a53294b44596a68c39f66110b2a0d254', 'sk', '088f861f19d356685c0da1916fbb260a', 'FIELD_DEFINITION_UUID', 0, '<p>Pre tento zoznam kódov (číselník) nie sústanovené žiadne hodnoty, t.j. jeho povolené hodnoty zohľadňujú akékoľvek hodnoty definované poskytovateˇmi údajov.</p>', NULL, NULL, NULL, '2019-07-30 14:34:10.096', NULL);\n" + "INSERT INTO public.reg_localization VALUES ('728f1066e1a3350f025d04b2d92a9ef5', 'sl', '088f861f19d356685c0da1916fbb260a', 'FIELD_LABEL_UUID', 0, 'Prazen seznam oznak', NULL, NULL, NULL, '2019-07-30 14:34:10.098', NULL);\n" + "INSERT INTO public.reg_localization VALUES ('45137c0ffad5f2d1b8cf41533fdb6158', 'sl', '088f861f19d356685c0da1916fbb260a', 'FIELD_DEFINITION_UUID', 0, '<p>Vrednost za pričujoči seznam oznak tega registre ni opredeljena, t.j. dovoljene vrednosti so vse tiste, ki jih opredeli ponudnik podatkov.</p>', NULL, NULL, NULL, '2019-07-30 14:34:10.101', NULL);\n" + "INSERT INTO public.reg_localization VALUES ('53a3dc3922a900aadc603c2824e97062', 'fi', '088f861f19d356685c0da1916fbb260a', 'FIELD_LABEL_UUID', 0, 'Tyhjä koodiluettelo', NULL, NULL, NULL, '2019-07-30 14:34:10.104', NULL);\n" + "INSERT INTO public.reg_localization VALUES ('bdbd12dac004efe165461174638c49e1', 'fi', '088f861f19d356685c0da1916fbb260a', 'FIELD_DEFINITION_UUID', 0, '<p>Tälle koodiluettelolle ei ole määritelty koodiarvoja tässä rekisterissä, joten luettelo muodostuu tiedontuottajien määrittelemistä koodiarvoista.</p>', NULL, NULL, NULL, '2019-07-30 14:34:10.107', NULL);\n" + "INSERT INTO public.reg_localization VALUES ('f6a96672bfaa26561777fd2c11dee25d', 'sv', '088f861f19d356685c0da1916fbb260a', 'FIELD_LABEL_UUID', 0, 'Tom kodlista', NULL, NULL, NULL, '2019-07-30 14:34:10.109', NULL);\n" + "INSERT INTO public.reg_localization VALUES ('381dcc1ad650297b4fc65a79fb0de084', 'sv', '088f861f19d356685c0da1916fbb260a', 'FIELD_DEFINITION_UUID', 0, '<p>Inga värden är specificierade för denna kodlista i detta register. dvs. tillåtna värden är alla värden definierade av dataleverantörerna</p>', NULL, NULL, NULL, '2019-07-30 14:34:10.113', NULL);\n" + "INSERT INTO public.reg_localization VALUES ('c764fa226b511ca3692e5ee24e13874b', 'en', '91e00e7f8d73c54fa2f80c67d3d9d5b0', 'FIELD_LABEL_UUID', 0, 'Extensible with narrower values', NULL, NULL, NULL, '2019-07-30 10:41:43.884', NULL);\n" + "INSERT INTO public.reg_localization VALUES ('86f3b5adcd0d541ed51afb7baec63c77', 'en', '91e00e7f8d73c54fa2f80c67d3d9d5b0', 'FIELD_DEFINITION_UUID', 0, '<p>The code list can only be extended with narrower values, i.e. its allowed values comprise the values specified in this register and narrower values defined by data providers.</p>', NULL, NULL, NULL, '2019-07-30 10:41:43.902', NULL);\n" + "INSERT INTO public.reg_localization VALUES ('5cd387613b918de85f78c16941d6739e', 'bg', '91e00e7f8d73c54fa2f80c67d3d9d5b0', 'FIELD_LABEL_UUID', 0, 'Списък на кодове, позволяващ разширяване със стойности от по-долно ниво в йерархията', NULL, NULL, NULL, '2019-07-30 14:35:08.182', NULL);\n" + "INSERT INTO public.reg_localization VALUES ('08678abd2653c801272966b87f6eb503', 'bg', '91e00e7f8d73c54fa2f80c67d3d9d5b0', 'FIELD_DEFINITION_UUID', 0, '<p>Списъкът на кодовете може да бъде разширяван със стойности от по-долно ниво в йерархията, т.е. допустимите стойности обхващат стойности, посочени в този регистър и стойности от по-долно ниво в йерархията, дефинирани от доставчиците на данни.</p>', NULL, NULL, NULL, '2019-07-30 14:35:08.185', NULL);\n" + "INSERT INTO public.reg_localization VALUES ('23ca5c9c9f9349b1d97f0ae817ce5d5d', 'cs', '91e00e7f8d73c54fa2f80c67d3d9d5b0', 'FIELD_LABEL_UUID', 0, 'Rozšiřitelný s použitím užšího oboru hodnot', NULL, NULL, NULL, '2019-07-30 14:35:08.188', NULL);\n" + "INSERT INTO public.reg_localization VALUES ('e44aef47a1bf6c1507a29be560cd5b86', 'cs', '91e00e7f8d73c54fa2f80c67d3d9d5b0', 'FIELD_DEFINITION_UUID', 0, '<p>Číselník může být rozšířen pouze o užší obor hodnot, tj. povolené hodnoty zahrnují hodnoty specifikované v registru a užší obor hodnot definovaný poskytovatelem dat.</p>', NULL, NULL, NULL, '2019-07-30 14:35:08.19', NULL);\n" + "INSERT INTO public.reg_localization VALUES ('b715ef1e3ea25b5d5f3e60af32afee23', 'da', '91e00e7f8d73c54fa2f80c67d3d9d5b0', 'FIELD_LABEL_UUID', 0, 'Kan udvides med underliggende værdier', NULL, NULL, NULL, '2019-07-30 14:35:08.193', NULL);\n" + "INSERT INTO public.reg_localization VALUES ('c9d7d330de270e5f4eebfaad98752852', 'da', '91e00e7f8d73c54fa2f80c67d3d9d5b0', 'FIELD_DEFINITION_UUID', 0, '<p>Kodelisten kan kun udvides med underliggende værdier, dvs. tilladte værdier udgøres af værdier i dette register samt undeliggende værdier defineret af dataleverandører.</p>', NULL, NULL, NULL, '2019-07-30 14:35:08.195', NULL);\n" + "INSERT INTO public.reg_localization VALUES ('71a9a76e480888c0151406532337ebbc', 'de', '91e00e7f8d73c54fa2f80c67d3d9d5b0', 'FIELD_LABEL_UUID', 0, 'Erweiterbar um spezifischere Werte', NULL, NULL, NULL, '2019-07-30 14:35:08.198', NULL);\n" + "INSERT INTO public.reg_localization VALUES ('37ae3acebdb3ef166021364567fee50d', 'de', '91e00e7f8d73c54fa2f80c67d3d9d5b0', 'FIELD_DEFINITION_UUID', 0, '<p>Die Codeliste darf nur um spezifischere Werte erweitert werden, d.h. ihre erlaubten Werte umfassen die Werte, die in diesem Register enthalten sind, und zusätzlich spezifischere von Datenanbietern definierte Werte.</p>', NULL, NULL, NULL, '2019-07-30 14:35:08.2', NULL);\n" + "INSERT INTO public.reg_localization VALUES ('1122177a1a888f5d04f7da416de27eea', 'et', '91e00e7f8d73c54fa2f80c67d3d9d5b0', 'FIELD_LABEL_UUID', 0, 'Laiendatav rohkem piiratud väärtustega', NULL, NULL, NULL, '2019-07-30 14:35:08.202', NULL);\n" + "INSERT INTO public.reg_localization VALUES ('cb793cdf897eb96130d6412b0f41581d', 'et', '91e00e7f8d73c54fa2f80c67d3d9d5b0', 'FIELD_DEFINITION_UUID', 0, '<p>Koodiloendit võib täiendada ainult rohkem piiratud väärtusega, st selle lubatud väärtused hõlmavad selles registris määratud väärtusi ja andmete tarnijate poolt kitsendavalt defineeritud väärtusi.</p>', NULL, NULL, NULL, '2019-07-30 14:35:08.205', NULL);\n" + "INSERT INTO public.reg_localization VALUES ('2b181ce585dec877dfcc8e3fea29b9b2', 'el', '91e00e7f8d73c54fa2f80c67d3d9d5b0', 'FIELD_LABEL_UUID', 0, 'επεκτάσιμο με μικρότερες τιμές', NULL, NULL, NULL, '2019-07-30 14:35:08.207', NULL);\n" + "INSERT INTO public.reg_localization VALUES ('b5289490decaf8cae742203ecff32f56', 'el', '91e00e7f8d73c54fa2f80c67d3d9d5b0', 'FIELD_DEFINITION_UUID', 0, '<p>Αυτός ο κωδικός λίστας μπορεί να επεκταθεί μόνο με στενότερες τιμές, οι επιτρεπόμενες τιμές αποτελούν τιμές που αναγράφονται καταχωρητής και στενότερες τιμές όπως ορίζονται από παρόχους δεδομένων</p>', NULL, NULL, NULL, '2019-07-30 14:35:08.21', NULL);\n" + "INSERT INTO public.reg_localization VALUES ('064db048e3917c147c1bc76281ad1117', 'es', '91e00e7f8d73c54fa2f80c67d3d9d5b0', 'FIELD_LABEL_UUID', 0, 'Extensible con valores más específicos', NULL, NULL, NULL, '2019-07-30 14:35:08.212', NULL);\n" + "INSERT INTO public.reg_localization VALUES ('540d7144ae14ca65faeb21da556f348c', 'es', '91e00e7f8d73c54fa2f80c67d3d9d5b0', 'FIELD_DEFINITION_UUID', 0, '<p>Se puede extender la lista de códigos sólo con valores más específicos; es decir, los valores permitidos son los valores especificados en el registro y otros más específicos definidos por el proveedor de datos</p>', NULL, NULL, NULL, '2019-07-30 14:35:08.214', NULL);\n" + "INSERT INTO public.reg_localization VALUES ('f6330f03c6d07127e6d9a2ec432fa832', 'fr', '91e00e7f8d73c54fa2f80c67d3d9d5b0', 'FIELD_LABEL_UUID', 0, 'Extensible avec des codes spécifiques', NULL, NULL, NULL, '2019-07-30 14:35:08.217', NULL);\n" + "INSERT INTO public.reg_localization VALUES ('926dcb2dc8cbeee9fb94b3fb083ef46c', 'fr', '91e00e7f8d73c54fa2f80c67d3d9d5b0', 'FIELD_DEFINITION_UUID', 0, '<p>La liste de codes ne peut être étendue qu''avec des codes spécifiques: les codes autorisés sont les codes existants et de nouveaux codes spécifiques définis par des fournisseurs de données.</p>', NULL, NULL, NULL, '2019-07-30 14:35:08.219', NULL);\n" + "INSERT INTO public.reg_localization VALUES ('ad90068e710791963b723a716ed0a722', 'hr', '91e00e7f8d73c54fa2f80c67d3d9d5b0', 'FIELD_LABEL_UUID', 0, 'Proširivo užim skupom vrijednosti', NULL, NULL, NULL, '2019-07-30 14:35:08.222', NULL);\n" + "INSERT INTO public.reg_localization VALUES ('c4b48d461d1a5ccad9eb3477939c1a5a', 'hr', '91e00e7f8d73c54fa2f80c67d3d9d5b0', 'FIELD_DEFINITION_UUID', 0, '<p>Kodna lista je proširiva samo užim skupom vrijednosti specificiranim u ovom registru ili definiranim od strane pružatelja podataka.</p>', NULL, NULL, NULL, '2019-07-30 14:35:08.224', NULL);\n" + "INSERT INTO public.reg_localization VALUES ('7e6e0e4074f4375470e9cb213d750024', 'it', '91e00e7f8d73c54fa2f80c67d3d9d5b0', 'FIELD_LABEL_UUID', 0, 'Estendibile con valori ristretti', NULL, NULL, NULL, '2019-07-30 14:35:08.227', NULL);\n" + "INSERT INTO public.reg_localization VALUES ('bd086cc3cd4c5e79f6e74e56216fe3b6', 'it', '91e00e7f8d73c54fa2f80c67d3d9d5b0', 'FIELD_DEFINITION_UUID', 0, '<p>L''elenco dei codici può essere esteso solo con valori più stretti, cioè i suoi valori consentiti comprendono i valori indicati in questo registro e valori più stretti definiti dal provider di dati.</p>', NULL, NULL, NULL, '2019-07-30 14:35:08.231', NULL);\n" + "INSERT INTO public.reg_localization VALUES ('7c786947045885937581227595386598', 'lv', '91e00e7f8d73c54fa2f80c67d3d9d5b0', 'FIELD_LABEL_UUID', 0, 'Paplašināms ar ierobežotām vērtībām', NULL, NULL, NULL, '2019-07-30 14:35:08.233', NULL);\n" + "INSERT INTO public.reg_localization VALUES ('2e33cddb1e10423103bfe23509d32b50', 'lv', '91e00e7f8d73c54fa2f80c67d3d9d5b0', 'FIELD_DEFINITION_UUID', 0, '<p>Kodu sarakstu var paplašināt tikai ar ierobežotām vērtībām, t.i., tā atļautās vērtības aptver šajā reģistrā iekļautās vērtības un ierobežotas datu sniedzēja definētas vērtības.</p>', NULL, NULL, NULL, '2019-07-30 14:35:08.236', NULL);\n" + "INSERT INTO public.reg_localization VALUES ('b5747e085e993fdf20ffffeba43bed62', 'lt', '91e00e7f8d73c54fa2f80c67d3d9d5b0', 'FIELD_LABEL_UUID', 0, 'Plečiamas konkretesnėmis reikšmėmis', NULL, NULL, NULL, '2019-07-30 14:35:08.238', NULL);\n" + "INSERT INTO public.reg_localization VALUES ('1be1d12115d948f5af6ee0708d7a89bd', 'lt', '91e00e7f8d73c54fa2f80c67d3d9d5b0', 'FIELD_DEFINITION_UUID', 0, '<p>Kodų sąrašas gali būti papildytas tik žemesnio lygmens reikšmėmis, t.y., leidžiamos reikšmės apima registre esančias ir duomenų teikėjo nurodytas reikšmes, jei jos yra konkretesnės už registre esančias reikšmes (jas patikslina).</p>', NULL, NULL, NULL, '2019-07-30 14:35:08.241', NULL);\n" + "INSERT INTO public.reg_localization VALUES ('2ee5cafab646da8412f18ecc567a6025', 'hu', '91e00e7f8d73c54fa2f80c67d3d9d5b0', 'FIELD_LABEL_UUID', 0, 'Az értékek szűkítése elfogadott', NULL, NULL, NULL, '2019-07-30 14:35:08.244', NULL);\n" + "INSERT INTO public.reg_localization VALUES ('6a11db7c1224bdd03e98220cc4964113', 'hu', '91e00e7f8d73c54fa2f80c67d3d9d5b0', 'FIELD_DEFINITION_UUID', 0, '<p>A kódlistához az adatszolgáltató olyan értékeket tehet hozzá, melyek szűkítik az eredeti értékek fogalmát.</p>', NULL, NULL, NULL, '2019-07-30 14:35:08.247', NULL);\n" + "INSERT INTO public.reg_localization VALUES ('2d621e6367a6d9f0a6ee1a8ad4c37e79', 'mt', '91e00e7f8d73c54fa2f80c67d3d9d5b0', 'FIELD_LABEL_UUID', 0, 'Estensibbli b''valuri idjaq', NULL, NULL, NULL, '2019-07-30 14:35:08.249', NULL);\n" + "INSERT INTO public.reg_localization VALUES ('c2d1fe890a89fc26be68264d3bef4120', 'mt', '91e00e7f8d73c54fa2f80c67d3d9d5b0', 'FIELD_DEFINITION_UUID', 0, '<p>Il-lista tal-koriċi tista'' tiġi estiża biss b''valuri idjaq, jiġifieri l-valuri permessi tagħha jinkludu l-valuri speċifikati f''dan ir-reġistru u valuri idjaq definiti mill-fornituri tad-dejta.</p>', NULL, NULL, NULL, '2019-07-30 14:35:08.252', NULL);\n" + "INSERT INTO public.reg_localization VALUES ('61b8e0e60e20cca39b39682327496cdc', 'nl', '91e00e7f8d73c54fa2f80c67d3d9d5b0', 'FIELD_LABEL_UUID', 0, 'Uitbreidbaar met meer beperkende waarden', NULL, NULL, NULL, '2019-07-30 14:35:08.255', NULL);\n" + "INSERT INTO public.reg_localization VALUES ('e2338ce9bbe7533c2e2a8ab6c75ab379', 'nl', '91e00e7f8d73c54fa2f80c67d3d9d5b0', 'FIELD_DEFINITION_UUID', 0, '<p>De codelijst kan enkel worden uitgebreid met nauwere waarden, met andere woorden de toegstane waarden zijn deze gespecifieerd in dit register plus de nauwere waarden gedefinieerd door gegevens beheerders.</p>', NULL, NULL, NULL, '2019-07-30 14:35:08.257', NULL);\n" + "INSERT INTO public.reg_localization VALUES ('e523c811f21f276725fec878996644ed', 'pl', '91e00e7f8d73c54fa2f80c67d3d9d5b0', 'FIELD_LABEL_UUID', 0, 'Rozszerzalny z węższymi wartościami', NULL, NULL, NULL, '2019-07-30 14:35:08.26', NULL);\n" + "INSERT INTO public.reg_localization VALUES ('c572a70e1c259f2d4df4def140c26681', 'pl', '91e00e7f8d73c54fa2f80c67d3d9d5b0', 'FIELD_DEFINITION_UUID', 0, '<p>Lista kodów może zostać jedynie rozszerzona z węższymi wartościami, to znaczy, że dozwolone wartości zawierają wartości określone w tym wykazie oraz zawężone wartości zdefiniowane przez dostawców danych.</p>', NULL, NULL, NULL, '2019-07-30 14:35:08.262', NULL);\n" + "INSERT INTO public.reg_localization VALUES ('5efb291a5bd9fbb386197d17c2c666f1', 'pt', '91e00e7f8d73c54fa2f80c67d3d9d5b0', 'FIELD_LABEL_UUID', 0, 'Extensível com valores mais restritos', NULL, NULL, NULL, '2019-07-30 14:35:08.265', NULL);\n" + "INSERT INTO public.reg_localization VALUES ('7adfa713c49549882e129a507df1d15c', 'pt', '91e00e7f8d73c54fa2f80c67d3d9d5b0', 'FIELD_DEFINITION_UUID', 0, '<p>A lista de códigos só pode ser alargada com valores mais restritos, ou seja, os valores permitidos compreendem os valores especificados neste registo e os valores mais estreitos definidos nos provedores de dados.</p>', NULL, NULL, NULL, '2019-07-30 14:35:08.267', NULL);\n" + "INSERT INTO public.reg_localization VALUES ('46402f09ef9a7ee15147fc5dc0e512bf', 'ro', '91e00e7f8d73c54fa2f80c67d3d9d5b0', 'FIELD_LABEL_UUID', 0, 'Extensibilă cu valori mai restrânse', NULL, NULL, NULL, '2019-07-30 14:35:08.27', NULL);\n" + "INSERT INTO public.reg_localization VALUES ('a688f9d76f1a225697d4f47f93f1980a', 'ro', '91e00e7f8d73c54fa2f80c67d3d9d5b0', 'FIELD_DEFINITION_UUID', 0, '<p>Lista de coduri pot fi extinsă doar cu valori mai restrânse, adică valorile sale permise cuprind valorile specificate în registru și valori înguste definite de furnizorii de date.</p>', NULL, NULL, NULL, '2019-07-30 14:35:08.273', NULL);\n" + "INSERT INTO public.reg_localization VALUES ('d80593eb4c75bdd73dad0dc5caf47796', 'sk', '91e00e7f8d73c54fa2f80c67d3d9d5b0', 'FIELD_LABEL_UUID', 0, 'Rozšíriteľný s užšími (podrobnejšími) hodnotami', NULL, NULL, NULL, '2019-07-30 14:35:08.275', NULL);\n" + "INSERT INTO public.reg_localization VALUES ('3677c233d6b05ad32b9a2358182121fe', 'sk', '91e00e7f8d73c54fa2f80c67d3d9d5b0', 'FIELD_DEFINITION_UUID', 0, '<p>Zoznam kódov (číselník) možno rozšíriť iba s hodnotami užšieho významu, t.j. jeho povolené hodnoty zahŕňajú hodnoty uvedené v tomto registri ako aj užšie hodnoty zadefinované poskytovateľmi údajov</p>', NULL, NULL, NULL, '2019-07-30 14:35:08.278', NULL);\n" + "INSERT INTO public.reg_localization VALUES ('5e6b48e52f4afbf1e05a2915c42cc982', 'sl', '91e00e7f8d73c54fa2f80c67d3d9d5b0', 'FIELD_LABEL_UUID', 0, 'Dopolnjevanje je mogoče z omejenimi vrednostmi', NULL, NULL, NULL, '2019-07-30 14:35:08.281', NULL);\n" + "INSERT INTO public.reg_localization VALUES ('4ff7f568e415ea9b36bf7bf44e1fadf4', 'sl', '91e00e7f8d73c54fa2f80c67d3d9d5b0', 'FIELD_DEFINITION_UUID', 0, '<p>Dopolnjevanje seznama oznak je mogoče le z omejenimi vrednostmi, t.j. dovoljene vrednosti so tiste navedene v registru in vrednosti, ki so bolj omejene od navedenih in ki jih opredeli ponudnik podatkov.</p>', NULL, NULL, NULL, '2019-07-30 14:35:08.283', NULL);\n" + "INSERT INTO public.reg_localization VALUES ('71a00da518b8054c63ccf262d7077960', 'fi', '91e00e7f8d73c54fa2f80c67d3d9d5b0', 'FIELD_LABEL_UUID', 0, 'Laajennettavissa yksityiskohtaisemmilla koodiarvoilla', NULL, NULL, NULL, '2019-07-30 14:35:08.286', NULL);\n" + "INSERT INTO public.reg_localization VALUES ('a7888e278954567a39dfe44bdb624e13', 'fi', '91e00e7f8d73c54fa2f80c67d3d9d5b0', 'FIELD_DEFINITION_UUID', 0, '<p>Koodiluetteloa voidaan laajentaa ainoastaan yksityiskohtaisemmilla koodiarvoilla. Koodiluettelossa siis sallitaan tässä rekisterissä määritellyt koodiarvot ja niitä yksityiskohtaisemmat tiedontuottajien määrittelemät koodiarvot.</p>', NULL, NULL, NULL, '2019-07-30 14:35:08.288', NULL);\n" + "INSERT INTO public.reg_localization VALUES ('982d4f69a6096487493ac852f0b95790', 'sv', '91e00e7f8d73c54fa2f80c67d3d9d5b0', 'FIELD_LABEL_UUID', 0, 'Utökningbar inom befintliga värdedomäner (specialisering)', NULL, NULL, NULL, '2019-07-30 14:35:08.29', NULL);\n" + "INSERT INTO public.reg_localization VALUES ('5dae549e0c70666cd3b9bc0c4ca03057', 'sv', '91e00e7f8d73c54fa2f80c67d3d9d5b0', 'FIELD_DEFINITION_UUID', 0, '<p>Kodlistan kan bara utökas inom befintliga värdedomäner, dvs. värden måste vara inom tillåtna värden i detta register och inom de av dataleverantörerna definierade värdedomänerna.</p>', NULL, NULL, NULL, '2019-07-30 14:35:08.293', NULL);"; public MigrateExtensiblityAndGovernanceLevel(MigrationManager migrationManager) { this.migrationManager = migrationManager; this.entityManagerRe3gistry2 = migrationManager.getEntityManagerRe3gistry2(); this.entityManagerRe3gistry2Migration = migrationManager.getEntityManagerRe3gistry2Migration(); this.logger = migrationManager.getLogger(); } public void startMigrationExtensiblityAndGovernanceLevel() throws Exception { ArrayList<RegItem> itemsToIndexSOLR = new ArrayList<>(); int DATAPROCEDUREORDER = migrationManager.getProcedureorder(); boolean commit = true; /** * migrate Register item class */ try { String USERMIGRATION_UUID = migrationManager.getMigrationUser().getUuid(); Query queryRegistry = entityManagerRe3gistry2Migration.createNamedQuery("Registry.findAll", Registry.class); Registry oldRegistry = ((Registry) queryRegistry.getResultList().get(0)); RegItemclasstypeManager regItemclasstypeManager = new RegItemclasstypeManager(entityManagerRe3gistry2); RegItemclasstype regItemclasstypeRegistry = regItemclasstypeManager.getByLocalid("registry"); String REGISTRY_ITEMCLASS_UUID = RegItemclassUuidHelper.getUuid(oldRegistry.getUriname(), null, regItemclasstypeRegistry); RegItemclassManager regItemclassManager = new RegItemclassManager(entityManagerRe3gistry2); RegItemclass registryItemClass = regItemclassManager.get(REGISTRY_ITEMCLASS_UUID); RegItemManager regItemManager = new RegItemManager(entityManagerRe3gistry2); RegItem newRegistry = regItemManager.getByLocalidAndRegItemClass(oldRegistry.getUriname(), regItemclassManager.get(REGISTRY_ITEMCLASS_UUID)); String REGISTRY_UUID = newRegistry.getUuid(); String BASE_URI_REGISTRY = registryItemClass.getBaseuri() + "/" + newRegistry.getLocalid(); /** * get fields */ RegFieldManager regFieldManager = new RegFieldManager(entityManagerRe3gistry2); String FIELD_LABEL_UUID = regFieldManager.getByLocalid(BaseConstants.KEY_FIELD_MANDATORY_LABEL_LOCALID).getUuid(); String FIELD_CONTENTSUMMARY_UUID = regFieldManager.getByLocalid(BaseConstants.KEY_FIELD_MANDATORY_CONTENTSUMMARY_LOCALID).getUuid(); RegInstallationHandler regInstallationHandler = new RegInstallationHandler(entityManagerRe3gistry2); RegField regFieldDefinition; try { regFieldDefinition = regFieldManager.getByLocalid(BaseConstants.KEY_FIELD_DEFINITION_LOCALID); } catch (Exception ex) { regFieldDefinition = regInstallationHandler.createRegFielAndFieldLocalizationdByName(BaseConstants.KEY_FIELD_DEFINITION_LOCALID, BaseConstants.KEY_FIELDTYPE_LONGTEXT_UUID, null, commit); } String FIELD_DEFINITION_UUID = regFieldDefinition.getUuid(); String FIELD_REGISTRYMANAGER_UUID = regFieldManager.getByLocalid(BaseConstants.KEY_FIELD_MANDATORY_REGISTRYMANAGER).getUuid(); String FIELD_REGISTERMANAGER_UUID = regFieldManager.getByLocalid(BaseConstants.KEY_FIELD_MANDATORY_REGISTERMANAGER).getUuid(); String FIELD_CONTENTBODY_UUID = regFieldManager.getByLocalid(BaseConstants.KEY_FIELD_MANDATORY_CONTROLBODY).getUuid(); String FIELD_SUBMITTINGORGANIZATION_UUID = regFieldManager.getByLocalid(BaseConstants.KEY_FIELD_MANDATORY_SUBMITTINGORGANIZATIONS).getUuid(); String FIELD_REGISTEROWNER_UUID = regFieldManager.getByLocalid(BaseConstants.KEY_FIELD_MANDATORY_REGISTEROWNER).getUuid(); RegField regFieldStatus; try { regFieldStatus = regFieldManager.getByLocalid(BaseConstants.KEY_FIELD_MANDATORY_STATUS_LOCALID); } catch (Exception ex) { regFieldStatus = regInstallationHandler.createRegFielAndFieldLocalizationdByName(BaseConstants.KEY_FIELD_MANDATORY_STATUS_LOCALID, BaseConstants.KEY_FIELDTYPE_STATUS_UUID, null, commit); } String FIELD_STATUS_UUID = regFieldStatus.getUuid(); RegGroupManager regGroupManager = new RegGroupManager(entityManagerRe3gistry2); String GROUP_REGISTERMANAGER_UUID = ((RegGroup) regGroupManager.getByLocalid(BaseConstants.KEY_ROLE_REGISTERMANAGER)).getUuid(); String GROUP_REGISTEROWNER_UUID = ((RegGroup) regGroupManager.getByLocalid(BaseConstants.KEY_ROLE_REGISTEROWNER)).getUuid(); String GROUP_CONTENTBODY_UUID = ((RegGroup) regGroupManager.getByLocalid(BaseConstants.KEY_ROLE_CONTROLBODY)).getUuid(); String GROUP_SUBMITTINGORGANIZATION_UUID = ((RegGroup) regGroupManager.getByLocalid(BaseConstants.KEY_ROLE_SUBMITTINGORGANIZATION)).getUuid(); try { if (!entityManagerRe3gistry2.getTransaction().isActive()) { entityManagerRe3gistry2.getTransaction().begin(); } entityManagerRe3gistry2.createNativeQuery(QUERY_ITEMCLASS_1 .replace("BASE_URI_REGISTRY", BASE_URI_REGISTRY) .replace("DATAPROCEDUREORDER", Integer.toString(DATAPROCEDUREORDER)) .replace("REGISTRY_ITEMCLASS_UUID", REGISTRY_ITEMCLASS_UUID)) .executeUpdate(); DATAPROCEDUREORDER++; entityManagerRe3gistry2.createNativeQuery(QUERY_ITEMCLASS_2 .replace("BASE_URI_REGISTRY", BASE_URI_REGISTRY) .replace("DATAPROCEDUREORDER", Integer.toString(DATAPROCEDUREORDER)) .replace("REGISTRY_ITEMCLASS_UUID", REGISTRY_ITEMCLASS_UUID)) .executeUpdate(); DATAPROCEDUREORDER++; entityManagerRe3gistry2.createNativeQuery(QUERY_ITEMCLASS_3 .replace("BASE_URI_REGISTRY", BASE_URI_REGISTRY) .replace("DATAPROCEDUREORDER", Integer.toString(DATAPROCEDUREORDER)) .replace("REGISTRY_ITEMCLASS_UUID", REGISTRY_ITEMCLASS_UUID)) .executeUpdate(); DATAPROCEDUREORDER++; entityManagerRe3gistry2.createNativeQuery(QUERY_ITEMCLASS_4 .replace("BASE_URI_REGISTRY", BASE_URI_REGISTRY) .replace("DATAPROCEDUREORDER", Integer.toString(DATAPROCEDUREORDER)) .replace("REGISTRY_ITEMCLASS_UUID", REGISTRY_ITEMCLASS_UUID)) .executeUpdate(); entityManagerRe3gistry2.createNativeQuery(QUERY_FIELDMAPPING .replace("FIELD_CONTENTBODY_UUID", FIELD_CONTENTBODY_UUID) .replace("FIELD_REGISTERMANAGER_UUID", FIELD_REGISTERMANAGER_UUID) .replace("FIELD_SUBMITTINGORGANIZATION_UUID", FIELD_SUBMITTINGORGANIZATION_UUID) .replace("FIELD_CONTENTSUMMARY_UUID", FIELD_CONTENTSUMMARY_UUID) .replace("FIELD_LABEL_UUID", FIELD_LABEL_UUID) .replace("FIELD_STATUS_UUID", FIELD_STATUS_UUID) .replace("FIELD_REGISTEROWNER_UUID", FIELD_REGISTEROWNER_UUID) .replace("FIELD_DEFINITION_UUID", FIELD_DEFINITION_UUID)) .executeUpdate(); entityManagerRe3gistry2.createNativeQuery(QUERY_ITEM .replace("USERMIGRATION_UUID", USERMIGRATION_UUID)) .executeUpdate(); entityManagerRe3gistry2.createNativeQuery(QUERY_ITEM_GROUP_ROLE .replace("GROUP_REGISTEROWNER_UUID", GROUP_REGISTEROWNER_UUID) .replace("GROUP_REGISTERMANAGER_UUID", GROUP_REGISTERMANAGER_UUID) .replace("GROUP_CONTENTBODY_UUID", GROUP_CONTENTBODY_UUID) .replace("GROUP_SUBMITTINGORGANIZATION_UUID", GROUP_SUBMITTINGORGANIZATION_UUID)) .executeUpdate(); entityManagerRe3gistry2.createNativeQuery(QUERY_RELATION .replace("REGISTRY_UUID", REGISTRY_UUID)) .executeUpdate(); entityManagerRe3gistry2.createNativeQuery(QUERY_GOVERNANCELEVEL .replace("FIELD_LABEL_UUID", FIELD_LABEL_UUID) .replace("FIELD_CONTENTSUMMARY_UUID", FIELD_CONTENTSUMMARY_UUID) .replace("FIELD_DEFINITION_UUID", FIELD_DEFINITION_UUID)) .executeUpdate(); entityManagerRe3gistry2.createNativeQuery(QUERY_EXTENSIBILITY .replace("FIELD_LABEL_UUID", FIELD_LABEL_UUID) .replace("FIELD_CONTENTSUMMARY_UUID", FIELD_CONTENTSUMMARY_UUID) .replace("FIELD_DEFINITION_UUID", FIELD_DEFINITION_UUID)) .executeUpdate(); entityManagerRe3gistry2.createNativeQuery(QUERY_EXTENSIBILITY_1 .replace("FIELD_LABEL_UUID", FIELD_LABEL_UUID) .replace("FIELD_CONTENTSUMMARY_UUID", FIELD_CONTENTSUMMARY_UUID) .replace("FIELD_DEFINITION_UUID", FIELD_DEFINITION_UUID)) .executeUpdate(); if (commit) { if (!entityManagerRe3gistry2.getTransaction().isActive()) { entityManagerRe3gistry2.getTransaction().begin(); } entityManagerRe3gistry2.getTransaction().commit(); } } catch (Exception ex) { logger.error(ex.getMessage(), ex); throw new Exception(ex.getMessage()); } for (String itemUuid : itemsUUID) { itemsToIndexSOLR.add(regItemManager.get(itemUuid)); } itemsToIndexSOLR.forEach((regItem) -> { try { SolrHandler.indexSingleItem(regItem); } catch (Exception e) { logger.error("@ MigrateRegister.MigrateExtensiblityAndGovernanceLevel: Solr indexing error.", e); } }); } catch (Exception exe) { logger.error(exe.getMessage()); throw new Exception(exe.getMessage()); } } }
ec-jrc/re3gistry
sources/Re3gistry2Migration/src/main/java/eu/europa/ec/re3gistry2/migration/manager/MigrateExtensiblityAndGovernanceLevel.java
1,063
package Client.ui.localization; import java.util.Arrays; import java.util.ListResourceBundle; import java.util.Locale; import Shared.commands.enums.CommandMessage; public class loc_el extends ListResourceBundle { private static final Object[][] contents = new Object[][] { { UIField.AuthTitle, "Συνδεθείτε ή εγγραφείτε"}, { UIField.Login, "Είσοδος"}, { UIField.Password, "Κωδικός πρόσβασης"}, { UIField.Register, "Εγγραφή"}, { UIField.Authorize, "Σύνδεση"}, {UIField.LoggedAs, "Είστε συνδεδεμένος ως"}, {UIField.Logout, "Αποσύνδεση"}, { UIField.Visualization, "οραματισμός"}, { UIField.TableTitle, "Πίνακας αντικειμένων"}, { UIField.NumberFormatError, "Δεν μοιάζει με αριθμό"}, { UIField.CannotBeNull, "Αυτό το πεδίο δεν μπορεί να είναι κενό ή μηδενικό"}, { UIField.DataFormatError, "Ημερομηνία σε λάθος μορφή"}, { UIField.X, "χ" }, { UIField.Y, "ψ" }, { UIField.Mass, "μάζα" }, { UIField.Save, "Αποθήκευση" }, { UIField.VisualizationTitle, "Οπτικοποίηση αντικειμένων" }, { UIField.RemoveBiggerObjects, "Αφαίρεση\n μεγαλύτερων\n αντικειμένων" }, { UIField.RemoveByKey, "Αφαίρεση\n με βάση το\n κλειδί" }, { UIField.RemoveWithBiggerKey, "Αφαίρεση με\n κλειδί μεγαλύτερο\n από το καθορ\nισμένο" }, { UIField.UpdateById, "Αντικατ\nάσταση με\n βάση το\n id" }, { UIField.UniqueDistances, "Μόνο\n μοναδικές\n αποστάσεις" }, { UIField.Add, "Προσθήκη" }, { UIField.Clear, "Καθαρισμός" }, { UIField.Delete, "Διαγραφή" }, { UIField.ReplaceIfLower, "Αντικατάσταση,\n αν το νέο αντικ\nείμενο είναι\n μικρότερο" }, { UIField.AddFilter, "Προσθήκη φίλτρου" }, { UIField.Start, "Έναρξη" }, { UIField.Stop, "Διακοπή" }, { UIField.Id, "αναγνωριστικό" }, { UIField.Key, "κλειδί" }, { UIField.Name, "όνομα" }, { UIField.CoordsX, "χ" }, { UIField.CoordsY, "ψ" }, { UIField.StartX, "αρχή_χ" }, { UIField.StartY, "αρχή_ψ" }, { UIField.StartZ, "αρχή_z" }, { UIField.StartName, "αρχή_όνομα" }, { UIField.FinishX, "τέλος_χ" }, { UIField.FinishY, "τέλος_ψ" }, { UIField.FinishZ, "τέλος_z" }, { UIField.FinishName, "τέλος_όνομα" }, { UIField.Distance, "απόσταση" }, { UIField.CreationDate, "ημερομηνία_δημιουργίας" }, { UIField.User, "χρήστης" }, { UIField.Execute, "Εκτέλεση"}, { UIField.ExecuteFile, "Εκτέλεση\n σεναρίου"}, { UIField.Radius, "ακτίνα" }, { CommandMessage.AuthorizationSuccess, "Επιτυχής εξουσιοδότηση" }, { CommandMessage.RegistrationSuccess, "Επιτυχής εγγραφή" }, { CommandMessage.UserAlreadyExists, "Αυτός ο χρήστης υπάρχει ήδη" }, { CommandMessage.UserNotExists, "Αυτός ο χρήστης δεν υπάρχει" }, { CommandMessage.UserNotAuthorized, "Ο χρήστης δεν είναι εξουσιοδοτημένος" }, { CommandMessage.IncorrectPassword, "Λανθασμένος κωδικός πρόσβασης" }, { UIField.FileName, "Όνομα αρχείου" }, { CommandMessage.UnexpectedError, "Απρόσμενο σφάλμα" }, { CommandMessage.InvalidArgument, "Μη έγκυρο %s" }, { CommandMessage.InvalidArgumentCount, "Μη έγκυρος αριθμός ορισμάτων" }, { CommandMessage.Success, "Επιτυχής εκτέλεση" }, { UIField.WriteFilterValue, "Εισαγάγετε την τιμή του φίλτρου" }, { CommandMessage.ServerNotResponded, "Ο διακομιστής δεν ανταποκρίθηκε στο αναμενόμενο χρονικό διάστημα" }, { CommandMessage.ArgumentNotPresented, "Δεν εισαγάγατε %s" }, { CommandMessage.RecursionRestricted, "Η αναδρομή είναι απαγορευμένη" }, { UIField.ServerUnavailable, "Φαίνεται ότι ο διακομιστής δεν είναι διαθέσιμος, η προσομοίωση δεν είναι δυνατή" } }; @Override public Locale getLocale(){ return new Locale("el"); } @Override protected Object[][] getContents() { return Arrays.stream(contents).peek(e -> e[0] = e[0].toString()).toArray(Object[][]::new); } @Override public String toString() { return "Ελληνικά"; } }
RAZRULETEL/Java_programming_ITMO
Lab_8/Client/ui/localization/loc_el.java