github.com/cozy/cozy-stack@v0.0.0-20240603063001-31110fa4cae1/tests/system/lib/couch.rb (about)

     1  class Couch
     2    def initialize(opts = {})
     3      @url = opts.delete(:url) || ENV['COZY_COUCHDB_URL'] || "http://localhost:5984"
     4      @client = RestClient::Resource.new @url, opts
     5    end
     6  
     7    def clean_test
     8      instances.each do |inst|
     9        next unless inst["domain"] =~ /test[^a-zA-Z]/
    10        all_dbs.grep(/#{prefix inst['domain']}/).each do |db|
    11          @client["/#{db.sub '/', '%2f'}"].delete
    12        end
    13        params = { params: { rev: inst["_rev"] } }
    14        @client["/global%2Finstances/#{inst['_id']}"].delete params
    15      end
    16    end
    17  
    18    def all_dbs
    19      JSON.parse @client["/_all_dbs"].get.body
    20    end
    21  
    22    def instances
    23      params = { params: { include_docs: true } }
    24      res = JSON.parse @client["/global%2Finstances/_all_docs"].get(params).body
    25      res["rows"].map { |row| row["doc"] }
    26    rescue RestClient::NotFound
    27      []
    28    end
    29  
    30    def prefix(db)
    31      "cozy" + Digest::SHA256.hexdigest(db)[0...32]
    32    end
    33  
    34    def get_doc(domain, doctype, id, opts = {})
    35      params = { params: opts }
    36      doctype = doctype.gsub(/\W/, '-')
    37      JSON.parse @client["/#{prefix domain}%2F#{doctype}/#{id}"].get(params).body
    38    end
    39  
    40    def create_named_doc(domain, doctype, id, doc)
    41      opts = {
    42        content_type: "application/json"
    43      }
    44      doctype = doctype.gsub(/\W/, '-')
    45      @client["/#{prefix domain}%2F#{doctype}/#{id}"].put(doc.to_json, opts)
    46    end
    47  
    48    def update_doc(domain, doctype, doc)
    49      opts = {
    50        content_type: "application/json"
    51      }
    52      id = doc["_id"].gsub("/", "%2F")
    53      doctype = doctype.gsub(/\W/, '-')
    54      @client["/#{prefix domain}%2F#{doctype}/#{id}"].put(doc.to_json, opts)
    55    end
    56  
    57    def all_docs(domain, doctype)
    58      doctype = doctype.gsub(/\W/, '-')
    59      res = @client["/#{prefix domain}%2F#{doctype}/_all_docs?include_docs=true"].get
    60      rows = JSON.parse(res.body)["rows"]
    61      rows.map { |r| r["doc"] }
    62    end
    63  
    64    def find_conflicts(domain, doctype)
    65      opts = {
    66        content_type: "application/json"
    67      }
    68      body = {
    69        selector: {
    70          "_conflicts": {
    71            "$exists": true
    72          }
    73        },
    74        "conflicts": true
    75      }
    76      doctype = doctype.gsub(/\W/, '-')
    77      res = @client["/#{prefix domain}%2F#{doctype}/_find"].post(body.to_json, opts)
    78      JSON.parse(res.body)["docs"]
    79    end
    80  end