test_qgis3.py

Mario Baranzini, 2018-02-27 07:12 AM

Download (1.76 KB)

 
1
# coding: utf-8
2

    
3
from qgis.core import (
4
    QgsVectorLayerJoinInfo, QgsVectorLayer, QgsField, QgsFeature,
5
    edit, QgsProject)
6
from PyQt5.QtCore import QVariant
7

    
8
# Create layer_1
9
layer_1 = QgsVectorLayer('Point?crs=epsg:21781', 'layer_1', 'memory')
10

    
11
with edit(layer_1):
12
    layer_1.addAttribute(QgsField('id', QVariant.Int))
13
    layer_1.addAttribute(QgsField('column_a', QVariant.String))
14
    layer_1.addAttribute(QgsField('column_b', QVariant.String))
15
    feat = QgsFeature()
16
    feat.setAttributes([1, 'A1', 'B1'])
17
    layer_1.addFeature(feat)
18

    
19
# add layer to the legend
20
QgsProject.instance().addMapLayer(layer_1)
21

    
22
# Create layer_2
23
layer_2 = QgsVectorLayer('Point?crs=epsg:21781', 'layer_2', 'memory')
24

    
25
with edit(layer_2):
26
    layer_2.addAttribute(QgsField('id', QVariant.Int))
27
    feat = QgsFeature()
28
    feat.setAttributes([1])
29
    layer_2.addFeature(feat)
30

    
31
# add layer to the legend
32
QgsProject.instance().addMapLayer(layer_2)
33

    
34
# Join the layers with the subset filds in the same order than the joined
35
# layer
36
join = QgsVectorLayerJoinInfo()
37
join.setJoinLayer(layer_1)
38
join.setJoinFieldName('id')
39
join.setTargetFieldName('id')
40
join.setJoinFieldNamesSubset(['column_a', 'column_b'])
41
layer_2.addJoin(join)
42

    
43
# Verify the result
44
assert next(layer_2.getFeatures()).attribute(
45
    'layer_1_column_a') == 'A1', 'Join (same order) Failed'
46

    
47
# Remove the join
48
layer_2.removeJoin(layer_1.id())
49

    
50
# Join the layers with the subset filds in a different order than the joined
51
# layer
52
join = QgsVectorLayerJoinInfo()
53
join.setJoinLayer(layer_1)
54

    
55
join.setJoinFieldName('id')
56
join.setTargetFieldName('id')
57
join.setJoinFieldNamesSubset(['column_b', 'column_a'])
58
layer_2.addJoin(join)
59

    
60
# Verify the result
61
assert next(layer_2.getFeatures()).attribute(
62
    'layer_1_column_a') == 'A1', 'Join (different order) Failed'